es6.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029
  1. 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};
  2. 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)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers;
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers;
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. var finalVertexCode;
  216. this._loadVertexShaderAsync(vertexSource)
  217. .then(function (vertexCode) {
  218. return _this._processIncludesAsync(vertexCode);
  219. })
  220. .then(function (vertexCodeWithIncludes) {
  221. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  222. return _this._loadFragmentShaderAsync(fragmentSource);
  223. })
  224. .then(function (fragmentCode) {
  225. return _this._processIncludesAsync(fragmentCode);
  226. })
  227. .then(function (fragmentCodeWithIncludes) {
  228. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  229. if (baseName) {
  230. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  231. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  232. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  233. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  234. }
  235. else {
  236. _this._vertexSourceCode = finalVertexCode;
  237. _this._fragmentSourceCode = migratedFragmentCode;
  238. }
  239. _this._prepareEffect();
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @ignore */
  348. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. return Promise.resolve(vertexCode);
  354. }
  355. }
  356. // Base64 encoded ?
  357. if (vertex.substr(0, 7) === "base64:") {
  358. var vertexBinary = window.atob(vertex.substr(7));
  359. return Promise.resolve(vertexBinary);
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. return Promise.resolve(fragmentCode);
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (fragment.substr(0, 7) === "base64:") {
  386. var fragmentBinary = window.atob(fragment.substr(7));
  387. return Promise.resolve(fragmentBinary);
  388. }
  389. // Is in local store ?
  390. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  391. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  392. }
  393. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  394. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  395. }
  396. var fragmentShaderUrl;
  397. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  398. fragmentShaderUrl = fragment;
  399. }
  400. else {
  401. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  402. }
  403. // Fragment shader
  404. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  405. };
  406. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  407. // Rebuild shaders source code
  408. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  409. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  410. vertexCode = prefix + vertexCode;
  411. fragmentCode = prefix + fragmentCode;
  412. // Number lines of shaders source code
  413. var i = 2;
  414. var regex = /\n/gm;
  415. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. i = 2;
  417. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  418. // Dump shaders name and formatted source code
  419. if (this.name.vertexElement) {
  420. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  421. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  422. }
  423. else if (this.name.vertex) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  426. }
  427. else {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  430. }
  431. };
  432. ;
  433. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  434. var preparedSourceCode = this._processPrecision(sourceCode);
  435. if (this._engine.webGLVersion == 1) {
  436. return preparedSourceCode;
  437. }
  438. // Already converted
  439. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  440. return preparedSourceCode.replace("#version 300 es", "");
  441. }
  442. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  443. // Remove extensions
  444. // #extension GL_OES_standard_derivatives : enable
  445. // #extension GL_EXT_shader_texture_lod : enable
  446. // #extension GL_EXT_frag_depth : enable
  447. // #extension GL_EXT_draw_buffers : require
  448. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  449. var result = preparedSourceCode.replace(regex, "");
  450. // Migrate to GLSL v300
  451. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  452. result = result.replace(/attribute[ \t]/g, "in ");
  453. result = result.replace(/[ \t]attribute/g, " in");
  454. if (isFragment) {
  455. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  456. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  457. result = result.replace(/texture2D\s*\(/g, "texture(");
  458. result = result.replace(/textureCube\s*\(/g, "texture(");
  459. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  460. result = result.replace(/gl_FragColor/g, "glFragColor");
  461. result = result.replace(/gl_FragData/g, "glFragData");
  462. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  463. }
  464. return result;
  465. };
  466. Effect.prototype._processIncludesAsync = function (sourceCode) {
  467. var _this = this;
  468. return new Promise(function (resolve, reject) {
  469. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  470. var match = regex.exec(sourceCode);
  471. var returnValue = sourceCode;
  472. while (match != null) {
  473. var includeFile = match[1];
  474. // Uniform declaration
  475. if (includeFile.indexOf("__decl__") !== -1) {
  476. includeFile = includeFile.replace(/__decl__/, "");
  477. if (_this._engine.supportsUniformBuffers) {
  478. includeFile = includeFile.replace(/Vertex/, "Ubo");
  479. includeFile = includeFile.replace(/Fragment/, "Ubo");
  480. }
  481. includeFile = includeFile + "Declaration";
  482. }
  483. if (Effect.IncludesShadersStore[includeFile]) {
  484. // Substitution
  485. var includeContent = Effect.IncludesShadersStore[includeFile];
  486. if (match[2]) {
  487. var splits = match[3].split(",");
  488. for (var index = 0; index < splits.length; index += 2) {
  489. var source = new RegExp(splits[index], "g");
  490. var dest = splits[index + 1];
  491. includeContent = includeContent.replace(source, dest);
  492. }
  493. }
  494. if (match[4]) {
  495. var indexString = match[5];
  496. if (indexString.indexOf("..") !== -1) {
  497. var indexSplits = indexString.split("..");
  498. var minIndex = parseInt(indexSplits[0]);
  499. var maxIndex = parseInt(indexSplits[1]);
  500. var sourceIncludeContent = includeContent.slice(0);
  501. includeContent = "";
  502. if (isNaN(maxIndex)) {
  503. maxIndex = _this._indexParameters[indexSplits[1]];
  504. }
  505. for (var i = minIndex; i < maxIndex; i++) {
  506. if (!_this._engine.supportsUniformBuffers) {
  507. // Ubo replacement
  508. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  509. return p1 + "{X}";
  510. });
  511. }
  512. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  513. }
  514. }
  515. else {
  516. if (!_this._engine.supportsUniformBuffers) {
  517. // Ubo replacement
  518. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  519. return p1 + "{X}";
  520. });
  521. }
  522. includeContent = includeContent.replace(/\{X\}/g, indexString);
  523. }
  524. }
  525. // Replace
  526. returnValue = returnValue.replace(match[0], includeContent);
  527. }
  528. else {
  529. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  530. _this._engine._loadFileAsync(includeShaderUrl)
  531. .then(function (fileContent) {
  532. Effect.IncludesShadersStore[includeFile] = fileContent;
  533. return _this._processIncludesAsync(returnValue);
  534. })
  535. .then(function (returnValue) {
  536. resolve(returnValue);
  537. });
  538. return;
  539. }
  540. match = regex.exec(sourceCode);
  541. }
  542. resolve(returnValue);
  543. });
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else {
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets an array of textures on the engine to be used in the shader.
  714. * @param channel Name of the variable.
  715. * @param textures Textures to set.
  716. */
  717. Effect.prototype.setTextureArray = function (channel, textures) {
  718. if (this._samplers.indexOf(channel + "Ex") === -1) {
  719. var initialPos = this._samplers.indexOf(channel);
  720. for (var index = 1; index < textures.length; index++) {
  721. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  722. }
  723. }
  724. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  725. };
  726. /**
  727. * 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)
  728. * @param channel Name of the sampler variable.
  729. * @param postProcess Post process to get the input texture from.
  730. */
  731. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  732. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  733. };
  734. /** @ignore */
  735. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  736. var cache = this._valueCache[uniformName];
  737. var flag = matrix.updateFlag;
  738. if (cache !== undefined && cache === flag) {
  739. return false;
  740. }
  741. this._valueCache[uniformName] = flag;
  742. return true;
  743. };
  744. /** @ignore */
  745. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  746. var cache = this._valueCache[uniformName];
  747. if (!cache) {
  748. cache = [x, y];
  749. this._valueCache[uniformName] = cache;
  750. return true;
  751. }
  752. var changed = false;
  753. if (cache[0] !== x) {
  754. cache[0] = x;
  755. changed = true;
  756. }
  757. if (cache[1] !== y) {
  758. cache[1] = y;
  759. changed = true;
  760. }
  761. return changed;
  762. };
  763. /** @ignore */
  764. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  765. var cache = this._valueCache[uniformName];
  766. if (!cache) {
  767. cache = [x, y, z];
  768. this._valueCache[uniformName] = cache;
  769. return true;
  770. }
  771. var changed = false;
  772. if (cache[0] !== x) {
  773. cache[0] = x;
  774. changed = true;
  775. }
  776. if (cache[1] !== y) {
  777. cache[1] = y;
  778. changed = true;
  779. }
  780. if (cache[2] !== z) {
  781. cache[2] = z;
  782. changed = true;
  783. }
  784. return changed;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y, z, w];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. if (cache[2] !== z) {
  804. cache[2] = z;
  805. changed = true;
  806. }
  807. if (cache[3] !== w) {
  808. cache[3] = w;
  809. changed = true;
  810. }
  811. return changed;
  812. };
  813. /**
  814. * Binds a buffer to a uniform.
  815. * @param buffer Buffer to bind.
  816. * @param name Name of the uniform variable to bind to.
  817. */
  818. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  819. var bufferName = this._uniformBuffersNames[name];
  820. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  821. return;
  822. }
  823. Effect._baseCache[bufferName] = buffer;
  824. this._engine.bindUniformBufferBase(buffer, bufferName);
  825. };
  826. /**
  827. * Binds block to a uniform.
  828. * @param blockName Name of the block to bind.
  829. * @param index Index to bind.
  830. */
  831. Effect.prototype.bindUniformBlock = function (blockName, index) {
  832. this._engine.bindUniformBlock(this._program, blockName, index);
  833. };
  834. /**
  835. * Sets an interger value on a uniform variable.
  836. * @param uniformName Name of the variable.
  837. * @param value Value to be set.
  838. * @returns this effect.
  839. */
  840. Effect.prototype.setInt = function (uniformName, value) {
  841. var cache = this._valueCache[uniformName];
  842. if (cache !== undefined && cache === value)
  843. return this;
  844. this._valueCache[uniformName] = value;
  845. this._engine.setInt(this.getUniform(uniformName), value);
  846. return this;
  847. };
  848. /**
  849. * Sets an int array on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param array array to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setIntArray = function (uniformName, array) {
  855. this._valueCache[uniformName] = null;
  856. this._engine.setIntArray(this.getUniform(uniformName), array);
  857. return this;
  858. };
  859. /**
  860. * 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)
  861. * @param uniformName Name of the variable.
  862. * @param array array to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setIntArray2 = function (uniformName, array) {
  866. this._valueCache[uniformName] = null;
  867. this._engine.setIntArray2(this.getUniform(uniformName), array);
  868. return this;
  869. };
  870. /**
  871. * 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)
  872. * @param uniformName Name of the variable.
  873. * @param array array to be set.
  874. * @returns this effect.
  875. */
  876. Effect.prototype.setIntArray3 = function (uniformName, array) {
  877. this._valueCache[uniformName] = null;
  878. this._engine.setIntArray3(this.getUniform(uniformName), array);
  879. return this;
  880. };
  881. /**
  882. * 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)
  883. * @param uniformName Name of the variable.
  884. * @param array array to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setIntArray4 = function (uniformName, array) {
  888. this._valueCache[uniformName] = null;
  889. this._engine.setIntArray4(this.getUniform(uniformName), array);
  890. return this;
  891. };
  892. /**
  893. * Sets an float array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setFloatArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setFloatArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * 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)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * 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)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * 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)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * 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)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * 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)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * 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)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets matrices on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param matrices matrices to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setMatrices = function (uniformName, matrices) {
  987. if (!matrices) {
  988. return this;
  989. }
  990. this._valueCache[uniformName] = null;
  991. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  992. return this;
  993. };
  994. /**
  995. * Sets matrix on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrix matrix to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1001. if (this._cacheMatrix(uniformName, matrix)) {
  1002. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1003. }
  1004. return this;
  1005. };
  1006. /**
  1007. * 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)
  1008. * @param uniformName Name of the variable.
  1009. * @param matrix matrix to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1019. * @param uniformName Name of the variable.
  1020. * @param matrix matrix to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets a float on a uniform variable.
  1030. * @param uniformName Name of the variable.
  1031. * @param value value to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setFloat = function (uniformName, value) {
  1035. var cache = this._valueCache[uniformName];
  1036. if (cache !== undefined && cache === value)
  1037. return this;
  1038. this._valueCache[uniformName] = value;
  1039. this._engine.setFloat(this.getUniform(uniformName), value);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a boolean on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param bool value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setBool = function (uniformName, bool) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === bool)
  1051. return this;
  1052. this._valueCache[uniformName] = bool;
  1053. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a Vector2 on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param vector2 vector2 to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1063. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1064. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1065. }
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float2 on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param x First float in float2.
  1072. * @param y Second float in float2.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1076. if (this._cacheFloat2(uniformName, x, y)) {
  1077. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1078. }
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector3 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector3 Value to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1088. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1089. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float3 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float3.
  1097. * @param y Second float in float3.
  1098. * @param z Third float in float3.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1102. if (this._cacheFloat3(uniformName, x, y, z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a Vector4 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param vector4 Value to be set.
  1111. * @returns this effect.
  1112. */
  1113. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1114. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1115. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1116. }
  1117. return this;
  1118. };
  1119. /**
  1120. * Sets a float4 on a uniform variable.
  1121. * @param uniformName Name of the variable.
  1122. * @param x First float in float4.
  1123. * @param y Second float in float4.
  1124. * @param z Third float in float4.
  1125. * @param w Fourth float in float4.
  1126. * @returns this effect.
  1127. */
  1128. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1129. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1130. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1131. }
  1132. return this;
  1133. };
  1134. /**
  1135. * Sets a Color3 on a uniform variable.
  1136. * @param uniformName Name of the variable.
  1137. * @param color3 Value to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setColor3 = function (uniformName, color3) {
  1141. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1142. this._engine.setColor3(this.getUniform(uniformName), color3);
  1143. }
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a Color4 on a uniform variable.
  1148. * @param uniformName Name of the variable.
  1149. * @param color3 Value to be set.
  1150. * @param alpha Alpha value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1154. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1155. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color4 on a uniform variable
  1161. * @param uniformName defines the name of the variable
  1162. * @param color4 defines the value to be set
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1166. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1167. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Resets the cache of effects.
  1173. */
  1174. Effect.ResetCache = function () {
  1175. Effect._baseCache = {};
  1176. };
  1177. Effect._uniqueIdSeed = 0;
  1178. Effect._baseCache = {};
  1179. // Statics
  1180. /**
  1181. * Store of each shader (The can be looked up using effect.key)
  1182. */
  1183. Effect.ShadersStore = {};
  1184. /**
  1185. * Store of each included file for a shader (The can be looked up using effect.key)
  1186. */
  1187. Effect.IncludesShadersStore = {};
  1188. return Effect;
  1189. }());
  1190. BABYLON.Effect = Effect;
  1191. })(BABYLON || (BABYLON = {}));
  1192. //# sourceMappingURL=babylon.effect.js.map
  1193. //# sourceMappingURL=babylon.types.js.map
  1194. var BABYLON;
  1195. (function (BABYLON) {
  1196. var KeyboardEventTypes = /** @class */ (function () {
  1197. function KeyboardEventTypes() {
  1198. }
  1199. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1200. get: function () {
  1201. return KeyboardEventTypes._KEYDOWN;
  1202. },
  1203. enumerable: true,
  1204. configurable: true
  1205. });
  1206. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1207. get: function () {
  1208. return KeyboardEventTypes._KEYUP;
  1209. },
  1210. enumerable: true,
  1211. configurable: true
  1212. });
  1213. KeyboardEventTypes._KEYDOWN = 0x01;
  1214. KeyboardEventTypes._KEYUP = 0x02;
  1215. return KeyboardEventTypes;
  1216. }());
  1217. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1218. var KeyboardInfo = /** @class */ (function () {
  1219. function KeyboardInfo(type, event) {
  1220. this.type = type;
  1221. this.event = event;
  1222. }
  1223. return KeyboardInfo;
  1224. }());
  1225. BABYLON.KeyboardInfo = KeyboardInfo;
  1226. /**
  1227. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1228. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1229. */
  1230. var KeyboardInfoPre = /** @class */ (function (_super) {
  1231. __extends(KeyboardInfoPre, _super);
  1232. function KeyboardInfoPre(type, event) {
  1233. var _this = _super.call(this, type, event) || this;
  1234. _this.skipOnPointerObservable = false;
  1235. return _this;
  1236. }
  1237. return KeyboardInfoPre;
  1238. }(KeyboardInfo));
  1239. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1240. })(BABYLON || (BABYLON = {}));
  1241. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1242. var BABYLON;
  1243. (function (BABYLON) {
  1244. var PointerEventTypes = /** @class */ (function () {
  1245. function PointerEventTypes() {
  1246. }
  1247. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERDOWN;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERUP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERMOVE;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERWHEEL;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERPICK;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERTAP;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOUBLETAP;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. PointerEventTypes._POINTERDOWN = 0x01;
  1297. PointerEventTypes._POINTERUP = 0x02;
  1298. PointerEventTypes._POINTERMOVE = 0x04;
  1299. PointerEventTypes._POINTERWHEEL = 0x08;
  1300. PointerEventTypes._POINTERPICK = 0x10;
  1301. PointerEventTypes._POINTERTAP = 0x20;
  1302. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1303. return PointerEventTypes;
  1304. }());
  1305. BABYLON.PointerEventTypes = PointerEventTypes;
  1306. var PointerInfoBase = /** @class */ (function () {
  1307. function PointerInfoBase(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return PointerInfoBase;
  1312. }());
  1313. BABYLON.PointerInfoBase = PointerInfoBase;
  1314. /**
  1315. * This class is used to store pointer related info for the onPrePointerObservable event.
  1316. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1317. */
  1318. var PointerInfoPre = /** @class */ (function (_super) {
  1319. __extends(PointerInfoPre, _super);
  1320. function PointerInfoPre(type, event, localX, localY) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1324. return _this;
  1325. }
  1326. return PointerInfoPre;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfoPre = PointerInfoPre;
  1329. /**
  1330. * This type contains all the data related to a pointer event in Babylon.js.
  1331. * 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.
  1332. */
  1333. var PointerInfo = /** @class */ (function (_super) {
  1334. __extends(PointerInfo, _super);
  1335. function PointerInfo(type, event, pickInfo) {
  1336. var _this = _super.call(this, type, event) || this;
  1337. _this.pickInfo = pickInfo;
  1338. return _this;
  1339. }
  1340. return PointerInfo;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfo = PointerInfo;
  1343. })(BABYLON || (BABYLON = {}));
  1344. //# sourceMappingURL=babylon.pointerEvents.js.map
  1345. var BABYLON;
  1346. (function (BABYLON) {
  1347. BABYLON.ToGammaSpace = 1 / 2.2;
  1348. BABYLON.ToLinearSpace = 2.2;
  1349. BABYLON.Epsilon = 0.001;
  1350. /**
  1351. * Class used to hold a RBG color
  1352. */
  1353. var Color3 = /** @class */ (function () {
  1354. /**
  1355. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1356. * @param r defines the red component (between 0 and 1, default is 0)
  1357. * @param g defines the green component (between 0 and 1, default is 0)
  1358. * @param b defines the blue component (between 0 and 1, default is 0)
  1359. */
  1360. function Color3(
  1361. /**
  1362. * Defines the red component (between 0 and 1, default is 0)
  1363. */
  1364. r,
  1365. /**
  1366. * Defines the green component (between 0 and 1, default is 0)
  1367. */
  1368. g,
  1369. /**
  1370. * Defines the blue component (between 0 and 1, default is 0)
  1371. */
  1372. b) {
  1373. if (r === void 0) { r = 0; }
  1374. if (g === void 0) { g = 0; }
  1375. if (b === void 0) { b = 0; }
  1376. this.r = r;
  1377. this.g = g;
  1378. this.b = b;
  1379. }
  1380. /**
  1381. * Creates a string with the Color3 current values
  1382. * @returns the string representation of the Color3 object
  1383. */
  1384. Color3.prototype.toString = function () {
  1385. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1386. };
  1387. /**
  1388. * Returns the string "Color3"
  1389. * @returns "Color3"
  1390. */
  1391. Color3.prototype.getClassName = function () {
  1392. return "Color3";
  1393. };
  1394. /**
  1395. * Compute the Color3 hash code
  1396. * @returns an unique number that can be used to hash Color3 objects
  1397. */
  1398. Color3.prototype.getHashCode = function () {
  1399. var hash = this.r || 0;
  1400. hash = (hash * 397) ^ (this.g || 0);
  1401. hash = (hash * 397) ^ (this.b || 0);
  1402. return hash;
  1403. };
  1404. // Operators
  1405. /**
  1406. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1407. * @param array defines the array where to store the r,g,b components
  1408. * @param index defines an optional index in the target array to define where to start storing values
  1409. * @returns the current Color3 object
  1410. */
  1411. Color3.prototype.toArray = function (array, index) {
  1412. if (index === undefined) {
  1413. index = 0;
  1414. }
  1415. array[index] = this.r;
  1416. array[index + 1] = this.g;
  1417. array[index + 2] = this.b;
  1418. return this;
  1419. };
  1420. /**
  1421. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1422. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1423. * @returns a new {BABYLON.Color4} object
  1424. */
  1425. Color3.prototype.toColor4 = function (alpha) {
  1426. if (alpha === void 0) { alpha = 1; }
  1427. return new Color4(this.r, this.g, this.b, alpha);
  1428. };
  1429. /**
  1430. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1431. * @returns the new array
  1432. */
  1433. Color3.prototype.asArray = function () {
  1434. var result = new Array();
  1435. this.toArray(result, 0);
  1436. return result;
  1437. };
  1438. /**
  1439. * Returns the luminance value
  1440. * @returns a float value
  1441. */
  1442. Color3.prototype.toLuminance = function () {
  1443. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1444. };
  1445. /**
  1446. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1447. * @param otherColor defines the second operand
  1448. * @returns the new Color3 object
  1449. */
  1450. Color3.prototype.multiply = function (otherColor) {
  1451. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1452. };
  1453. /**
  1454. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1455. * @param otherColor defines the second operand
  1456. * @param result defines the Color3 object where to store the result
  1457. * @returns the current Color3
  1458. */
  1459. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1460. result.r = this.r * otherColor.r;
  1461. result.g = this.g * otherColor.g;
  1462. result.b = this.b * otherColor.b;
  1463. return this;
  1464. };
  1465. /**
  1466. * Determines equality between Color3 objects
  1467. * @param otherColor defines the second operand
  1468. * @returns true if the rgb values are equal to the passed ones
  1469. */
  1470. Color3.prototype.equals = function (otherColor) {
  1471. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1472. };
  1473. /**
  1474. * Determines equality between the current Color3 object and a set of r,b,g values
  1475. * @param r defines the red component to check
  1476. * @param g defines the green component to check
  1477. * @param b defines the blue component to check
  1478. * @returns true if the rgb values are equal to the passed ones
  1479. */
  1480. Color3.prototype.equalsFloats = function (r, g, b) {
  1481. return this.r === r && this.g === g && this.b === b;
  1482. };
  1483. /**
  1484. * Multiplies in place each rgb value by scale
  1485. * @param scale defines the scaling factor
  1486. * @returns the updated Color3.
  1487. */
  1488. Color3.prototype.scale = function (scale) {
  1489. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1490. };
  1491. /**
  1492. * Multiplies the rgb values by scale and stores the result into "result"
  1493. * @param scale defines the scaling factor
  1494. * @param result defines the Color3 object where to store the result
  1495. * @returns the unmodified current Color3.
  1496. */
  1497. Color3.prototype.scaleToRef = function (scale, result) {
  1498. result.r = this.r * scale;
  1499. result.g = this.g * scale;
  1500. result.b = this.b * scale;
  1501. return this;
  1502. };
  1503. /**
  1504. * Clamps the rgb values by the min and max values and stores the result into "result"
  1505. * @param min defines minimum clamping value (default is 0)
  1506. * @param max defines maximum clamping value (default is 1)
  1507. * @param result defines color to store the result into
  1508. * @returns the original Color3
  1509. */
  1510. Color3.prototype.clampToRef = function (min, max, result) {
  1511. if (min === void 0) { min = 0; }
  1512. if (max === void 0) { max = 1; }
  1513. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1514. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1515. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1516. return this;
  1517. };
  1518. /**
  1519. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3
  1522. */
  1523. Color3.prototype.add = function (otherColor) {
  1524. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1525. };
  1526. /**
  1527. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines Color3 object to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.addToRef = function (otherColor, result) {
  1533. result.r = this.r + otherColor.r;
  1534. result.g = this.g + otherColor.g;
  1535. result.b = this.b + otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1540. * @param otherColor defines the second operand
  1541. * @returns the new Color3
  1542. */
  1543. Color3.prototype.subtract = function (otherColor) {
  1544. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1545. };
  1546. /**
  1547. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1548. * @param otherColor defines the second operand
  1549. * @param result defines Color3 object to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.subtractToRef = function (otherColor, result) {
  1553. result.r = this.r - otherColor.r;
  1554. result.g = this.g - otherColor.g;
  1555. result.b = this.b - otherColor.b;
  1556. return this;
  1557. };
  1558. /**
  1559. * Copy the current object
  1560. * @returns a new Color3 copied the current one
  1561. */
  1562. Color3.prototype.clone = function () {
  1563. return new Color3(this.r, this.g, this.b);
  1564. };
  1565. /**
  1566. * Copies the rgb values from the source in the current Color3
  1567. * @param source defines the source Color3 object
  1568. * @returns the updated Color3 object
  1569. */
  1570. Color3.prototype.copyFrom = function (source) {
  1571. this.r = source.r;
  1572. this.g = source.g;
  1573. this.b = source.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Updates the Color3 rgb values from the passed floats
  1578. * @param r defines the red component to read from
  1579. * @param g defines the green component to read from
  1580. * @param b defines the blue component to read from
  1581. * @returns the current Color3 object
  1582. */
  1583. Color3.prototype.copyFromFloats = function (r, g, b) {
  1584. this.r = r;
  1585. this.g = g;
  1586. this.b = b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Updates the Color3 rgb values from the passed floats
  1591. * @param r defines the red component to read from
  1592. * @param g defines the green component to read from
  1593. * @param b defines the blue component to read from
  1594. * @returns the current Color3 object
  1595. */
  1596. Color3.prototype.set = function (r, g, b) {
  1597. return this.copyFromFloats(r, g, b);
  1598. };
  1599. /**
  1600. * Compute the Color3 hexadecimal code as a string
  1601. * @returns a string containing the hexadecimal representation of the Color3 object
  1602. */
  1603. Color3.prototype.toHexString = function () {
  1604. var intR = (this.r * 255) | 0;
  1605. var intG = (this.g * 255) | 0;
  1606. var intB = (this.b * 255) | 0;
  1607. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1608. };
  1609. /**
  1610. * Computes a new Color3 converted from the current one to linear space
  1611. * @returns a new Color3 object
  1612. */
  1613. Color3.prototype.toLinearSpace = function () {
  1614. var convertedColor = new Color3();
  1615. this.toLinearSpaceToRef(convertedColor);
  1616. return convertedColor;
  1617. };
  1618. /**
  1619. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1620. * @param convertedColor defines the Color3 object where to store the linear space version
  1621. * @returns the unmodified Color3
  1622. */
  1623. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1624. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1625. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1626. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1627. return this;
  1628. };
  1629. /**
  1630. * Computes a new Color3 converted from the current one to gamma space
  1631. * @returns a new Color3 object
  1632. */
  1633. Color3.prototype.toGammaSpace = function () {
  1634. var convertedColor = new Color3();
  1635. this.toGammaSpaceToRef(convertedColor);
  1636. return convertedColor;
  1637. };
  1638. /**
  1639. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1640. * @param convertedColor defines the Color3 object where to store the gamma space version
  1641. * @returns the unmodified Color3
  1642. */
  1643. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1644. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1645. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1646. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1647. return this;
  1648. };
  1649. // Statics
  1650. /**
  1651. * Creates a new Color3 from the string containing valid hexadecimal values
  1652. * @param hex defines a string containing valid hexadecimal values
  1653. * @returns a new Color3 object
  1654. */
  1655. Color3.FromHexString = function (hex) {
  1656. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1657. return new Color3(0, 0, 0);
  1658. }
  1659. var r = parseInt(hex.substring(1, 3), 16);
  1660. var g = parseInt(hex.substring(3, 5), 16);
  1661. var b = parseInt(hex.substring(5, 7), 16);
  1662. return Color3.FromInts(r, g, b);
  1663. };
  1664. /**
  1665. * Creates a new Vector3 from the starting index of the passed array
  1666. * @param array defines the source array
  1667. * @param offset defines an offset in the source array
  1668. * @returns a new Color3 object
  1669. */
  1670. Color3.FromArray = function (array, offset) {
  1671. if (offset === void 0) { offset = 0; }
  1672. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1673. };
  1674. /**
  1675. * Creates a new Color3 from integer values (< 256)
  1676. * @param r defines the red component to read from (value between 0 and 255)
  1677. * @param g defines the green component to read from (value between 0 and 255)
  1678. * @param b defines the blue component to read from (value between 0 and 255)
  1679. * @returns a new Color3 object
  1680. */
  1681. Color3.FromInts = function (r, g, b) {
  1682. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1683. };
  1684. /**
  1685. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1686. * @param start defines the start Color3 value
  1687. * @param end defines the end Color3 value
  1688. * @param amount defines the gradient value between start and end
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.Lerp = function (start, end, amount) {
  1692. var r = start.r + ((end.r - start.r) * amount);
  1693. var g = start.g + ((end.g - start.g) * amount);
  1694. var b = start.b + ((end.b - start.b) * amount);
  1695. return new Color3(r, g, b);
  1696. };
  1697. /**
  1698. * Returns a Color3 value containing a red color
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.Red = function () { return new Color3(1, 0, 0); };
  1702. /**
  1703. * Returns a Color3 value containing a green color
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.Green = function () { return new Color3(0, 1, 0); };
  1707. /**
  1708. * Returns a Color3 value containing a blue color
  1709. * @returns a new Color3 object
  1710. */
  1711. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1712. /**
  1713. * Returns a Color3 value containing a black color
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Black = function () { return new Color3(0, 0, 0); };
  1717. /**
  1718. * Returns a Color3 value containing a white color
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.White = function () { return new Color3(1, 1, 1); };
  1722. /**
  1723. * Returns a Color3 value containing a purple color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1727. /**
  1728. * Returns a Color3 value containing a magenta color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1732. /**
  1733. * Returns a Color3 value containing a yellow color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a gray color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1742. /**
  1743. * Returns a Color3 value containing a teal color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1747. /**
  1748. * Returns a Color3 value containing a random color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1752. return Color3;
  1753. }());
  1754. BABYLON.Color3 = Color3;
  1755. /**
  1756. * Class used to hold a RBGA color
  1757. */
  1758. var Color4 = /** @class */ (function () {
  1759. /**
  1760. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1761. * @param r defines the red component (between 0 and 1, default is 0)
  1762. * @param g defines the green component (between 0 and 1, default is 0)
  1763. * @param b defines the blue component (between 0 and 1, default is 0)
  1764. * @param a defines the alpha component (between 0 and 1, default is 1)
  1765. */
  1766. function Color4(
  1767. /**
  1768. * Defines the red component (between 0 and 1, default is 0)
  1769. */
  1770. r,
  1771. /**
  1772. * Defines the green component (between 0 and 1, default is 0)
  1773. */
  1774. g,
  1775. /**
  1776. * Defines the blue component (between 0 and 1, default is 0)
  1777. */
  1778. b,
  1779. /**
  1780. * Defines the alpha component (between 0 and 1, default is 1)
  1781. */
  1782. a) {
  1783. if (r === void 0) { r = 0; }
  1784. if (g === void 0) { g = 0; }
  1785. if (b === void 0) { b = 0; }
  1786. if (a === void 0) { a = 1; }
  1787. this.r = r;
  1788. this.g = g;
  1789. this.b = b;
  1790. this.a = a;
  1791. }
  1792. // Operators
  1793. /**
  1794. * Adds in place the passed Color4 values to the current Color4 object
  1795. * @param right defines the second operand
  1796. * @returns the current updated Color4 object
  1797. */
  1798. Color4.prototype.addInPlace = function (right) {
  1799. this.r += right.r;
  1800. this.g += right.g;
  1801. this.b += right.b;
  1802. this.a += right.a;
  1803. return this;
  1804. };
  1805. /**
  1806. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1807. * @returns the new array
  1808. */
  1809. Color4.prototype.asArray = function () {
  1810. var result = new Array();
  1811. this.toArray(result, 0);
  1812. return result;
  1813. };
  1814. /**
  1815. * Stores from the starting index in the passed array the Color4 successive values
  1816. * @param array defines the array where to store the r,g,b components
  1817. * @param index defines an optional index in the target array to define where to start storing values
  1818. * @returns the current Color4 object
  1819. */
  1820. Color4.prototype.toArray = function (array, index) {
  1821. if (index === undefined) {
  1822. index = 0;
  1823. }
  1824. array[index] = this.r;
  1825. array[index + 1] = this.g;
  1826. array[index + 2] = this.b;
  1827. array[index + 3] = this.a;
  1828. return this;
  1829. };
  1830. /**
  1831. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1832. * @param right defines the second operand
  1833. * @returns a new Color4 object
  1834. */
  1835. Color4.prototype.add = function (right) {
  1836. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1837. };
  1838. /**
  1839. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1840. * @param right defines the second operand
  1841. * @returns a new Color4 object
  1842. */
  1843. Color4.prototype.subtract = function (right) {
  1844. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1845. };
  1846. /**
  1847. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1848. * @param right defines the second operand
  1849. * @param result defines the Color4 object where to store the result
  1850. * @returns the current Color4 object
  1851. */
  1852. Color4.prototype.subtractToRef = function (right, result) {
  1853. result.r = this.r - right.r;
  1854. result.g = this.g - right.g;
  1855. result.b = this.b - right.b;
  1856. result.a = this.a - right.a;
  1857. return this;
  1858. };
  1859. /**
  1860. * Creates a new Color4 with the current Color4 values multiplied by scale
  1861. * @param scale defines the scaling factor to apply
  1862. * @returns a new Color4 object
  1863. */
  1864. Color4.prototype.scale = function (scale) {
  1865. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1866. };
  1867. /**
  1868. * Multiplies the current Color4 values by scale and stores the result in "result"
  1869. * @param scale defines the scaling factor to apply
  1870. * @param result defines the Color4 object where to store the result
  1871. * @returns the current Color4.
  1872. */
  1873. Color4.prototype.scaleToRef = function (scale, result) {
  1874. result.r = this.r * scale;
  1875. result.g = this.g * scale;
  1876. result.b = this.b * scale;
  1877. result.a = this.a * scale;
  1878. return this;
  1879. };
  1880. /**
  1881. * Clamps the rgb values by the min and max values and stores the result into "result"
  1882. * @param min defines minimum clamping value (default is 0)
  1883. * @param max defines maximum clamping value (default is 1)
  1884. * @param result defines color to store the result into.
  1885. * @returns the cuurent Color4
  1886. */
  1887. Color4.prototype.clampToRef = function (min, max, result) {
  1888. if (min === void 0) { min = 0; }
  1889. if (max === void 0) { max = 1; }
  1890. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1891. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1892. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1893. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1894. return this;
  1895. };
  1896. /**
  1897. * Multipy an Color4 value by another and return a new Color4 object
  1898. * @param color defines the Color4 value to multiply by
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.multiply = function (color) {
  1902. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1903. };
  1904. /**
  1905. * Multipy a Color4 value by another and push the result in a reference value
  1906. * @param color defines the Color4 value to multiply by
  1907. * @param result defines the Color4 to fill the result in
  1908. * @returns the result Color4
  1909. */
  1910. Color4.prototype.multiplyToRef = function (color, result) {
  1911. result.r = this.r * color.r;
  1912. result.g = this.g * color.g;
  1913. result.b = this.b * color.b;
  1914. result.a = this.a * color.a;
  1915. return result;
  1916. };
  1917. /**
  1918. * Creates a string with the Color4 current values
  1919. * @returns the string representation of the Color4 object
  1920. */
  1921. Color4.prototype.toString = function () {
  1922. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1923. };
  1924. /**
  1925. * Returns the string "Color4"
  1926. * @returns "Color4"
  1927. */
  1928. Color4.prototype.getClassName = function () {
  1929. return "Color4";
  1930. };
  1931. /**
  1932. * Compute the Color4 hash code
  1933. * @returns an unique number that can be used to hash Color4 objects
  1934. */
  1935. Color4.prototype.getHashCode = function () {
  1936. var hash = this.r || 0;
  1937. hash = (hash * 397) ^ (this.g || 0);
  1938. hash = (hash * 397) ^ (this.b || 0);
  1939. hash = (hash * 397) ^ (this.a || 0);
  1940. return hash;
  1941. };
  1942. /**
  1943. * Creates a new Color4 copied from the current one
  1944. * @returns a new Color4 object
  1945. */
  1946. Color4.prototype.clone = function () {
  1947. return new Color4(this.r, this.g, this.b, this.a);
  1948. };
  1949. /**
  1950. * Copies the passed Color4 values into the current one
  1951. * @param source defines the source Color4 object
  1952. * @returns the current updated Color4 object
  1953. */
  1954. Color4.prototype.copyFrom = function (source) {
  1955. this.r = source.r;
  1956. this.g = source.g;
  1957. this.b = source.b;
  1958. this.a = source.a;
  1959. return this;
  1960. };
  1961. /**
  1962. * Copies the passed float values into the current one
  1963. * @param r defines the red component to read from
  1964. * @param g defines the green component to read from
  1965. * @param b defines the blue component to read from
  1966. * @param a defines the alpha component to read from
  1967. * @returns the current updated Color4 object
  1968. */
  1969. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1970. this.r = r;
  1971. this.g = g;
  1972. this.b = b;
  1973. this.a = a;
  1974. return this;
  1975. };
  1976. /**
  1977. * Copies the passed float values into the current one
  1978. * @param r defines the red component to read from
  1979. * @param g defines the green component to read from
  1980. * @param b defines the blue component to read from
  1981. * @param a defines the alpha component to read from
  1982. * @returns the current updated Color4 object
  1983. */
  1984. Color4.prototype.set = function (r, g, b, a) {
  1985. return this.copyFromFloats(r, g, b, a);
  1986. };
  1987. /**
  1988. * Compute the Color4 hexadecimal code as a string
  1989. * @returns a string containing the hexadecimal representation of the Color4 object
  1990. */
  1991. Color4.prototype.toHexString = function () {
  1992. var intR = (this.r * 255) | 0;
  1993. var intG = (this.g * 255) | 0;
  1994. var intB = (this.b * 255) | 0;
  1995. var intA = (this.a * 255) | 0;
  1996. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1997. };
  1998. /**
  1999. * Computes a new Color4 converted from the current one to linear space
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.toLinearSpace = function () {
  2003. var convertedColor = new Color4();
  2004. this.toLinearSpaceToRef(convertedColor);
  2005. return convertedColor;
  2006. };
  2007. /**
  2008. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2009. * @param convertedColor defines the Color4 object where to store the linear space version
  2010. * @returns the unmodified Color4
  2011. */
  2012. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2013. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2014. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2015. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2016. convertedColor.a = this.a;
  2017. return this;
  2018. };
  2019. /**
  2020. * Computes a new Color4 converted from the current one to gamma space
  2021. * @returns a new Color4 object
  2022. */
  2023. Color4.prototype.toGammaSpace = function () {
  2024. var convertedColor = new Color4();
  2025. this.toGammaSpaceToRef(convertedColor);
  2026. return convertedColor;
  2027. };
  2028. /**
  2029. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2030. * @param convertedColor defines the Color4 object where to store the gamma space version
  2031. * @returns the unmodified Color4
  2032. */
  2033. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2034. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2035. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2036. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2037. convertedColor.a = this.a;
  2038. return this;
  2039. };
  2040. // Statics
  2041. /**
  2042. * Creates a new Color4 from the string containing valid hexadecimal values
  2043. * @param hex defines a string containing valid hexadecimal values
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.FromHexString = function (hex) {
  2047. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2048. return new Color4(0.0, 0.0, 0.0, 0.0);
  2049. }
  2050. var r = parseInt(hex.substring(1, 3), 16);
  2051. var g = parseInt(hex.substring(3, 5), 16);
  2052. var b = parseInt(hex.substring(5, 7), 16);
  2053. var a = parseInt(hex.substring(7, 9), 16);
  2054. return Color4.FromInts(r, g, b, a);
  2055. };
  2056. /**
  2057. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2058. * @param left defines the start value
  2059. * @param right defines the end value
  2060. * @param amount defines the gradient factor
  2061. * @returns a new Color4 object
  2062. */
  2063. Color4.Lerp = function (left, right, amount) {
  2064. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2065. Color4.LerpToRef(left, right, amount, result);
  2066. return result;
  2067. };
  2068. /**
  2069. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2070. * @param left defines the start value
  2071. * @param right defines the end value
  2072. * @param amount defines the gradient factor
  2073. * @param result defines the Color4 object where to store data
  2074. */
  2075. Color4.LerpToRef = function (left, right, amount, result) {
  2076. result.r = left.r + (right.r - left.r) * amount;
  2077. result.g = left.g + (right.g - left.g) * amount;
  2078. result.b = left.b + (right.b - left.b) * amount;
  2079. result.a = left.a + (right.a - left.a) * amount;
  2080. };
  2081. /**
  2082. * Creates a new Color4 from the starting index element of the passed array
  2083. * @param array defines the source array to read from
  2084. * @param offset defines the offset in the source array
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromArray = function (array, offset) {
  2088. if (offset === void 0) { offset = 0; }
  2089. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2090. };
  2091. /**
  2092. * Creates a new Color3 from integer values (< 256)
  2093. * @param r defines the red component to read from (value between 0 and 255)
  2094. * @param g defines the green component to read from (value between 0 and 255)
  2095. * @param b defines the blue component to read from (value between 0 and 255)
  2096. * @param a defines the alpha component to read from (value between 0 and 255)
  2097. * @returns a new Color3 object
  2098. */
  2099. Color4.FromInts = function (r, g, b, a) {
  2100. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2101. };
  2102. /**
  2103. * Check the content of a given array and convert it to an array containing RGBA data
  2104. * If the original array was already containing count * 4 values then it is returned directly
  2105. * @param colors defines the array to check
  2106. * @param count defines the number of RGBA data to expect
  2107. * @returns an array containing count * 4 values (RGBA)
  2108. */
  2109. Color4.CheckColors4 = function (colors, count) {
  2110. // Check if color3 was used
  2111. if (colors.length === count * 3) {
  2112. var colors4 = [];
  2113. for (var index = 0; index < colors.length; index += 3) {
  2114. var newIndex = (index / 3) * 4;
  2115. colors4[newIndex] = colors[index];
  2116. colors4[newIndex + 1] = colors[index + 1];
  2117. colors4[newIndex + 2] = colors[index + 2];
  2118. colors4[newIndex + 3] = 1.0;
  2119. }
  2120. return colors4;
  2121. }
  2122. return colors;
  2123. };
  2124. return Color4;
  2125. }());
  2126. BABYLON.Color4 = Color4;
  2127. var Vector2 = /** @class */ (function () {
  2128. /**
  2129. * Creates a new Vector2 from the passed x and y coordinates.
  2130. */
  2131. function Vector2(x, y) {
  2132. this.x = x;
  2133. this.y = y;
  2134. }
  2135. /**
  2136. * Returns a string with the Vector2 coordinates.
  2137. */
  2138. Vector2.prototype.toString = function () {
  2139. return "{X: " + this.x + " Y:" + this.y + "}";
  2140. };
  2141. /**
  2142. * Returns the string "Vector2"
  2143. */
  2144. Vector2.prototype.getClassName = function () {
  2145. return "Vector2";
  2146. };
  2147. /**
  2148. * Returns the Vector2 hash code as a number.
  2149. */
  2150. Vector2.prototype.getHashCode = function () {
  2151. var hash = this.x || 0;
  2152. hash = (hash * 397) ^ (this.y || 0);
  2153. return hash;
  2154. };
  2155. // Operators
  2156. /**
  2157. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2158. * Returns the Vector2.
  2159. */
  2160. Vector2.prototype.toArray = function (array, index) {
  2161. if (index === void 0) { index = 0; }
  2162. array[index] = this.x;
  2163. array[index + 1] = this.y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Returns a new array with 2 elements : the Vector2 coordinates.
  2168. */
  2169. Vector2.prototype.asArray = function () {
  2170. var result = new Array();
  2171. this.toArray(result, 0);
  2172. return result;
  2173. };
  2174. /**
  2175. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2176. * Returns the updated Vector2.
  2177. */
  2178. Vector2.prototype.copyFrom = function (source) {
  2179. this.x = source.x;
  2180. this.y = source.y;
  2181. return this;
  2182. };
  2183. /**
  2184. * Sets the Vector2 coordinates with the passed floats.
  2185. * Returns the updated Vector2.
  2186. */
  2187. Vector2.prototype.copyFromFloats = function (x, y) {
  2188. this.x = x;
  2189. this.y = y;
  2190. return this;
  2191. };
  2192. /**
  2193. * Sets the Vector2 coordinates with the passed floats.
  2194. * Returns the updated Vector2.
  2195. */
  2196. Vector2.prototype.set = function (x, y) {
  2197. return this.copyFromFloats(x, y);
  2198. };
  2199. /**
  2200. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2201. */
  2202. Vector2.prototype.add = function (otherVector) {
  2203. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2204. };
  2205. /**
  2206. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2207. * Returns the Vector2.
  2208. */
  2209. Vector2.prototype.addToRef = function (otherVector, result) {
  2210. result.x = this.x + otherVector.x;
  2211. result.y = this.y + otherVector.y;
  2212. return this;
  2213. };
  2214. /**
  2215. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2216. * Returns the updated Vector2.
  2217. */
  2218. Vector2.prototype.addInPlace = function (otherVector) {
  2219. this.x += otherVector.x;
  2220. this.y += otherVector.y;
  2221. return this;
  2222. };
  2223. /**
  2224. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2225. */
  2226. Vector2.prototype.addVector3 = function (otherVector) {
  2227. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2228. };
  2229. /**
  2230. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2231. */
  2232. Vector2.prototype.subtract = function (otherVector) {
  2233. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2234. };
  2235. /**
  2236. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2237. * Returns the Vector2.
  2238. */
  2239. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2240. result.x = this.x - otherVector.x;
  2241. result.y = this.y - otherVector.y;
  2242. return this;
  2243. };
  2244. /**
  2245. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2246. * Returns the updated Vector2.
  2247. */
  2248. Vector2.prototype.subtractInPlace = function (otherVector) {
  2249. this.x -= otherVector.x;
  2250. this.y -= otherVector.y;
  2251. return this;
  2252. };
  2253. /**
  2254. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2255. * Returns the updated Vector2.
  2256. */
  2257. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2258. this.x *= otherVector.x;
  2259. this.y *= otherVector.y;
  2260. return this;
  2261. };
  2262. /**
  2263. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2264. */
  2265. Vector2.prototype.multiply = function (otherVector) {
  2266. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2267. };
  2268. /**
  2269. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2270. * Returns the Vector2.
  2271. */
  2272. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2273. result.x = this.x * otherVector.x;
  2274. result.y = this.y * otherVector.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2279. */
  2280. Vector2.prototype.multiplyByFloats = function (x, y) {
  2281. return new Vector2(this.x * x, this.y * y);
  2282. };
  2283. /**
  2284. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2285. */
  2286. Vector2.prototype.divide = function (otherVector) {
  2287. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2288. };
  2289. /**
  2290. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2291. * Returns the Vector2.
  2292. */
  2293. Vector2.prototype.divideToRef = function (otherVector, result) {
  2294. result.x = this.x / otherVector.x;
  2295. result.y = this.y / otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Divides the current Vector3 coordinates by the passed ones.
  2300. * Returns the updated Vector3.
  2301. */
  2302. Vector2.prototype.divideInPlace = function (otherVector) {
  2303. return this.divideToRef(otherVector, this);
  2304. };
  2305. /**
  2306. * Returns a new Vector2 with current Vector2 negated coordinates.
  2307. */
  2308. Vector2.prototype.negate = function () {
  2309. return new Vector2(-this.x, -this.y);
  2310. };
  2311. /**
  2312. * Multiply the Vector2 coordinates by scale.
  2313. * Returns the updated Vector2.
  2314. */
  2315. Vector2.prototype.scaleInPlace = function (scale) {
  2316. this.x *= scale;
  2317. this.y *= scale;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2322. */
  2323. Vector2.prototype.scale = function (scale) {
  2324. return new Vector2(this.x * scale, this.y * scale);
  2325. };
  2326. /**
  2327. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2328. */
  2329. Vector2.prototype.equals = function (otherVector) {
  2330. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2331. };
  2332. /**
  2333. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2334. */
  2335. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2336. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2337. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2338. };
  2339. // Properties
  2340. /**
  2341. * Returns the vector length (float).
  2342. */
  2343. Vector2.prototype.length = function () {
  2344. return Math.sqrt(this.x * this.x + this.y * this.y);
  2345. };
  2346. /**
  2347. * Returns the vector squared length (float);
  2348. */
  2349. Vector2.prototype.lengthSquared = function () {
  2350. return (this.x * this.x + this.y * this.y);
  2351. };
  2352. // Methods
  2353. /**
  2354. * Normalize the vector.
  2355. * Returns the updated Vector2.
  2356. */
  2357. Vector2.prototype.normalize = function () {
  2358. var len = this.length();
  2359. if (len === 0)
  2360. return this;
  2361. var num = 1.0 / len;
  2362. this.x *= num;
  2363. this.y *= num;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 copied from the Vector2.
  2368. */
  2369. Vector2.prototype.clone = function () {
  2370. return new Vector2(this.x, this.y);
  2371. };
  2372. // Statics
  2373. /**
  2374. * Returns a new Vector2(0, 0)
  2375. */
  2376. Vector2.Zero = function () {
  2377. return new Vector2(0, 0);
  2378. };
  2379. /**
  2380. * Returns a new Vector2(1, 1)
  2381. */
  2382. Vector2.One = function () {
  2383. return new Vector2(1, 1);
  2384. };
  2385. /**
  2386. * Returns a new Vector2 set from the passed index element of the passed array.
  2387. */
  2388. Vector2.FromArray = function (array, offset) {
  2389. if (offset === void 0) { offset = 0; }
  2390. return new Vector2(array[offset], array[offset + 1]);
  2391. };
  2392. /**
  2393. * Sets "result" from the passed index element of the passed array.
  2394. */
  2395. Vector2.FromArrayToRef = function (array, offset, result) {
  2396. result.x = array[offset];
  2397. result.y = array[offset + 1];
  2398. };
  2399. /**
  2400. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2401. */
  2402. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2403. var squared = amount * amount;
  2404. var cubed = amount * squared;
  2405. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2406. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2407. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2408. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2409. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2410. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2411. return new Vector2(x, y);
  2412. };
  2413. /**
  2414. * 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".
  2415. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2416. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2417. */
  2418. Vector2.Clamp = function (value, min, max) {
  2419. var x = value.x;
  2420. x = (x > max.x) ? max.x : x;
  2421. x = (x < min.x) ? min.x : x;
  2422. var y = value.y;
  2423. y = (y > max.y) ? max.y : y;
  2424. y = (y < min.y) ? min.y : y;
  2425. return new Vector2(x, y);
  2426. };
  2427. /**
  2428. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2429. */
  2430. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2431. var squared = amount * amount;
  2432. var cubed = amount * squared;
  2433. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2434. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2435. var part3 = (cubed - (2.0 * squared)) + amount;
  2436. var part4 = cubed - squared;
  2437. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2438. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2439. return new Vector2(x, y);
  2440. };
  2441. /**
  2442. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2443. */
  2444. Vector2.Lerp = function (start, end, amount) {
  2445. var x = start.x + ((end.x - start.x) * amount);
  2446. var y = start.y + ((end.y - start.y) * amount);
  2447. return new Vector2(x, y);
  2448. };
  2449. /**
  2450. * Returns the dot product (float) of the vector "left" and the vector "right".
  2451. */
  2452. Vector2.Dot = function (left, right) {
  2453. return left.x * right.x + left.y * right.y;
  2454. };
  2455. /**
  2456. * Returns a new Vector2 equal to the normalized passed vector.
  2457. */
  2458. Vector2.Normalize = function (vector) {
  2459. var newVector = vector.clone();
  2460. newVector.normalize();
  2461. return newVector;
  2462. };
  2463. /**
  2464. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2465. */
  2466. Vector2.Minimize = function (left, right) {
  2467. var x = (left.x < right.x) ? left.x : right.x;
  2468. var y = (left.y < right.y) ? left.y : right.y;
  2469. return new Vector2(x, y);
  2470. };
  2471. /**
  2472. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2473. */
  2474. Vector2.Maximize = function (left, right) {
  2475. var x = (left.x > right.x) ? left.x : right.x;
  2476. var y = (left.y > right.y) ? left.y : right.y;
  2477. return new Vector2(x, y);
  2478. };
  2479. /**
  2480. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2481. */
  2482. Vector2.Transform = function (vector, transformation) {
  2483. var r = Vector2.Zero();
  2484. Vector2.TransformToRef(vector, transformation, r);
  2485. return r;
  2486. };
  2487. /**
  2488. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2489. */
  2490. Vector2.TransformToRef = function (vector, transformation, result) {
  2491. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2492. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2493. result.x = x;
  2494. result.y = y;
  2495. };
  2496. /**
  2497. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2498. */
  2499. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2500. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2501. var sign = a < 0 ? -1 : 1;
  2502. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2503. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2504. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2505. };
  2506. /**
  2507. * Returns the distance (float) between the vectors "value1" and "value2".
  2508. */
  2509. Vector2.Distance = function (value1, value2) {
  2510. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2511. };
  2512. /**
  2513. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2514. */
  2515. Vector2.DistanceSquared = function (value1, value2) {
  2516. var x = value1.x - value2.x;
  2517. var y = value1.y - value2.y;
  2518. return (x * x) + (y * y);
  2519. };
  2520. /**
  2521. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2522. */
  2523. Vector2.Center = function (value1, value2) {
  2524. var center = value1.add(value2);
  2525. center.scaleInPlace(0.5);
  2526. return center;
  2527. };
  2528. /**
  2529. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2530. */
  2531. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2532. var l2 = Vector2.DistanceSquared(segA, segB);
  2533. if (l2 === 0.0) {
  2534. return Vector2.Distance(p, segA);
  2535. }
  2536. var v = segB.subtract(segA);
  2537. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2538. var proj = segA.add(v.multiplyByFloats(t, t));
  2539. return Vector2.Distance(p, proj);
  2540. };
  2541. return Vector2;
  2542. }());
  2543. BABYLON.Vector2 = Vector2;
  2544. /**
  2545. * Classed used to store (x,y,z) vector representation
  2546. * A Vector3 is the main object used in 3D geometry
  2547. * It can represent etiher the coordinates of a point the space, either a direction
  2548. * Reminder: Babylon.js uses a left handed forward facing system
  2549. */
  2550. var Vector3 = /** @class */ (function () {
  2551. /**
  2552. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2553. * @param x defines the first coordinates (on X axis)
  2554. * @param y defines the second coordinates (on Y axis)
  2555. * @param z defines the third coordinates (on Z axis)
  2556. */
  2557. function Vector3(
  2558. /**
  2559. * Defines the first coordinates (on X axis)
  2560. */
  2561. x,
  2562. /**
  2563. * Defines the second coordinates (on Y axis)
  2564. */
  2565. y,
  2566. /**
  2567. * Defines the third coordinates (on Z axis)
  2568. */
  2569. z) {
  2570. this.x = x;
  2571. this.y = y;
  2572. this.z = z;
  2573. }
  2574. /**
  2575. * Creates a string representation of the Vector3
  2576. * @returns a string with the Vector3 coordinates.
  2577. */
  2578. Vector3.prototype.toString = function () {
  2579. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2580. };
  2581. /**
  2582. * Gets the class name
  2583. * @returns the string "Vector3"
  2584. */
  2585. Vector3.prototype.getClassName = function () {
  2586. return "Vector3";
  2587. };
  2588. /**
  2589. * Creates the Vector3 hash code
  2590. * @returns a number which tends to be unique between Vector3 instances
  2591. */
  2592. Vector3.prototype.getHashCode = function () {
  2593. var hash = this.x || 0;
  2594. hash = (hash * 397) ^ (this.y || 0);
  2595. hash = (hash * 397) ^ (this.z || 0);
  2596. return hash;
  2597. };
  2598. // Operators
  2599. /**
  2600. * Creates an array containing three elements : the coordinates of the Vector3
  2601. * @returns a new array of numbers
  2602. */
  2603. Vector3.prototype.asArray = function () {
  2604. var result = [];
  2605. this.toArray(result, 0);
  2606. return result;
  2607. };
  2608. /**
  2609. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2610. * @param array defines the destination array
  2611. * @param index defines the offset in the destination array
  2612. * @returns the current Vector3
  2613. */
  2614. Vector3.prototype.toArray = function (array, index) {
  2615. if (index === void 0) { index = 0; }
  2616. array[index] = this.x;
  2617. array[index + 1] = this.y;
  2618. array[index + 2] = this.z;
  2619. return this;
  2620. };
  2621. /**
  2622. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2623. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2624. */
  2625. Vector3.prototype.toQuaternion = function () {
  2626. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2631. var cosy = Math.cos(this.y * 0.5);
  2632. var siny = Math.sin(this.y * 0.5);
  2633. result.x = coszMinusx * siny;
  2634. result.y = -sinzMinusx * siny;
  2635. result.z = sinxPlusz * cosy;
  2636. result.w = cosxPlusz * cosy;
  2637. return result;
  2638. };
  2639. /**
  2640. * Adds the passed vector to the current Vector3
  2641. * @param otherVector defines the second operand
  2642. * @returns the current updated Vector3
  2643. */
  2644. Vector3.prototype.addInPlace = function (otherVector) {
  2645. this.x += otherVector.x;
  2646. this.y += otherVector.y;
  2647. this.z += otherVector.z;
  2648. return this;
  2649. };
  2650. /**
  2651. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2652. * @param otherVector defines the second operand
  2653. * @returns the resulting Vector3
  2654. */
  2655. Vector3.prototype.add = function (otherVector) {
  2656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2657. };
  2658. /**
  2659. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2660. * @param otherVector defines the second operand
  2661. * @param result defines the Vector3 object where to store the result
  2662. * @returns the current Vector3
  2663. */
  2664. Vector3.prototype.addToRef = function (otherVector, result) {
  2665. result.x = this.x + otherVector.x;
  2666. result.y = this.y + otherVector.y;
  2667. result.z = this.z + otherVector.z;
  2668. return this;
  2669. };
  2670. /**
  2671. * Subtract the passed vector from the current Vector3
  2672. * @param otherVector defines the second operand
  2673. * @returns the current updated Vector3
  2674. */
  2675. Vector3.prototype.subtractInPlace = function (otherVector) {
  2676. this.x -= otherVector.x;
  2677. this.y -= otherVector.y;
  2678. this.z -= otherVector.z;
  2679. return this;
  2680. };
  2681. /**
  2682. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2683. * @param otherVector defines the second operand
  2684. * @returns the resulting Vector3
  2685. */
  2686. Vector3.prototype.subtract = function (otherVector) {
  2687. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2688. };
  2689. /**
  2690. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2691. * @param otherVector defines the second operand
  2692. * @param result defines the Vector3 object where to store the result
  2693. * @returns the current Vector3
  2694. */
  2695. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2696. result.x = this.x - otherVector.x;
  2697. result.y = this.y - otherVector.y;
  2698. result.z = this.z - otherVector.z;
  2699. return this;
  2700. };
  2701. /**
  2702. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2703. * @param x defines the x coordinate of the operand
  2704. * @param y defines the y coordinate of the operand
  2705. * @param z defines the z coordinate of the operand
  2706. * @returns the resulting Vector3
  2707. */
  2708. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2709. return new Vector3(this.x - x, this.y - y, this.z - z);
  2710. };
  2711. /**
  2712. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2713. * @param x defines the x coordinate of the operand
  2714. * @param y defines the y coordinate of the operand
  2715. * @param z defines the z coordinate of the operand
  2716. * @param result defines the Vector3 object where to store the result
  2717. * @returns the current Vector3
  2718. */
  2719. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2720. result.x = this.x - x;
  2721. result.y = this.y - y;
  2722. result.z = this.z - z;
  2723. return this;
  2724. };
  2725. /**
  2726. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2727. * @returns a new Vector3
  2728. */
  2729. Vector3.prototype.negate = function () {
  2730. return new Vector3(-this.x, -this.y, -this.z);
  2731. };
  2732. /**
  2733. * Multiplies the Vector3 coordinates by the float "scale"
  2734. * @param scale defines the multiplier factor
  2735. * @returns the current updated Vector3
  2736. */
  2737. Vector3.prototype.scaleInPlace = function (scale) {
  2738. this.x *= scale;
  2739. this.y *= scale;
  2740. this.z *= scale;
  2741. return this;
  2742. };
  2743. /**
  2744. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2745. * @param scale defines the multiplier factor
  2746. * @returns a new Vector3
  2747. */
  2748. Vector3.prototype.scale = function (scale) {
  2749. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2750. };
  2751. /**
  2752. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2753. * @param scale defines the multiplier factor
  2754. * @param result defines the Vector3 object where to store the result
  2755. * @returns the current Vector3
  2756. */
  2757. Vector3.prototype.scaleToRef = function (scale, result) {
  2758. result.x = this.x * scale;
  2759. result.y = this.y * scale;
  2760. result.z = this.z * scale;
  2761. return this;
  2762. };
  2763. /**
  2764. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2765. * @param otherVector defines the second operand
  2766. * @returns true if both vectors are equals
  2767. */
  2768. Vector3.prototype.equals = function (otherVector) {
  2769. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2770. };
  2771. /**
  2772. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2773. * @param otherVector defines the second operand
  2774. * @param epsilon defines the minimal distance to define values as equals
  2775. * @returns true if both vectors are distant less than epsilon
  2776. */
  2777. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2778. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2779. 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);
  2780. };
  2781. /**
  2782. * Returns true if the current Vector3 coordinates equals the passed floats
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @returns true if both vectors are equals
  2787. */
  2788. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2789. return this.x === x && this.y === y && this.z === z;
  2790. };
  2791. /**
  2792. * Multiplies the current Vector3 coordinates by the passed ones
  2793. * @param otherVector defines the second operand
  2794. * @returns the current updated Vector3
  2795. */
  2796. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2797. this.x *= otherVector.x;
  2798. this.y *= otherVector.y;
  2799. this.z *= otherVector.z;
  2800. return this;
  2801. };
  2802. /**
  2803. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2804. * @param otherVector defines the second operand
  2805. * @returns the new Vector3
  2806. */
  2807. Vector3.prototype.multiply = function (otherVector) {
  2808. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2809. };
  2810. /**
  2811. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2812. * @param otherVector defines the second operand
  2813. * @param result defines the Vector3 object where to store the result
  2814. * @returns the current Vector3
  2815. */
  2816. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2817. result.x = this.x * otherVector.x;
  2818. result.y = this.y * otherVector.y;
  2819. result.z = this.z * otherVector.z;
  2820. return this;
  2821. };
  2822. /**
  2823. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2824. * @param x defines the x coordinate of the operand
  2825. * @param y defines the y coordinate of the operand
  2826. * @param z defines the z coordinate of the operand
  2827. * @returns the new Vector3
  2828. */
  2829. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2830. return new Vector3(this.x * x, this.y * y, this.z * z);
  2831. };
  2832. /**
  2833. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2834. * @param otherVector defines the second operand
  2835. * @returns the new Vector3
  2836. */
  2837. Vector3.prototype.divide = function (otherVector) {
  2838. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2839. };
  2840. /**
  2841. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2842. * @param otherVector defines the second operand
  2843. * @param result defines the Vector3 object where to store the result
  2844. * @returns the current Vector3
  2845. */
  2846. Vector3.prototype.divideToRef = function (otherVector, result) {
  2847. result.x = this.x / otherVector.x;
  2848. result.y = this.y / otherVector.y;
  2849. result.z = this.z / otherVector.z;
  2850. return this;
  2851. };
  2852. /**
  2853. * Divides the current Vector3 coordinates by the passed ones.
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.divideInPlace = function (otherVector) {
  2858. return this.divideToRef(otherVector, this);
  2859. };
  2860. /**
  2861. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2862. * @param other defines the second operand
  2863. * @returns the current updated Vector3
  2864. */
  2865. Vector3.prototype.minimizeInPlace = function (other) {
  2866. if (other.x < this.x)
  2867. this.x = other.x;
  2868. if (other.y < this.y)
  2869. this.y = other.y;
  2870. if (other.z < this.z)
  2871. this.z = other.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2876. * @param other defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.maximizeInPlace = function (other) {
  2880. if (other.x > this.x)
  2881. this.x = other.x;
  2882. if (other.y > this.y)
  2883. this.y = other.y;
  2884. if (other.z > this.z)
  2885. this.z = other.z;
  2886. return this;
  2887. };
  2888. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2889. /**
  2890. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2891. */
  2892. get: function () {
  2893. var absX = Math.abs(this.x);
  2894. var absY = Math.abs(this.y);
  2895. if (absX !== absY) {
  2896. return true;
  2897. }
  2898. var absZ = Math.abs(this.z);
  2899. if (absX !== absZ) {
  2900. return true;
  2901. }
  2902. if (absY !== absZ) {
  2903. return true;
  2904. }
  2905. return false;
  2906. },
  2907. enumerable: true,
  2908. configurable: true
  2909. });
  2910. // Properties
  2911. /**
  2912. * Gets the length of the Vector3
  2913. * @returns the length of the Vecto3
  2914. */
  2915. Vector3.prototype.length = function () {
  2916. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2917. };
  2918. /**
  2919. * Gets the squared length of the Vector3
  2920. * @returns squared length of the Vector3
  2921. */
  2922. Vector3.prototype.lengthSquared = function () {
  2923. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2924. };
  2925. /**
  2926. * Normalize the current Vector3.
  2927. * Please note that this is an in place operation.
  2928. * @returns the current updated Vector3
  2929. */
  2930. Vector3.prototype.normalize = function () {
  2931. var len = this.length();
  2932. if (len === 0 || len === 1.0)
  2933. return this;
  2934. var num = 1.0 / len;
  2935. this.x *= num;
  2936. this.y *= num;
  2937. this.z *= num;
  2938. return this;
  2939. };
  2940. /**
  2941. * Normalize the current Vector3 to a new vector
  2942. * @returns the new Vector3
  2943. */
  2944. Vector3.prototype.normalizeToNew = function () {
  2945. var normalized = new Vector3(0, 0, 0);
  2946. this.normalizeToRef(normalized);
  2947. return normalized;
  2948. };
  2949. /**
  2950. * Normalize the current Vector3 to the reference
  2951. * @param reference define the Vector3 to update
  2952. * @returns the updated Vector3
  2953. */
  2954. Vector3.prototype.normalizeToRef = function (reference) {
  2955. var len = this.length();
  2956. if (len === 0 || len === 1.0) {
  2957. reference.set(this.x, this.y, this.z);
  2958. return reference;
  2959. }
  2960. var scale = 1.0 / len;
  2961. this.scaleToRef(scale, reference);
  2962. return reference;
  2963. };
  2964. /**
  2965. * Creates a new Vector3 copied from the current Vector3
  2966. * @returns the new Vector3
  2967. */
  2968. Vector3.prototype.clone = function () {
  2969. return new Vector3(this.x, this.y, this.z);
  2970. };
  2971. /**
  2972. * Copies the passed vector coordinates to the current Vector3 ones
  2973. * @param source defines the source Vector3
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.copyFrom = function (source) {
  2977. this.x = source.x;
  2978. this.y = source.y;
  2979. this.z = source.z;
  2980. return this;
  2981. };
  2982. /**
  2983. * Copies the passed floats to the current Vector3 coordinates
  2984. * @param x defines the x coordinate of the operand
  2985. * @param y defines the y coordinate of the operand
  2986. * @param z defines the z coordinate of the operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2990. this.x = x;
  2991. this.y = y;
  2992. this.z = z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Copies the passed floats to the current Vector3 coordinates
  2997. * @param x defines the x coordinate of the operand
  2998. * @param y defines the y coordinate of the operand
  2999. * @param z defines the z coordinate of the operand
  3000. * @returns the current updated Vector3
  3001. */
  3002. Vector3.prototype.set = function (x, y, z) {
  3003. return this.copyFromFloats(x, y, z);
  3004. };
  3005. // Statics
  3006. /**
  3007. * Get the clip factor between two vectors
  3008. * @param vector0 defines the first operand
  3009. * @param vector1 defines the second operand
  3010. * @param axis defines the axis to use
  3011. * @param size defines the size along the axis
  3012. * @returns the clip factor
  3013. */
  3014. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3015. var d0 = Vector3.Dot(vector0, axis) - size;
  3016. var d1 = Vector3.Dot(vector1, axis) - size;
  3017. var s = d0 / (d0 - d1);
  3018. return s;
  3019. };
  3020. /**
  3021. * Get angle between two vectors
  3022. * @param vector0 angle between vector0 and vector1
  3023. * @param vector1 angle between vector0 and vector1
  3024. * @param normal direction of the normal
  3025. * @return the angle between vector0 and vector1
  3026. */
  3027. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3028. var v0 = vector0.clone().normalize();
  3029. var v1 = vector1.clone().normalize();
  3030. var dot = Vector3.Dot(v0, v1);
  3031. var n = Vector3.Cross(v0, v1);
  3032. if (Vector3.Dot(n, normal) > 0) {
  3033. return Math.acos(dot);
  3034. }
  3035. return -Math.acos(dot);
  3036. };
  3037. /**
  3038. * Returns a new Vector3 set from the index "offset" of the passed array
  3039. * @param array defines the source array
  3040. * @param offset defines the offset in the source array
  3041. * @returns the new Vector3
  3042. */
  3043. Vector3.FromArray = function (array, offset) {
  3044. if (!offset) {
  3045. offset = 0;
  3046. }
  3047. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3048. };
  3049. /**
  3050. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3051. * This function is deprecated. Use FromArray instead
  3052. * @param array defines the source array
  3053. * @param offset defines the offset in the source array
  3054. * @returns the new Vector3
  3055. */
  3056. Vector3.FromFloatArray = function (array, offset) {
  3057. return Vector3.FromArray(array, offset);
  3058. };
  3059. /**
  3060. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3061. * @param array defines the source array
  3062. * @param offset defines the offset in the source array
  3063. * @param result defines the Vector3 where to store the result
  3064. */
  3065. Vector3.FromArrayToRef = function (array, offset, result) {
  3066. result.x = array[offset];
  3067. result.y = array[offset + 1];
  3068. result.z = array[offset + 2];
  3069. };
  3070. /**
  3071. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3072. * This function is deprecated. Use FromArrayToRef instead.
  3073. * @param array defines the source array
  3074. * @param offset defines the offset in the source array
  3075. * @param result defines the Vector3 where to store the result
  3076. */
  3077. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3078. return Vector3.FromArrayToRef(array, offset, result);
  3079. };
  3080. /**
  3081. * Sets the passed vector "result" with the passed floats.
  3082. * @param x defines the x coordinate of the source
  3083. * @param y defines the y coordinate of the source
  3084. * @param z defines the z coordinate of the source
  3085. * @param result defines the Vector3 where to store the result
  3086. */
  3087. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3088. result.x = x;
  3089. result.y = y;
  3090. result.z = z;
  3091. };
  3092. /**
  3093. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3094. * @returns a new empty Vector3
  3095. */
  3096. Vector3.Zero = function () {
  3097. return new Vector3(0.0, 0.0, 0.0);
  3098. };
  3099. /**
  3100. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3101. * @returns a new unit Vector3
  3102. */
  3103. Vector3.One = function () {
  3104. return new Vector3(1.0, 1.0, 1.0);
  3105. };
  3106. /**
  3107. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3108. * @returns a new up Vector3
  3109. */
  3110. Vector3.Up = function () {
  3111. return new Vector3(0.0, 1.0, 0.0);
  3112. };
  3113. /**
  3114. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3115. * @returns a new forward Vector3
  3116. */
  3117. Vector3.Forward = function () {
  3118. return new Vector3(0.0, 0.0, 1.0);
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3122. * @returns a new right Vector3
  3123. */
  3124. Vector3.Right = function () {
  3125. return new Vector3(1.0, 0.0, 0.0);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3129. * @returns a new left Vector3
  3130. */
  3131. Vector3.Left = function () {
  3132. return new Vector3(-1.0, 0.0, 0.0);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3136. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3137. * @param vector defines the Vector3 to transform
  3138. * @param transformation defines the transformation matrix
  3139. * @returns the transformed Vector3
  3140. */
  3141. Vector3.TransformCoordinates = function (vector, transformation) {
  3142. var result = Vector3.Zero();
  3143. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3144. return result;
  3145. };
  3146. /**
  3147. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3148. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3149. * @param vector defines the Vector3 to transform
  3150. * @param transformation defines the transformation matrix
  3151. * @param result defines the Vector3 where to store the result
  3152. */
  3153. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3154. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3155. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3156. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3157. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3158. result.x = x / w;
  3159. result.y = y / w;
  3160. result.z = z / w;
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3164. * This method computes tranformed coordinates only, not transformed direction vectors
  3165. * @param x define the x coordinate of the source vector
  3166. * @param y define the y coordinate of the source vector
  3167. * @param z define the z coordinate of the source vector
  3168. * @param transformation defines the transformation matrix
  3169. * @param result defines the Vector3 where to store the result
  3170. */
  3171. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3172. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3173. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3174. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3175. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3176. result.x = rx / rw;
  3177. result.y = ry / rw;
  3178. result.z = rz / rw;
  3179. };
  3180. /**
  3181. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3182. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3183. * @param vector defines the Vector3 to transform
  3184. * @param transformation defines the transformation matrix
  3185. * @returns the new Vector3
  3186. */
  3187. Vector3.TransformNormal = function (vector, transformation) {
  3188. var result = Vector3.Zero();
  3189. Vector3.TransformNormalToRef(vector, transformation, result);
  3190. return result;
  3191. };
  3192. /**
  3193. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3194. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3195. * @param vector defines the Vector3 to transform
  3196. * @param transformation defines the transformation matrix
  3197. * @param result defines the Vector3 where to store the result
  3198. */
  3199. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3200. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3201. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3202. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3203. result.x = x;
  3204. result.y = y;
  3205. result.z = z;
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3209. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3210. * @param x define the x coordinate of the source vector
  3211. * @param y define the y coordinate of the source vector
  3212. * @param z define the z coordinate of the source vector
  3213. * @param transformation defines the transformation matrix
  3214. * @param result defines the Vector3 where to store the result
  3215. */
  3216. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3217. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3218. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3219. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3220. };
  3221. /**
  3222. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3223. * @param value1 defines the first control point
  3224. * @param value2 defines the second control point
  3225. * @param value3 defines the third control point
  3226. * @param value4 defines the fourth control point
  3227. * @param amount defines the amount on the spline to use
  3228. * @returns the new Vector3
  3229. */
  3230. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3231. var squared = amount * amount;
  3232. var cubed = amount * squared;
  3233. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3234. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3235. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3236. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3237. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3238. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3239. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3240. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3241. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3242. return new Vector3(x, y, z);
  3243. };
  3244. /**
  3245. * 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"
  3246. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3247. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3248. * @param value defines the current value
  3249. * @param min defines the lower range value
  3250. * @param max defines the upper range value
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.Clamp = function (value, min, max) {
  3254. var x = value.x;
  3255. x = (x > max.x) ? max.x : x;
  3256. x = (x < min.x) ? min.x : x;
  3257. var y = value.y;
  3258. y = (y > max.y) ? max.y : y;
  3259. y = (y < min.y) ? min.y : y;
  3260. var z = value.z;
  3261. z = (z > max.z) ? max.z : z;
  3262. z = (z < min.z) ? min.z : z;
  3263. return new Vector3(x, y, z);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3267. * @param value1 defines the first control point
  3268. * @param tangent1 defines the first tangent vector
  3269. * @param value2 defines the second control point
  3270. * @param tangent2 defines the second tangent vector
  3271. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3272. * @returns the new Vector3
  3273. */
  3274. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3275. var squared = amount * amount;
  3276. var cubed = amount * squared;
  3277. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3278. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3279. var part3 = (cubed - (2.0 * squared)) + amount;
  3280. var part4 = cubed - squared;
  3281. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3282. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3283. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3284. return new Vector3(x, y, z);
  3285. };
  3286. /**
  3287. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3288. * @param start defines the start value
  3289. * @param end defines the end value
  3290. * @param amount max defines amount between both (between 0 and 1)
  3291. * @returns the new Vector3
  3292. */
  3293. Vector3.Lerp = function (start, end, amount) {
  3294. var result = new Vector3(0, 0, 0);
  3295. Vector3.LerpToRef(start, end, amount, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3300. * @param start defines the start value
  3301. * @param end defines the end value
  3302. * @param amount max defines amount between both (between 0 and 1)
  3303. * @param result defines the Vector3 where to store the result
  3304. */
  3305. Vector3.LerpToRef = function (start, end, amount, result) {
  3306. result.x = start.x + ((end.x - start.x) * amount);
  3307. result.y = start.y + ((end.y - start.y) * amount);
  3308. result.z = start.z + ((end.z - start.z) * amount);
  3309. };
  3310. /**
  3311. * Returns the dot product (float) between the vectors "left" and "right"
  3312. * @param left defines the left operand
  3313. * @param right defines the right operand
  3314. * @returns the dot product
  3315. */
  3316. Vector3.Dot = function (left, right) {
  3317. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3321. * The cross product is then orthogonal to both "left" and "right"
  3322. * @param left defines the left operand
  3323. * @param right defines the right operand
  3324. * @returns the cross product
  3325. */
  3326. Vector3.Cross = function (left, right) {
  3327. var result = Vector3.Zero();
  3328. Vector3.CrossToRef(left, right, result);
  3329. return result;
  3330. };
  3331. /**
  3332. * Sets the passed vector "result" with the cross product of "left" and "right"
  3333. * The cross product is then orthogonal to both "left" and "right"
  3334. * @param left defines the left operand
  3335. * @param right defines the right operand
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.CrossToRef = function (left, right, result) {
  3339. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3340. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3341. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3342. result.copyFrom(MathTmp.Vector3[0]);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 as the normalization of the passed vector
  3346. * @param vector defines the Vector3 to normalize
  3347. * @returns the new Vector3
  3348. */
  3349. Vector3.Normalize = function (vector) {
  3350. var result = Vector3.Zero();
  3351. Vector3.NormalizeToRef(vector, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed vector "result" with the normalization of the passed first vector
  3356. * @param vector defines the Vector3 to normalize
  3357. * @param result defines the Vector3 where to store the result
  3358. */
  3359. Vector3.NormalizeToRef = function (vector, result) {
  3360. result.copyFrom(vector);
  3361. result.normalize();
  3362. };
  3363. /**
  3364. * Project a Vector3 onto screen space
  3365. * @param vector defines the Vector3 to project
  3366. * @param world defines the world matrix to use
  3367. * @param transform defines the transform (view x projection) matrix to use
  3368. * @param viewport defines the screen viewport to use
  3369. * @returns the new Vector3
  3370. */
  3371. Vector3.Project = function (vector, world, transform, viewport) {
  3372. var cw = viewport.width;
  3373. var ch = viewport.height;
  3374. var cx = viewport.x;
  3375. var cy = viewport.y;
  3376. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3377. 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);
  3378. var matrix = MathTmp.Matrix[0];
  3379. world.multiplyToRef(transform, matrix);
  3380. matrix.multiplyToRef(viewportMatrix, matrix);
  3381. return Vector3.TransformCoordinates(vector, matrix);
  3382. };
  3383. /**
  3384. * Unproject from screen space to object space
  3385. * @param source defines the screen space Vector3 to use
  3386. * @param viewportWidth defines the current width of the viewport
  3387. * @param viewportHeight defines the current height of the viewport
  3388. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3389. * @param transform defines the transform (view x projection) matrix to use
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3393. var matrix = MathTmp.Matrix[0];
  3394. world.multiplyToRef(transform, matrix);
  3395. matrix.invert();
  3396. source.x = source.x / viewportWidth * 2 - 1;
  3397. source.y = -(source.y / viewportHeight * 2 - 1);
  3398. var vector = Vector3.TransformCoordinates(source, matrix);
  3399. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3400. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3401. vector = vector.scale(1.0 / num);
  3402. }
  3403. return vector;
  3404. };
  3405. /**
  3406. * Unproject from screen space to object space
  3407. * @param source defines the screen space Vector3 to use
  3408. * @param viewportWidth defines the current width of the viewport
  3409. * @param viewportHeight defines the current height of the viewport
  3410. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3411. * @param view defines the view matrix to use
  3412. * @param projection defines the projection matrix to use
  3413. * @returns the new Vector3
  3414. */
  3415. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3416. var result = Vector3.Zero();
  3417. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3418. return result;
  3419. };
  3420. /**
  3421. * Unproject from screen space to object space
  3422. * @param source defines the screen space Vector3 to use
  3423. * @param viewportWidth defines the current width of the viewport
  3424. * @param viewportHeight defines the current height of the viewport
  3425. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3426. * @param view defines the view matrix to use
  3427. * @param projection defines the projection matrix to use
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3431. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3432. };
  3433. /**
  3434. * Unproject from screen space to object space
  3435. * @param sourceX defines the screen space x coordinate to use
  3436. * @param sourceY defines the screen space y coordinate to use
  3437. * @param sourceZ defines the screen space z coordinate to use
  3438. * @param viewportWidth defines the current width of the viewport
  3439. * @param viewportHeight defines the current height of the viewport
  3440. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3441. * @param view defines the view matrix to use
  3442. * @param projection defines the projection matrix to use
  3443. * @param result defines the Vector3 where to store the result
  3444. */
  3445. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3446. var matrix = MathTmp.Matrix[0];
  3447. world.multiplyToRef(view, matrix);
  3448. matrix.multiplyToRef(projection, matrix);
  3449. matrix.invert();
  3450. var screenSource = MathTmp.Vector3[0];
  3451. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3452. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3453. screenSource.z = 2 * sourceZ - 1.0;
  3454. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3455. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3456. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3457. result.scaleInPlace(1.0 / num);
  3458. }
  3459. };
  3460. /**
  3461. * Gets the minimal coordinate values between two Vector3
  3462. * @param left defines the first operand
  3463. * @param right defines the second operand
  3464. * @returns the new Vector3
  3465. */
  3466. Vector3.Minimize = function (left, right) {
  3467. var min = left.clone();
  3468. min.minimizeInPlace(right);
  3469. return min;
  3470. };
  3471. /**
  3472. * Gets the maximal coordinate values between two Vector3
  3473. * @param left defines the first operand
  3474. * @param right defines the second operand
  3475. * @returns the new Vector3
  3476. */
  3477. Vector3.Maximize = function (left, right) {
  3478. var max = left.clone();
  3479. max.maximizeInPlace(right);
  3480. return max;
  3481. };
  3482. /**
  3483. * Returns the distance between the vectors "value1" and "value2"
  3484. * @param value1 defines the first operand
  3485. * @param value2 defines the second operand
  3486. * @returns the distance
  3487. */
  3488. Vector3.Distance = function (value1, value2) {
  3489. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3490. };
  3491. /**
  3492. * Returns the squared distance between the vectors "value1" and "value2"
  3493. * @param value1 defines the first operand
  3494. * @param value2 defines the second operand
  3495. * @returns the squared distance
  3496. */
  3497. Vector3.DistanceSquared = function (value1, value2) {
  3498. var x = value1.x - value2.x;
  3499. var y = value1.y - value2.y;
  3500. var z = value1.z - value2.z;
  3501. return (x * x) + (y * y) + (z * z);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 located at the center between "value1" and "value2"
  3505. * @param value1 defines the first operand
  3506. * @param value2 defines the second operand
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Center = function (value1, value2) {
  3510. var center = value1.add(value2);
  3511. center.scaleInPlace(0.5);
  3512. return center;
  3513. };
  3514. /**
  3515. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3516. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3517. * to something in order to rotate it from its local system to the given target system
  3518. * Note: axis1, axis2 and axis3 are normalized during this operation
  3519. * @param axis1 defines the first axis
  3520. * @param axis2 defines the second axis
  3521. * @param axis3 defines the third axis
  3522. * @returns a new Vector3
  3523. */
  3524. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3525. var rotation = Vector3.Zero();
  3526. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3527. return rotation;
  3528. };
  3529. /**
  3530. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3531. * @param axis1 defines the first axis
  3532. * @param axis2 defines the second axis
  3533. * @param axis3 defines the third axis
  3534. * @param ref defines the Vector3 where to store the result
  3535. */
  3536. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3537. var quat = MathTmp.Quaternion[0];
  3538. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3539. quat.toEulerAnglesToRef(ref);
  3540. };
  3541. return Vector3;
  3542. }());
  3543. BABYLON.Vector3 = Vector3;
  3544. //Vector4 class created for EulerAngle class conversion to Quaternion
  3545. var Vector4 = /** @class */ (function () {
  3546. /**
  3547. * Creates a Vector4 object from the passed floats.
  3548. */
  3549. function Vector4(x, y, z, w) {
  3550. this.x = x;
  3551. this.y = y;
  3552. this.z = z;
  3553. this.w = w;
  3554. }
  3555. /**
  3556. * Returns the string with the Vector4 coordinates.
  3557. */
  3558. Vector4.prototype.toString = function () {
  3559. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3560. };
  3561. /**
  3562. * Returns the string "Vector4".
  3563. */
  3564. Vector4.prototype.getClassName = function () {
  3565. return "Vector4";
  3566. };
  3567. /**
  3568. * Returns the Vector4 hash code.
  3569. */
  3570. Vector4.prototype.getHashCode = function () {
  3571. var hash = this.x || 0;
  3572. hash = (hash * 397) ^ (this.y || 0);
  3573. hash = (hash * 397) ^ (this.z || 0);
  3574. hash = (hash * 397) ^ (this.w || 0);
  3575. return hash;
  3576. };
  3577. // Operators
  3578. /**
  3579. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3580. */
  3581. Vector4.prototype.asArray = function () {
  3582. var result = new Array();
  3583. this.toArray(result, 0);
  3584. return result;
  3585. };
  3586. /**
  3587. * Populates the passed array from the passed index with the Vector4 coordinates.
  3588. * Returns the Vector4.
  3589. */
  3590. Vector4.prototype.toArray = function (array, index) {
  3591. if (index === undefined) {
  3592. index = 0;
  3593. }
  3594. array[index] = this.x;
  3595. array[index + 1] = this.y;
  3596. array[index + 2] = this.z;
  3597. array[index + 3] = this.w;
  3598. return this;
  3599. };
  3600. /**
  3601. * Adds the passed vector to the current Vector4.
  3602. * Returns the updated Vector4.
  3603. */
  3604. Vector4.prototype.addInPlace = function (otherVector) {
  3605. this.x += otherVector.x;
  3606. this.y += otherVector.y;
  3607. this.z += otherVector.z;
  3608. this.w += otherVector.w;
  3609. return this;
  3610. };
  3611. /**
  3612. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3613. */
  3614. Vector4.prototype.add = function (otherVector) {
  3615. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3616. };
  3617. /**
  3618. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3619. * Returns the current Vector4.
  3620. */
  3621. Vector4.prototype.addToRef = function (otherVector, result) {
  3622. result.x = this.x + otherVector.x;
  3623. result.y = this.y + otherVector.y;
  3624. result.z = this.z + otherVector.z;
  3625. result.w = this.w + otherVector.w;
  3626. return this;
  3627. };
  3628. /**
  3629. * Subtract in place the passed vector from the current Vector4.
  3630. * Returns the updated Vector4.
  3631. */
  3632. Vector4.prototype.subtractInPlace = function (otherVector) {
  3633. this.x -= otherVector.x;
  3634. this.y -= otherVector.y;
  3635. this.z -= otherVector.z;
  3636. this.w -= otherVector.w;
  3637. return this;
  3638. };
  3639. /**
  3640. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3641. */
  3642. Vector4.prototype.subtract = function (otherVector) {
  3643. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3644. };
  3645. /**
  3646. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3647. * Returns the current Vector4.
  3648. */
  3649. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3650. result.x = this.x - otherVector.x;
  3651. result.y = this.y - otherVector.y;
  3652. result.z = this.z - otherVector.z;
  3653. result.w = this.w - otherVector.w;
  3654. return this;
  3655. };
  3656. /**
  3657. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3658. */
  3659. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3660. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3661. };
  3662. /**
  3663. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3664. * Returns the current Vector4.
  3665. */
  3666. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3667. result.x = this.x - x;
  3668. result.y = this.y - y;
  3669. result.z = this.z - z;
  3670. result.w = this.w - w;
  3671. return this;
  3672. };
  3673. /**
  3674. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3675. */
  3676. Vector4.prototype.negate = function () {
  3677. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3678. };
  3679. /**
  3680. * Multiplies the current Vector4 coordinates by scale (float).
  3681. * Returns the updated Vector4.
  3682. */
  3683. Vector4.prototype.scaleInPlace = function (scale) {
  3684. this.x *= scale;
  3685. this.y *= scale;
  3686. this.z *= scale;
  3687. this.w *= scale;
  3688. return this;
  3689. };
  3690. /**
  3691. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3692. */
  3693. Vector4.prototype.scale = function (scale) {
  3694. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3695. };
  3696. /**
  3697. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3698. * Returns the current Vector4.
  3699. */
  3700. Vector4.prototype.scaleToRef = function (scale, result) {
  3701. result.x = this.x * scale;
  3702. result.y = this.y * scale;
  3703. result.z = this.z * scale;
  3704. result.w = this.w * scale;
  3705. return this;
  3706. };
  3707. /**
  3708. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3709. */
  3710. Vector4.prototype.equals = function (otherVector) {
  3711. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3712. };
  3713. /**
  3714. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3715. */
  3716. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3717. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3718. return otherVector
  3719. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3720. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3721. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3722. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3723. };
  3724. /**
  3725. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3726. */
  3727. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3728. return this.x === x && this.y === y && this.z === z && this.w === w;
  3729. };
  3730. /**
  3731. * Multiplies in place the current Vector4 by the passed one.
  3732. * Returns the updated Vector4.
  3733. */
  3734. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3735. this.x *= otherVector.x;
  3736. this.y *= otherVector.y;
  3737. this.z *= otherVector.z;
  3738. this.w *= otherVector.w;
  3739. return this;
  3740. };
  3741. /**
  3742. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3743. */
  3744. Vector4.prototype.multiply = function (otherVector) {
  3745. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3746. };
  3747. /**
  3748. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3749. * Returns the current Vector4.
  3750. */
  3751. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3752. result.x = this.x * otherVector.x;
  3753. result.y = this.y * otherVector.y;
  3754. result.z = this.z * otherVector.z;
  3755. result.w = this.w * otherVector.w;
  3756. return this;
  3757. };
  3758. /**
  3759. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3760. */
  3761. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3762. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3763. };
  3764. /**
  3765. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3766. */
  3767. Vector4.prototype.divide = function (otherVector) {
  3768. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3769. };
  3770. /**
  3771. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3772. * Returns the current Vector4.
  3773. */
  3774. Vector4.prototype.divideToRef = function (otherVector, result) {
  3775. result.x = this.x / otherVector.x;
  3776. result.y = this.y / otherVector.y;
  3777. result.z = this.z / otherVector.z;
  3778. result.w = this.w / otherVector.w;
  3779. return this;
  3780. };
  3781. /**
  3782. * Divides the current Vector3 coordinates by the passed ones.
  3783. * @returns the updated Vector3.
  3784. */
  3785. Vector4.prototype.divideInPlace = function (otherVector) {
  3786. return this.divideToRef(otherVector, this);
  3787. };
  3788. /**
  3789. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3790. * @param other defines the second operand
  3791. * @returns the current updated Vector4
  3792. */
  3793. Vector4.prototype.minimizeInPlace = function (other) {
  3794. if (other.x < this.x)
  3795. this.x = other.x;
  3796. if (other.y < this.y)
  3797. this.y = other.y;
  3798. if (other.z < this.z)
  3799. this.z = other.z;
  3800. if (other.w < this.w)
  3801. this.w = other.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3806. * @param other defines the second operand
  3807. * @returns the current updated Vector4
  3808. */
  3809. Vector4.prototype.maximizeInPlace = function (other) {
  3810. if (other.x > this.x)
  3811. this.x = other.x;
  3812. if (other.y > this.y)
  3813. this.y = other.y;
  3814. if (other.z > this.z)
  3815. this.z = other.z;
  3816. if (other.w > this.w)
  3817. this.w = other.w;
  3818. return this;
  3819. };
  3820. // Properties
  3821. /**
  3822. * Returns the Vector4 length (float).
  3823. */
  3824. Vector4.prototype.length = function () {
  3825. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3826. };
  3827. /**
  3828. * Returns the Vector4 squared length (float).
  3829. */
  3830. Vector4.prototype.lengthSquared = function () {
  3831. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3832. };
  3833. // Methods
  3834. /**
  3835. * Normalizes in place the Vector4.
  3836. * Returns the updated Vector4.
  3837. */
  3838. Vector4.prototype.normalize = function () {
  3839. var len = this.length();
  3840. if (len === 0)
  3841. return this;
  3842. var num = 1.0 / len;
  3843. this.x *= num;
  3844. this.y *= num;
  3845. this.z *= num;
  3846. this.w *= num;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3851. */
  3852. Vector4.prototype.toVector3 = function () {
  3853. return new Vector3(this.x, this.y, this.z);
  3854. };
  3855. /**
  3856. * Returns a new Vector4 copied from the current one.
  3857. */
  3858. Vector4.prototype.clone = function () {
  3859. return new Vector4(this.x, this.y, this.z, this.w);
  3860. };
  3861. /**
  3862. * Updates the current Vector4 with the passed one coordinates.
  3863. * Returns the updated Vector4.
  3864. */
  3865. Vector4.prototype.copyFrom = function (source) {
  3866. this.x = source.x;
  3867. this.y = source.y;
  3868. this.z = source.z;
  3869. this.w = source.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Updates the current Vector4 coordinates with the passed floats.
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3877. this.x = x;
  3878. this.y = y;
  3879. this.z = z;
  3880. this.w = w;
  3881. return this;
  3882. };
  3883. /**
  3884. * Updates the current Vector4 coordinates with the passed floats.
  3885. * Returns the updated Vector4.
  3886. */
  3887. Vector4.prototype.set = function (x, y, z, w) {
  3888. return this.copyFromFloats(x, y, z, w);
  3889. };
  3890. // Statics
  3891. /**
  3892. * Returns a new Vector4 set from the starting index of the passed array.
  3893. */
  3894. Vector4.FromArray = function (array, offset) {
  3895. if (!offset) {
  3896. offset = 0;
  3897. }
  3898. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3899. };
  3900. /**
  3901. * Updates the passed vector "result" from the starting index of the passed array.
  3902. */
  3903. Vector4.FromArrayToRef = function (array, offset, result) {
  3904. result.x = array[offset];
  3905. result.y = array[offset + 1];
  3906. result.z = array[offset + 2];
  3907. result.w = array[offset + 3];
  3908. };
  3909. /**
  3910. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3911. */
  3912. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3913. Vector4.FromArrayToRef(array, offset, result);
  3914. };
  3915. /**
  3916. * Updates the passed vector "result" coordinates from the passed floats.
  3917. */
  3918. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3919. result.x = x;
  3920. result.y = y;
  3921. result.z = z;
  3922. result.w = w;
  3923. };
  3924. /**
  3925. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3926. */
  3927. Vector4.Zero = function () {
  3928. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3929. };
  3930. /**
  3931. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3932. */
  3933. Vector4.One = function () {
  3934. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3935. };
  3936. /**
  3937. * Returns a new normalized Vector4 from the passed one.
  3938. */
  3939. Vector4.Normalize = function (vector) {
  3940. var result = Vector4.Zero();
  3941. Vector4.NormalizeToRef(vector, result);
  3942. return result;
  3943. };
  3944. /**
  3945. * Updates the passed vector "result" from the normalization of the passed one.
  3946. */
  3947. Vector4.NormalizeToRef = function (vector, result) {
  3948. result.copyFrom(vector);
  3949. result.normalize();
  3950. };
  3951. Vector4.Minimize = function (left, right) {
  3952. var min = left.clone();
  3953. min.minimizeInPlace(right);
  3954. return min;
  3955. };
  3956. Vector4.Maximize = function (left, right) {
  3957. var max = left.clone();
  3958. max.maximizeInPlace(right);
  3959. return max;
  3960. };
  3961. /**
  3962. * Returns the distance (float) between the vectors "value1" and "value2".
  3963. */
  3964. Vector4.Distance = function (value1, value2) {
  3965. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3966. };
  3967. /**
  3968. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3969. */
  3970. Vector4.DistanceSquared = function (value1, value2) {
  3971. var x = value1.x - value2.x;
  3972. var y = value1.y - value2.y;
  3973. var z = value1.z - value2.z;
  3974. var w = value1.w - value2.w;
  3975. return (x * x) + (y * y) + (z * z) + (w * w);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3979. */
  3980. Vector4.Center = function (value1, value2) {
  3981. var center = value1.add(value2);
  3982. center.scaleInPlace(0.5);
  3983. return center;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3987. * This methods computes transformed normalized direction vectors only.
  3988. */
  3989. Vector4.TransformNormal = function (vector, transformation) {
  3990. var result = Vector4.Zero();
  3991. Vector4.TransformNormalToRef(vector, transformation, result);
  3992. return result;
  3993. };
  3994. /**
  3995. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3996. * This methods computes transformed normalized direction vectors only.
  3997. */
  3998. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3999. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4000. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4001. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4002. result.x = x;
  4003. result.y = y;
  4004. result.z = z;
  4005. result.w = vector.w;
  4006. };
  4007. /**
  4008. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4009. * This methods computes transformed normalized direction vectors only.
  4010. */
  4011. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4012. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4013. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4014. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4015. result.w = w;
  4016. };
  4017. return Vector4;
  4018. }());
  4019. BABYLON.Vector4 = Vector4;
  4020. var Size = /** @class */ (function () {
  4021. /**
  4022. * Creates a Size object from the passed width and height (floats).
  4023. */
  4024. function Size(width, height) {
  4025. this.width = width;
  4026. this.height = height;
  4027. }
  4028. // Returns a string with the Size width and height.
  4029. Size.prototype.toString = function () {
  4030. return "{W: " + this.width + ", H: " + this.height + "}";
  4031. };
  4032. /**
  4033. * Returns the string "Size"
  4034. */
  4035. Size.prototype.getClassName = function () {
  4036. return "Size";
  4037. };
  4038. /**
  4039. * Returns the Size hash code.
  4040. */
  4041. Size.prototype.getHashCode = function () {
  4042. var hash = this.width || 0;
  4043. hash = (hash * 397) ^ (this.height || 0);
  4044. return hash;
  4045. };
  4046. /**
  4047. * Updates the current size from the passed one.
  4048. * Returns the updated Size.
  4049. */
  4050. Size.prototype.copyFrom = function (src) {
  4051. this.width = src.width;
  4052. this.height = src.height;
  4053. };
  4054. /**
  4055. * Updates in place the current Size from the passed floats.
  4056. * Returns the updated Size.
  4057. */
  4058. Size.prototype.copyFromFloats = function (width, height) {
  4059. this.width = width;
  4060. this.height = height;
  4061. return this;
  4062. };
  4063. /**
  4064. * Updates in place the current Size from the passed floats.
  4065. * Returns the updated Size.
  4066. */
  4067. Size.prototype.set = function (width, height) {
  4068. return this.copyFromFloats(width, height);
  4069. };
  4070. /**
  4071. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4072. */
  4073. Size.prototype.multiplyByFloats = function (w, h) {
  4074. return new Size(this.width * w, this.height * h);
  4075. };
  4076. /**
  4077. * Returns a new Size copied from the passed one.
  4078. */
  4079. Size.prototype.clone = function () {
  4080. return new Size(this.width, this.height);
  4081. };
  4082. /**
  4083. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4084. */
  4085. Size.prototype.equals = function (other) {
  4086. if (!other) {
  4087. return false;
  4088. }
  4089. return (this.width === other.width) && (this.height === other.height);
  4090. };
  4091. Object.defineProperty(Size.prototype, "surface", {
  4092. /**
  4093. * Returns the surface of the Size : width * height (float).
  4094. */
  4095. get: function () {
  4096. return this.width * this.height;
  4097. },
  4098. enumerable: true,
  4099. configurable: true
  4100. });
  4101. /**
  4102. * Returns a new Size set to (0.0, 0.0)
  4103. */
  4104. Size.Zero = function () {
  4105. return new Size(0.0, 0.0);
  4106. };
  4107. /**
  4108. * Returns a new Size set as the addition result of the current Size and the passed one.
  4109. */
  4110. Size.prototype.add = function (otherSize) {
  4111. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4112. return r;
  4113. };
  4114. /**
  4115. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4116. */
  4117. Size.prototype.subtract = function (otherSize) {
  4118. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4119. return r;
  4120. };
  4121. /**
  4122. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4123. */
  4124. Size.Lerp = function (start, end, amount) {
  4125. var w = start.width + ((end.width - start.width) * amount);
  4126. var h = start.height + ((end.height - start.height) * amount);
  4127. return new Size(w, h);
  4128. };
  4129. return Size;
  4130. }());
  4131. BABYLON.Size = Size;
  4132. var Quaternion = /** @class */ (function () {
  4133. /**
  4134. * Creates a new Quaternion from the passed floats.
  4135. */
  4136. function Quaternion(x, y, z, w) {
  4137. if (x === void 0) { x = 0.0; }
  4138. if (y === void 0) { y = 0.0; }
  4139. if (z === void 0) { z = 0.0; }
  4140. if (w === void 0) { w = 1.0; }
  4141. this.x = x;
  4142. this.y = y;
  4143. this.z = z;
  4144. this.w = w;
  4145. }
  4146. /**
  4147. * Returns a string with the Quaternion coordinates.
  4148. */
  4149. Quaternion.prototype.toString = function () {
  4150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4151. };
  4152. /**
  4153. * Returns the string "Quaternion".
  4154. */
  4155. Quaternion.prototype.getClassName = function () {
  4156. return "Quaternion";
  4157. };
  4158. /**
  4159. * Returns the Quaternion hash code.
  4160. */
  4161. Quaternion.prototype.getHashCode = function () {
  4162. var hash = this.x || 0;
  4163. hash = (hash * 397) ^ (this.y || 0);
  4164. hash = (hash * 397) ^ (this.z || 0);
  4165. hash = (hash * 397) ^ (this.w || 0);
  4166. return hash;
  4167. };
  4168. /**
  4169. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4170. */
  4171. Quaternion.prototype.asArray = function () {
  4172. return [this.x, this.y, this.z, this.w];
  4173. };
  4174. /**
  4175. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4176. */
  4177. Quaternion.prototype.equals = function (otherQuaternion) {
  4178. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4179. };
  4180. /**
  4181. * Returns a new Quaternion copied from the current one.
  4182. */
  4183. Quaternion.prototype.clone = function () {
  4184. return new Quaternion(this.x, this.y, this.z, this.w);
  4185. };
  4186. /**
  4187. * Updates the current Quaternion from the passed one coordinates.
  4188. * Returns the updated Quaterion.
  4189. */
  4190. Quaternion.prototype.copyFrom = function (other) {
  4191. this.x = other.x;
  4192. this.y = other.y;
  4193. this.z = other.z;
  4194. this.w = other.w;
  4195. return this;
  4196. };
  4197. /**
  4198. * Updates the current Quaternion from the passed float coordinates.
  4199. * Returns the updated Quaterion.
  4200. */
  4201. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4202. this.x = x;
  4203. this.y = y;
  4204. this.z = z;
  4205. this.w = w;
  4206. return this;
  4207. };
  4208. /**
  4209. * Updates the current Quaternion from the passed float coordinates.
  4210. * Returns the updated Quaterion.
  4211. */
  4212. Quaternion.prototype.set = function (x, y, z, w) {
  4213. return this.copyFromFloats(x, y, z, w);
  4214. };
  4215. /**
  4216. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4217. */
  4218. Quaternion.prototype.add = function (other) {
  4219. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4220. };
  4221. /**
  4222. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4223. */
  4224. Quaternion.prototype.subtract = function (other) {
  4225. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4226. };
  4227. /**
  4228. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4229. */
  4230. Quaternion.prototype.scale = function (value) {
  4231. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4232. };
  4233. /**
  4234. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4235. */
  4236. Quaternion.prototype.multiply = function (q1) {
  4237. var result = new Quaternion(0, 0, 0, 1.0);
  4238. this.multiplyToRef(q1, result);
  4239. return result;
  4240. };
  4241. /**
  4242. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4243. * Returns the current Quaternion.
  4244. */
  4245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4250. result.copyFromFloats(x, y, z, w);
  4251. return this;
  4252. };
  4253. /**
  4254. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4255. * Returns the updated Quaternion.
  4256. */
  4257. Quaternion.prototype.multiplyInPlace = function (q1) {
  4258. this.multiplyToRef(q1, this);
  4259. return this;
  4260. };
  4261. /**
  4262. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4263. * Returns the current Quaternion.
  4264. */
  4265. Quaternion.prototype.conjugateToRef = function (ref) {
  4266. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4267. return this;
  4268. };
  4269. /**
  4270. * Conjugates in place the current Quaternion.
  4271. * Returns the updated Quaternion.
  4272. */
  4273. Quaternion.prototype.conjugateInPlace = function () {
  4274. this.x *= -1;
  4275. this.y *= -1;
  4276. this.z *= -1;
  4277. return this;
  4278. };
  4279. /**
  4280. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4281. */
  4282. Quaternion.prototype.conjugate = function () {
  4283. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4284. return result;
  4285. };
  4286. /**
  4287. * Returns the Quaternion length (float).
  4288. */
  4289. Quaternion.prototype.length = function () {
  4290. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4291. };
  4292. /**
  4293. * Normalize in place the current Quaternion.
  4294. * Returns the updated Quaternion.
  4295. */
  4296. Quaternion.prototype.normalize = function () {
  4297. var length = 1.0 / this.length();
  4298. this.x *= length;
  4299. this.y *= length;
  4300. this.z *= length;
  4301. this.w *= length;
  4302. return this;
  4303. };
  4304. /**
  4305. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4306. */
  4307. Quaternion.prototype.toEulerAngles = function (order) {
  4308. if (order === void 0) { order = "YZX"; }
  4309. var result = Vector3.Zero();
  4310. this.toEulerAnglesToRef(result, order);
  4311. return result;
  4312. };
  4313. /**
  4314. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4315. * Returns the current Quaternion.
  4316. */
  4317. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4318. if (order === void 0) { order = "YZX"; }
  4319. var qz = this.z;
  4320. var qx = this.x;
  4321. var qy = this.y;
  4322. var qw = this.w;
  4323. var sqw = qw * qw;
  4324. var sqz = qz * qz;
  4325. var sqx = qx * qx;
  4326. var sqy = qy * qy;
  4327. var zAxisY = qy * qz - qx * qw;
  4328. var limit = .4999999;
  4329. if (zAxisY < -limit) {
  4330. result.y = 2 * Math.atan2(qy, qw);
  4331. result.x = Math.PI / 2;
  4332. result.z = 0;
  4333. }
  4334. else if (zAxisY > limit) {
  4335. result.y = 2 * Math.atan2(qy, qw);
  4336. result.x = -Math.PI / 2;
  4337. result.z = 0;
  4338. }
  4339. else {
  4340. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4341. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4342. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4343. }
  4344. return this;
  4345. };
  4346. /**
  4347. * Updates the passed rotation matrix with the current Quaternion values.
  4348. * Returns the current Quaternion.
  4349. */
  4350. Quaternion.prototype.toRotationMatrix = function (result) {
  4351. var xx = this.x * this.x;
  4352. var yy = this.y * this.y;
  4353. var zz = this.z * this.z;
  4354. var xy = this.x * this.y;
  4355. var zw = this.z * this.w;
  4356. var zx = this.z * this.x;
  4357. var yw = this.y * this.w;
  4358. var yz = this.y * this.z;
  4359. var xw = this.x * this.w;
  4360. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4361. result.m[1] = 2.0 * (xy + zw);
  4362. result.m[2] = 2.0 * (zx - yw);
  4363. result.m[3] = 0;
  4364. result.m[4] = 2.0 * (xy - zw);
  4365. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4366. result.m[6] = 2.0 * (yz + xw);
  4367. result.m[7] = 0;
  4368. result.m[8] = 2.0 * (zx + yw);
  4369. result.m[9] = 2.0 * (yz - xw);
  4370. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4371. result.m[11] = 0;
  4372. result.m[12] = 0;
  4373. result.m[13] = 0;
  4374. result.m[14] = 0;
  4375. result.m[15] = 1.0;
  4376. result._markAsUpdated();
  4377. return this;
  4378. };
  4379. /**
  4380. * Updates the current Quaternion from the passed rotation matrix values.
  4381. * Returns the updated Quaternion.
  4382. */
  4383. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4384. Quaternion.FromRotationMatrixToRef(matrix, this);
  4385. return this;
  4386. };
  4387. // Statics
  4388. /**
  4389. * Returns a new Quaternion set from the passed rotation matrix values.
  4390. */
  4391. Quaternion.FromRotationMatrix = function (matrix) {
  4392. var result = new Quaternion();
  4393. Quaternion.FromRotationMatrixToRef(matrix, result);
  4394. return result;
  4395. };
  4396. /**
  4397. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4398. */
  4399. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4400. var data = matrix.m;
  4401. var m11 = data[0], m12 = data[4], m13 = data[8];
  4402. var m21 = data[1], m22 = data[5], m23 = data[9];
  4403. var m31 = data[2], m32 = data[6], m33 = data[10];
  4404. var trace = m11 + m22 + m33;
  4405. var s;
  4406. if (trace > 0) {
  4407. s = 0.5 / Math.sqrt(trace + 1.0);
  4408. result.w = 0.25 / s;
  4409. result.x = (m32 - m23) * s;
  4410. result.y = (m13 - m31) * s;
  4411. result.z = (m21 - m12) * s;
  4412. }
  4413. else if (m11 > m22 && m11 > m33) {
  4414. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4415. result.w = (m32 - m23) / s;
  4416. result.x = 0.25 * s;
  4417. result.y = (m12 + m21) / s;
  4418. result.z = (m13 + m31) / s;
  4419. }
  4420. else if (m22 > m33) {
  4421. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4422. result.w = (m13 - m31) / s;
  4423. result.x = (m12 + m21) / s;
  4424. result.y = 0.25 * s;
  4425. result.z = (m23 + m32) / s;
  4426. }
  4427. else {
  4428. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4429. result.w = (m21 - m12) / s;
  4430. result.x = (m13 + m31) / s;
  4431. result.y = (m23 + m32) / s;
  4432. result.z = 0.25 * s;
  4433. }
  4434. };
  4435. /**
  4436. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4437. */
  4438. Quaternion.Zero = function () {
  4439. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4440. };
  4441. /**
  4442. * Returns a new Quaternion as the inverted current Quaternion.
  4443. */
  4444. Quaternion.Inverse = function (q) {
  4445. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4446. };
  4447. /**
  4448. * Returns the identity Quaternion.
  4449. */
  4450. Quaternion.Identity = function () {
  4451. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4452. };
  4453. Quaternion.IsIdentity = function (quaternion) {
  4454. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4455. };
  4456. /**
  4457. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4458. */
  4459. Quaternion.RotationAxis = function (axis, angle) {
  4460. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4461. };
  4462. /**
  4463. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4464. */
  4465. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4466. var sin = Math.sin(angle / 2);
  4467. axis.normalize();
  4468. result.w = Math.cos(angle / 2);
  4469. result.x = axis.x * sin;
  4470. result.y = axis.y * sin;
  4471. result.z = axis.z * sin;
  4472. return result;
  4473. };
  4474. /**
  4475. * Retuns a new Quaternion set from the starting index of the passed array.
  4476. */
  4477. Quaternion.FromArray = function (array, offset) {
  4478. if (!offset) {
  4479. offset = 0;
  4480. }
  4481. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4482. };
  4483. /**
  4484. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4485. */
  4486. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4487. var q = new Quaternion();
  4488. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4489. return q;
  4490. };
  4491. /**
  4492. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4493. */
  4494. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4495. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4496. var halfRoll = roll * 0.5;
  4497. var halfPitch = pitch * 0.5;
  4498. var halfYaw = yaw * 0.5;
  4499. var sinRoll = Math.sin(halfRoll);
  4500. var cosRoll = Math.cos(halfRoll);
  4501. var sinPitch = Math.sin(halfPitch);
  4502. var cosPitch = Math.cos(halfPitch);
  4503. var sinYaw = Math.sin(halfYaw);
  4504. var cosYaw = Math.cos(halfYaw);
  4505. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4506. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4507. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4508. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4509. };
  4510. /**
  4511. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4512. */
  4513. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4514. var result = new Quaternion();
  4515. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4520. */
  4521. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4522. // Produces a quaternion from Euler angles in the z-x-z orientation
  4523. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4524. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4525. var halfBeta = beta * 0.5;
  4526. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4527. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4528. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4529. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4530. };
  4531. /**
  4532. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4533. * cf to Vector3.RotationFromAxis() documentation.
  4534. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4535. */
  4536. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4537. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4538. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4539. return quat;
  4540. };
  4541. /**
  4542. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4543. * cf to Vector3.RotationFromAxis() documentation.
  4544. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4545. */
  4546. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4547. var rotMat = MathTmp.Matrix[0];
  4548. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4549. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4550. };
  4551. Quaternion.Slerp = function (left, right, amount) {
  4552. var result = Quaternion.Identity();
  4553. Quaternion.SlerpToRef(left, right, amount, result);
  4554. return result;
  4555. };
  4556. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4557. var num2;
  4558. var num3;
  4559. var num = amount;
  4560. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4561. var flag = false;
  4562. if (num4 < 0) {
  4563. flag = true;
  4564. num4 = -num4;
  4565. }
  4566. if (num4 > 0.999999) {
  4567. num3 = 1 - num;
  4568. num2 = flag ? -num : num;
  4569. }
  4570. else {
  4571. var num5 = Math.acos(num4);
  4572. var num6 = (1.0 / Math.sin(num5));
  4573. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4574. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4575. }
  4576. result.x = (num3 * left.x) + (num2 * right.x);
  4577. result.y = (num3 * left.y) + (num2 * right.y);
  4578. result.z = (num3 * left.z) + (num2 * right.z);
  4579. result.w = (num3 * left.w) + (num2 * right.w);
  4580. };
  4581. /**
  4582. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4583. */
  4584. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4585. var squared = amount * amount;
  4586. var cubed = amount * squared;
  4587. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4588. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4589. var part3 = (cubed - (2.0 * squared)) + amount;
  4590. var part4 = cubed - squared;
  4591. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4592. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4593. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4594. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4595. return new Quaternion(x, y, z, w);
  4596. };
  4597. return Quaternion;
  4598. }());
  4599. BABYLON.Quaternion = Quaternion;
  4600. var Matrix = /** @class */ (function () {
  4601. function Matrix() {
  4602. this._isIdentity = false;
  4603. this._isIdentityDirty = true;
  4604. this.m = new Float32Array(16);
  4605. this._markAsUpdated();
  4606. }
  4607. Matrix.prototype._markAsUpdated = function () {
  4608. this.updateFlag = Matrix._updateFlagSeed++;
  4609. this._isIdentityDirty = true;
  4610. };
  4611. // Properties
  4612. /**
  4613. * Boolean : True is the matrix is the identity matrix
  4614. */
  4615. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4616. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4617. if (this._isIdentityDirty) {
  4618. this._isIdentityDirty = false;
  4619. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4620. this._isIdentity = false;
  4621. }
  4622. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4623. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4624. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4625. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4626. this._isIdentity = false;
  4627. }
  4628. else {
  4629. this._isIdentity = true;
  4630. }
  4631. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4632. this._isIdentity = false;
  4633. }
  4634. }
  4635. return this._isIdentity;
  4636. };
  4637. /**
  4638. * Returns the matrix determinant (float).
  4639. */
  4640. Matrix.prototype.determinant = function () {
  4641. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4642. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4643. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4644. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4645. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4646. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4647. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4648. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4649. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4650. };
  4651. // Methods
  4652. /**
  4653. * Returns the matrix underlying array.
  4654. */
  4655. Matrix.prototype.toArray = function () {
  4656. return this.m;
  4657. };
  4658. /**
  4659. * Returns the matrix underlying array.
  4660. */
  4661. Matrix.prototype.asArray = function () {
  4662. return this.toArray();
  4663. };
  4664. /**
  4665. * Inverts in place the Matrix.
  4666. * Returns the Matrix inverted.
  4667. */
  4668. Matrix.prototype.invert = function () {
  4669. this.invertToRef(this);
  4670. return this;
  4671. };
  4672. /**
  4673. * Sets all the matrix elements to zero.
  4674. * Returns the Matrix.
  4675. */
  4676. Matrix.prototype.reset = function () {
  4677. for (var index = 0; index < 16; index++) {
  4678. this.m[index] = 0.0;
  4679. }
  4680. this._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4685. */
  4686. Matrix.prototype.add = function (other) {
  4687. var result = new Matrix();
  4688. this.addToRef(other, result);
  4689. return result;
  4690. };
  4691. /**
  4692. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4693. * Returns the Matrix.
  4694. */
  4695. Matrix.prototype.addToRef = function (other, result) {
  4696. for (var index = 0; index < 16; index++) {
  4697. result.m[index] = this.m[index] + other.m[index];
  4698. }
  4699. result._markAsUpdated();
  4700. return this;
  4701. };
  4702. /**
  4703. * Adds in place the passed matrix to the current Matrix.
  4704. * Returns the updated Matrix.
  4705. */
  4706. Matrix.prototype.addToSelf = function (other) {
  4707. for (var index = 0; index < 16; index++) {
  4708. this.m[index] += other.m[index];
  4709. }
  4710. this._markAsUpdated();
  4711. return this;
  4712. };
  4713. /**
  4714. * Sets the passed matrix with the current inverted Matrix.
  4715. * Returns the unmodified current Matrix.
  4716. */
  4717. Matrix.prototype.invertToRef = function (other) {
  4718. var l1 = this.m[0];
  4719. var l2 = this.m[1];
  4720. var l3 = this.m[2];
  4721. var l4 = this.m[3];
  4722. var l5 = this.m[4];
  4723. var l6 = this.m[5];
  4724. var l7 = this.m[6];
  4725. var l8 = this.m[7];
  4726. var l9 = this.m[8];
  4727. var l10 = this.m[9];
  4728. var l11 = this.m[10];
  4729. var l12 = this.m[11];
  4730. var l13 = this.m[12];
  4731. var l14 = this.m[13];
  4732. var l15 = this.m[14];
  4733. var l16 = this.m[15];
  4734. var l17 = (l11 * l16) - (l12 * l15);
  4735. var l18 = (l10 * l16) - (l12 * l14);
  4736. var l19 = (l10 * l15) - (l11 * l14);
  4737. var l20 = (l9 * l16) - (l12 * l13);
  4738. var l21 = (l9 * l15) - (l11 * l13);
  4739. var l22 = (l9 * l14) - (l10 * l13);
  4740. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4741. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4742. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4743. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4744. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4745. var l28 = (l7 * l16) - (l8 * l15);
  4746. var l29 = (l6 * l16) - (l8 * l14);
  4747. var l30 = (l6 * l15) - (l7 * l14);
  4748. var l31 = (l5 * l16) - (l8 * l13);
  4749. var l32 = (l5 * l15) - (l7 * l13);
  4750. var l33 = (l5 * l14) - (l6 * l13);
  4751. var l34 = (l7 * l12) - (l8 * l11);
  4752. var l35 = (l6 * l12) - (l8 * l10);
  4753. var l36 = (l6 * l11) - (l7 * l10);
  4754. var l37 = (l5 * l12) - (l8 * l9);
  4755. var l38 = (l5 * l11) - (l7 * l9);
  4756. var l39 = (l5 * l10) - (l6 * l9);
  4757. other.m[0] = l23 * l27;
  4758. other.m[4] = l24 * l27;
  4759. other.m[8] = l25 * l27;
  4760. other.m[12] = l26 * l27;
  4761. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4762. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4763. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4764. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4765. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4766. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4767. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4768. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4769. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4770. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4771. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4772. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4773. other._markAsUpdated();
  4774. return this;
  4775. };
  4776. /**
  4777. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4778. * Returns the updated Matrix.
  4779. */
  4780. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4781. this.m[12] = x;
  4782. this.m[13] = y;
  4783. this.m[14] = z;
  4784. this._markAsUpdated();
  4785. return this;
  4786. };
  4787. /**
  4788. * Inserts the translation vector in the current Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.setTranslation = function (vector3) {
  4792. this.m[12] = vector3.x;
  4793. this.m[13] = vector3.y;
  4794. this.m[14] = vector3.z;
  4795. this._markAsUpdated();
  4796. return this;
  4797. };
  4798. /**
  4799. * Returns a new Vector3 as the extracted translation from the Matrix.
  4800. */
  4801. Matrix.prototype.getTranslation = function () {
  4802. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4803. };
  4804. /**
  4805. * Fill a Vector3 with the extracted translation from the Matrix.
  4806. */
  4807. Matrix.prototype.getTranslationToRef = function (result) {
  4808. result.x = this.m[12];
  4809. result.y = this.m[13];
  4810. result.z = this.m[14];
  4811. return this;
  4812. };
  4813. /**
  4814. * Remove rotation and scaling part from the Matrix.
  4815. * Returns the updated Matrix.
  4816. */
  4817. Matrix.prototype.removeRotationAndScaling = function () {
  4818. this.setRowFromFloats(0, 1, 0, 0, 0);
  4819. this.setRowFromFloats(1, 0, 1, 0, 0);
  4820. this.setRowFromFloats(2, 0, 0, 1, 0);
  4821. return this;
  4822. };
  4823. /**
  4824. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4825. */
  4826. Matrix.prototype.multiply = function (other) {
  4827. var result = new Matrix();
  4828. this.multiplyToRef(other, result);
  4829. return result;
  4830. };
  4831. /**
  4832. * Updates the current Matrix from the passed one values.
  4833. * Returns the updated Matrix.
  4834. */
  4835. Matrix.prototype.copyFrom = function (other) {
  4836. for (var index = 0; index < 16; index++) {
  4837. this.m[index] = other.m[index];
  4838. }
  4839. this._markAsUpdated();
  4840. return this;
  4841. };
  4842. /**
  4843. * Populates the passed array from the starting index with the Matrix values.
  4844. * Returns the Matrix.
  4845. */
  4846. Matrix.prototype.copyToArray = function (array, offset) {
  4847. if (offset === void 0) { offset = 0; }
  4848. for (var index = 0; index < 16; index++) {
  4849. array[offset + index] = this.m[index];
  4850. }
  4851. return this;
  4852. };
  4853. /**
  4854. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4855. */
  4856. Matrix.prototype.multiplyToRef = function (other, result) {
  4857. this.multiplyToArray(other, result.m, 0);
  4858. result._markAsUpdated();
  4859. return this;
  4860. };
  4861. /**
  4862. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4863. */
  4864. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4865. var tm0 = this.m[0];
  4866. var tm1 = this.m[1];
  4867. var tm2 = this.m[2];
  4868. var tm3 = this.m[3];
  4869. var tm4 = this.m[4];
  4870. var tm5 = this.m[5];
  4871. var tm6 = this.m[6];
  4872. var tm7 = this.m[7];
  4873. var tm8 = this.m[8];
  4874. var tm9 = this.m[9];
  4875. var tm10 = this.m[10];
  4876. var tm11 = this.m[11];
  4877. var tm12 = this.m[12];
  4878. var tm13 = this.m[13];
  4879. var tm14 = this.m[14];
  4880. var tm15 = this.m[15];
  4881. var om0 = other.m[0];
  4882. var om1 = other.m[1];
  4883. var om2 = other.m[2];
  4884. var om3 = other.m[3];
  4885. var om4 = other.m[4];
  4886. var om5 = other.m[5];
  4887. var om6 = other.m[6];
  4888. var om7 = other.m[7];
  4889. var om8 = other.m[8];
  4890. var om9 = other.m[9];
  4891. var om10 = other.m[10];
  4892. var om11 = other.m[11];
  4893. var om12 = other.m[12];
  4894. var om13 = other.m[13];
  4895. var om14 = other.m[14];
  4896. var om15 = other.m[15];
  4897. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4898. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4899. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4900. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4901. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4902. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4903. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4904. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4905. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4906. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4907. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4908. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4909. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4910. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4911. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4912. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4913. return this;
  4914. };
  4915. /**
  4916. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4917. */
  4918. Matrix.prototype.equals = function (value) {
  4919. return value &&
  4920. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4921. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4922. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4923. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4924. };
  4925. /**
  4926. * Returns a new Matrix from the current Matrix.
  4927. */
  4928. Matrix.prototype.clone = function () {
  4929. 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]);
  4930. };
  4931. /**
  4932. * Returns the string "Matrix"
  4933. */
  4934. Matrix.prototype.getClassName = function () {
  4935. return "Matrix";
  4936. };
  4937. /**
  4938. * Returns the Matrix hash code.
  4939. */
  4940. Matrix.prototype.getHashCode = function () {
  4941. var hash = this.m[0] || 0;
  4942. for (var i = 1; i < 16; i++) {
  4943. hash = (hash * 397) ^ (this.m[i] || 0);
  4944. }
  4945. return hash;
  4946. };
  4947. /**
  4948. * Decomposes the current Matrix into :
  4949. * - a scale vector3 passed as a reference to update,
  4950. * - a rotation quaternion passed as a reference to update,
  4951. * - a translation vector3 passed as a reference to update.
  4952. * Returns the true if operation was successful.
  4953. */
  4954. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4955. translation.x = this.m[12];
  4956. translation.y = this.m[13];
  4957. translation.z = this.m[14];
  4958. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4959. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4960. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4961. if (this.determinant() <= 0) {
  4962. scale.y *= -1;
  4963. }
  4964. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4965. rotation.x = 0;
  4966. rotation.y = 0;
  4967. rotation.z = 0;
  4968. rotation.w = 1;
  4969. return false;
  4970. }
  4971. 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]);
  4972. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4973. return true;
  4974. };
  4975. /**
  4976. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4977. * @param ref matrix to store the result
  4978. */
  4979. Matrix.prototype.toNormalMatrix = function (ref) {
  4980. this.invertToRef(ref);
  4981. ref.transpose();
  4982. var m = ref.m;
  4983. 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);
  4984. };
  4985. /**
  4986. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4987. */
  4988. Matrix.prototype.getRotationMatrix = function () {
  4989. var result = Matrix.Identity();
  4990. this.getRotationMatrixToRef(result);
  4991. return result;
  4992. };
  4993. /**
  4994. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4995. * Returns the current Matrix.
  4996. */
  4997. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4998. var m = this.m;
  4999. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5000. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5001. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5002. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5003. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5004. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5005. 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);
  5006. return this;
  5007. };
  5008. // Statics
  5009. /**
  5010. * Returns a new Matrix set from the starting index of the passed array.
  5011. */
  5012. Matrix.FromArray = function (array, offset) {
  5013. var result = new Matrix();
  5014. if (!offset) {
  5015. offset = 0;
  5016. }
  5017. Matrix.FromArrayToRef(array, offset, result);
  5018. return result;
  5019. };
  5020. /**
  5021. * Sets the passed "result" matrix from the starting index of the passed array.
  5022. */
  5023. Matrix.FromArrayToRef = function (array, offset, result) {
  5024. for (var index = 0; index < 16; index++) {
  5025. result.m[index] = array[index + offset];
  5026. }
  5027. result._markAsUpdated();
  5028. };
  5029. /**
  5030. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5031. */
  5032. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5033. for (var index = 0; index < 16; index++) {
  5034. result.m[index] = array[index + offset] * scale;
  5035. }
  5036. result._markAsUpdated();
  5037. };
  5038. /**
  5039. * Sets the passed matrix "result" with the 16 passed floats.
  5040. */
  5041. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5042. result.m[0] = initialM11;
  5043. result.m[1] = initialM12;
  5044. result.m[2] = initialM13;
  5045. result.m[3] = initialM14;
  5046. result.m[4] = initialM21;
  5047. result.m[5] = initialM22;
  5048. result.m[6] = initialM23;
  5049. result.m[7] = initialM24;
  5050. result.m[8] = initialM31;
  5051. result.m[9] = initialM32;
  5052. result.m[10] = initialM33;
  5053. result.m[11] = initialM34;
  5054. result.m[12] = initialM41;
  5055. result.m[13] = initialM42;
  5056. result.m[14] = initialM43;
  5057. result.m[15] = initialM44;
  5058. result._markAsUpdated();
  5059. };
  5060. /**
  5061. * Returns the index-th row of the current matrix as a new Vector4.
  5062. */
  5063. Matrix.prototype.getRow = function (index) {
  5064. if (index < 0 || index > 3) {
  5065. return null;
  5066. }
  5067. var i = index * 4;
  5068. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5069. };
  5070. /**
  5071. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5072. * Returns the updated Matrix.
  5073. */
  5074. Matrix.prototype.setRow = function (index, row) {
  5075. if (index < 0 || index > 3) {
  5076. return this;
  5077. }
  5078. var i = index * 4;
  5079. this.m[i + 0] = row.x;
  5080. this.m[i + 1] = row.y;
  5081. this.m[i + 2] = row.z;
  5082. this.m[i + 3] = row.w;
  5083. this._markAsUpdated();
  5084. return this;
  5085. };
  5086. /**
  5087. * Compute the transpose of the matrix.
  5088. * Returns a new Matrix.
  5089. */
  5090. Matrix.prototype.transpose = function () {
  5091. return Matrix.Transpose(this);
  5092. };
  5093. /**
  5094. * Compute the transpose of the matrix.
  5095. * Returns the current matrix.
  5096. */
  5097. Matrix.prototype.transposeToRef = function (result) {
  5098. Matrix.TransposeToRef(this, result);
  5099. return this;
  5100. };
  5101. /**
  5102. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5103. * Returns the updated Matrix.
  5104. */
  5105. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5106. if (index < 0 || index > 3) {
  5107. return this;
  5108. }
  5109. var i = index * 4;
  5110. this.m[i + 0] = x;
  5111. this.m[i + 1] = y;
  5112. this.m[i + 2] = z;
  5113. this.m[i + 3] = w;
  5114. this._markAsUpdated();
  5115. return this;
  5116. };
  5117. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5118. /**
  5119. * Static identity matrix to be used as readonly matrix
  5120. * Must not be updated.
  5121. */
  5122. get: function () {
  5123. return Matrix._identityReadOnly;
  5124. },
  5125. enumerable: true,
  5126. configurable: true
  5127. });
  5128. /**
  5129. * Returns a new Matrix set from the 16 passed floats.
  5130. */
  5131. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5132. var result = new Matrix();
  5133. result.m[0] = initialM11;
  5134. result.m[1] = initialM12;
  5135. result.m[2] = initialM13;
  5136. result.m[3] = initialM14;
  5137. result.m[4] = initialM21;
  5138. result.m[5] = initialM22;
  5139. result.m[6] = initialM23;
  5140. result.m[7] = initialM24;
  5141. result.m[8] = initialM31;
  5142. result.m[9] = initialM32;
  5143. result.m[10] = initialM33;
  5144. result.m[11] = initialM34;
  5145. result.m[12] = initialM41;
  5146. result.m[13] = initialM42;
  5147. result.m[14] = initialM43;
  5148. result.m[15] = initialM44;
  5149. return result;
  5150. };
  5151. /**
  5152. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5153. */
  5154. Matrix.Compose = function (scale, rotation, translation) {
  5155. var result = Matrix.Identity();
  5156. Matrix.ComposeToRef(scale, rotation, translation, result);
  5157. return result;
  5158. };
  5159. /**
  5160. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5161. */
  5162. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5163. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5164. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5165. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5166. result.setTranslation(translation);
  5167. };
  5168. /**
  5169. * Returns a new indentity Matrix.
  5170. */
  5171. Matrix.Identity = function () {
  5172. 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);
  5173. };
  5174. /**
  5175. * Sets the passed "result" as an identity matrix.
  5176. */
  5177. Matrix.IdentityToRef = function (result) {
  5178. 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);
  5179. };
  5180. /**
  5181. * Returns a new zero Matrix.
  5182. */
  5183. Matrix.Zero = function () {
  5184. 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);
  5185. };
  5186. /**
  5187. * Returns a new rotation matrix for "angle" radians around the X axis.
  5188. */
  5189. Matrix.RotationX = function (angle) {
  5190. var result = new Matrix();
  5191. Matrix.RotationXToRef(angle, result);
  5192. return result;
  5193. };
  5194. /**
  5195. * Returns a new Matrix as the passed inverted one.
  5196. */
  5197. Matrix.Invert = function (source) {
  5198. var result = new Matrix();
  5199. source.invertToRef(result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5204. */
  5205. Matrix.RotationXToRef = function (angle, result) {
  5206. var s = Math.sin(angle);
  5207. var c = Math.cos(angle);
  5208. result.m[0] = 1.0;
  5209. result.m[15] = 1.0;
  5210. result.m[5] = c;
  5211. result.m[10] = c;
  5212. result.m[9] = -s;
  5213. result.m[6] = s;
  5214. result.m[1] = 0.0;
  5215. result.m[2] = 0.0;
  5216. result.m[3] = 0.0;
  5217. result.m[4] = 0.0;
  5218. result.m[7] = 0.0;
  5219. result.m[8] = 0.0;
  5220. result.m[11] = 0.0;
  5221. result.m[12] = 0.0;
  5222. result.m[13] = 0.0;
  5223. result.m[14] = 0.0;
  5224. result._markAsUpdated();
  5225. };
  5226. /**
  5227. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5228. */
  5229. Matrix.RotationY = function (angle) {
  5230. var result = new Matrix();
  5231. Matrix.RotationYToRef(angle, result);
  5232. return result;
  5233. };
  5234. /**
  5235. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5236. */
  5237. Matrix.RotationYToRef = function (angle, result) {
  5238. var s = Math.sin(angle);
  5239. var c = Math.cos(angle);
  5240. result.m[5] = 1.0;
  5241. result.m[15] = 1.0;
  5242. result.m[0] = c;
  5243. result.m[2] = -s;
  5244. result.m[8] = s;
  5245. result.m[10] = c;
  5246. result.m[1] = 0.0;
  5247. result.m[3] = 0.0;
  5248. result.m[4] = 0.0;
  5249. result.m[6] = 0.0;
  5250. result.m[7] = 0.0;
  5251. result.m[9] = 0.0;
  5252. result.m[11] = 0.0;
  5253. result.m[12] = 0.0;
  5254. result.m[13] = 0.0;
  5255. result.m[14] = 0.0;
  5256. result._markAsUpdated();
  5257. };
  5258. /**
  5259. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5260. */
  5261. Matrix.RotationZ = function (angle) {
  5262. var result = new Matrix();
  5263. Matrix.RotationZToRef(angle, result);
  5264. return result;
  5265. };
  5266. /**
  5267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5268. */
  5269. Matrix.RotationZToRef = function (angle, result) {
  5270. var s = Math.sin(angle);
  5271. var c = Math.cos(angle);
  5272. result.m[10] = 1.0;
  5273. result.m[15] = 1.0;
  5274. result.m[0] = c;
  5275. result.m[1] = s;
  5276. result.m[4] = -s;
  5277. result.m[5] = c;
  5278. result.m[2] = 0.0;
  5279. result.m[3] = 0.0;
  5280. result.m[6] = 0.0;
  5281. result.m[7] = 0.0;
  5282. result.m[8] = 0.0;
  5283. result.m[9] = 0.0;
  5284. result.m[11] = 0.0;
  5285. result.m[12] = 0.0;
  5286. result.m[13] = 0.0;
  5287. result.m[14] = 0.0;
  5288. result._markAsUpdated();
  5289. };
  5290. /**
  5291. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5292. */
  5293. Matrix.RotationAxis = function (axis, angle) {
  5294. var result = Matrix.Zero();
  5295. Matrix.RotationAxisToRef(axis, angle, result);
  5296. return result;
  5297. };
  5298. /**
  5299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5300. */
  5301. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5302. var s = Math.sin(-angle);
  5303. var c = Math.cos(-angle);
  5304. var c1 = 1 - c;
  5305. axis.normalize();
  5306. result.m[0] = (axis.x * axis.x) * c1 + c;
  5307. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5308. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5309. result.m[3] = 0.0;
  5310. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5311. result.m[5] = (axis.y * axis.y) * c1 + c;
  5312. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5313. result.m[7] = 0.0;
  5314. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5315. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5316. result.m[10] = (axis.z * axis.z) * c1 + c;
  5317. result.m[11] = 0.0;
  5318. result.m[15] = 1.0;
  5319. result._markAsUpdated();
  5320. };
  5321. /**
  5322. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5323. */
  5324. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5325. var result = new Matrix();
  5326. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5327. return result;
  5328. };
  5329. /**
  5330. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5331. */
  5332. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5333. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5334. this._tempQuaternion.toRotationMatrix(result);
  5335. };
  5336. /**
  5337. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5338. */
  5339. Matrix.Scaling = function (x, y, z) {
  5340. var result = Matrix.Zero();
  5341. Matrix.ScalingToRef(x, y, z, result);
  5342. return result;
  5343. };
  5344. /**
  5345. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5346. */
  5347. Matrix.ScalingToRef = function (x, y, z, result) {
  5348. result.m[0] = x;
  5349. result.m[1] = 0.0;
  5350. result.m[2] = 0.0;
  5351. result.m[3] = 0.0;
  5352. result.m[4] = 0.0;
  5353. result.m[5] = y;
  5354. result.m[6] = 0.0;
  5355. result.m[7] = 0.0;
  5356. result.m[8] = 0.0;
  5357. result.m[9] = 0.0;
  5358. result.m[10] = z;
  5359. result.m[11] = 0.0;
  5360. result.m[12] = 0.0;
  5361. result.m[13] = 0.0;
  5362. result.m[14] = 0.0;
  5363. result.m[15] = 1.0;
  5364. result._markAsUpdated();
  5365. };
  5366. /**
  5367. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5368. */
  5369. Matrix.Translation = function (x, y, z) {
  5370. var result = Matrix.Identity();
  5371. Matrix.TranslationToRef(x, y, z, result);
  5372. return result;
  5373. };
  5374. /**
  5375. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5376. */
  5377. Matrix.TranslationToRef = function (x, y, z, result) {
  5378. 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);
  5379. };
  5380. /**
  5381. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5382. */
  5383. Matrix.Lerp = function (startValue, endValue, gradient) {
  5384. var result = Matrix.Zero();
  5385. for (var index = 0; index < 16; index++) {
  5386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5387. }
  5388. result._markAsUpdated();
  5389. return result;
  5390. };
  5391. /**
  5392. * Returns a new Matrix whose values are computed by :
  5393. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5394. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5395. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5396. */
  5397. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5398. var startScale = new Vector3(0, 0, 0);
  5399. var startRotation = new Quaternion();
  5400. var startTranslation = new Vector3(0, 0, 0);
  5401. startValue.decompose(startScale, startRotation, startTranslation);
  5402. var endScale = new Vector3(0, 0, 0);
  5403. var endRotation = new Quaternion();
  5404. var endTranslation = new Vector3(0, 0, 0);
  5405. endValue.decompose(endScale, endRotation, endTranslation);
  5406. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5407. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5408. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5409. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5410. };
  5411. /**
  5412. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5413. * This methods works for a Left-Handed system.
  5414. */
  5415. Matrix.LookAtLH = function (eye, target, up) {
  5416. var result = Matrix.Zero();
  5417. Matrix.LookAtLHToRef(eye, target, up, result);
  5418. return result;
  5419. };
  5420. /**
  5421. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5422. * This methods works for a Left-Handed system.
  5423. */
  5424. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5425. // Z axis
  5426. target.subtractToRef(eye, this._zAxis);
  5427. this._zAxis.normalize();
  5428. // X axis
  5429. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5430. if (this._xAxis.lengthSquared() === 0) {
  5431. this._xAxis.x = 1.0;
  5432. }
  5433. else {
  5434. this._xAxis.normalize();
  5435. }
  5436. // Y axis
  5437. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5438. this._yAxis.normalize();
  5439. // Eye angles
  5440. var ex = -Vector3.Dot(this._xAxis, eye);
  5441. var ey = -Vector3.Dot(this._yAxis, eye);
  5442. var ez = -Vector3.Dot(this._zAxis, eye);
  5443. 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);
  5444. };
  5445. /**
  5446. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5447. * This methods works for a Right-Handed system.
  5448. */
  5449. Matrix.LookAtRH = function (eye, target, up) {
  5450. var result = Matrix.Zero();
  5451. Matrix.LookAtRHToRef(eye, target, up, result);
  5452. return result;
  5453. };
  5454. /**
  5455. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5456. * This methods works for a Left-Handed system.
  5457. */
  5458. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5459. // Z axis
  5460. eye.subtractToRef(target, this._zAxis);
  5461. this._zAxis.normalize();
  5462. // X axis
  5463. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5464. if (this._xAxis.lengthSquared() === 0) {
  5465. this._xAxis.x = 1.0;
  5466. }
  5467. else {
  5468. this._xAxis.normalize();
  5469. }
  5470. // Y axis
  5471. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5472. this._yAxis.normalize();
  5473. // Eye angles
  5474. var ex = -Vector3.Dot(this._xAxis, eye);
  5475. var ey = -Vector3.Dot(this._yAxis, eye);
  5476. var ez = -Vector3.Dot(this._zAxis, eye);
  5477. 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);
  5478. };
  5479. /**
  5480. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5481. */
  5482. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5483. var matrix = Matrix.Zero();
  5484. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5485. return matrix;
  5486. };
  5487. /**
  5488. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5489. */
  5490. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5491. var n = znear;
  5492. var f = zfar;
  5493. var a = 2.0 / width;
  5494. var b = 2.0 / height;
  5495. var c = 2.0 / (f - n);
  5496. var d = -(f + n) / (f - n);
  5497. 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);
  5498. };
  5499. /**
  5500. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5501. */
  5502. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5503. var matrix = Matrix.Zero();
  5504. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5505. return matrix;
  5506. };
  5507. /**
  5508. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5509. */
  5510. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5511. var n = znear;
  5512. var f = zfar;
  5513. var a = 2.0 / (right - left);
  5514. var b = 2.0 / (top - bottom);
  5515. var c = 2.0 / (f - n);
  5516. var d = -(f + n) / (f - n);
  5517. var i0 = (left + right) / (left - right);
  5518. var i1 = (top + bottom) / (bottom - top);
  5519. 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);
  5520. };
  5521. /**
  5522. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5523. */
  5524. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5525. var matrix = Matrix.Zero();
  5526. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5527. return matrix;
  5528. };
  5529. /**
  5530. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5531. */
  5532. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5533. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5534. result.m[10] *= -1.0;
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5538. */
  5539. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. var n = znear;
  5542. var f = zfar;
  5543. var a = 2.0 * n / width;
  5544. var b = 2.0 * n / height;
  5545. var c = (f + n) / (f - n);
  5546. var d = -2.0 * f * n / (f - n);
  5547. 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);
  5548. return matrix;
  5549. };
  5550. /**
  5551. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5552. */
  5553. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5556. return matrix;
  5557. };
  5558. /**
  5559. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5560. */
  5561. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5562. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5563. var n = znear;
  5564. var f = zfar;
  5565. var t = 1.0 / (Math.tan(fov * 0.5));
  5566. var a = isVerticalFovFixed ? (t / aspect) : t;
  5567. var b = isVerticalFovFixed ? t : (t * aspect);
  5568. var c = (f + n) / (f - n);
  5569. var d = -2.0 * f * n / (f - n);
  5570. 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);
  5571. };
  5572. /**
  5573. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5574. */
  5575. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5576. var matrix = Matrix.Zero();
  5577. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5578. return matrix;
  5579. };
  5580. /**
  5581. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5582. */
  5583. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5584. //alternatively this could be expressed as:
  5585. // m = PerspectiveFovLHToRef
  5586. // m[10] *= -1.0;
  5587. // m[11] *= -1.0;
  5588. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5589. var n = znear;
  5590. var f = zfar;
  5591. var t = 1.0 / (Math.tan(fov * 0.5));
  5592. var a = isVerticalFovFixed ? (t / aspect) : t;
  5593. var b = isVerticalFovFixed ? t : (t * aspect);
  5594. var c = -(f + n) / (f - n);
  5595. var d = -2 * f * n / (f - n);
  5596. 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);
  5597. };
  5598. /**
  5599. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5600. */
  5601. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5602. if (rightHanded === void 0) { rightHanded = false; }
  5603. var rightHandedFactor = rightHanded ? -1 : 1;
  5604. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5605. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5606. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5607. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5608. var xScale = 2.0 / (leftTan + rightTan);
  5609. var yScale = 2.0 / (upTan + downTan);
  5610. result.m[0] = xScale;
  5611. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5612. result.m[5] = yScale;
  5613. result.m[6] = result.m[7] = 0.0;
  5614. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5615. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5616. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5617. result.m[10] = -zfar / (znear - zfar);
  5618. result.m[11] = 1.0 * rightHandedFactor;
  5619. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5620. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5621. // result.m[14] = (znear * zfar) / (znear - zfar);
  5622. result._markAsUpdated();
  5623. };
  5624. /**
  5625. * Returns the final transformation matrix : world * view * projection * viewport
  5626. */
  5627. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5628. var cw = viewport.width;
  5629. var ch = viewport.height;
  5630. var cx = viewport.x;
  5631. var cy = viewport.y;
  5632. 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);
  5633. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5634. };
  5635. /**
  5636. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5637. */
  5638. Matrix.GetAsMatrix2x2 = function (matrix) {
  5639. return new Float32Array([
  5640. matrix.m[0], matrix.m[1],
  5641. matrix.m[4], matrix.m[5]
  5642. ]);
  5643. };
  5644. /**
  5645. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5646. */
  5647. Matrix.GetAsMatrix3x3 = function (matrix) {
  5648. return new Float32Array([
  5649. matrix.m[0], matrix.m[1], matrix.m[2],
  5650. matrix.m[4], matrix.m[5], matrix.m[6],
  5651. matrix.m[8], matrix.m[9], matrix.m[10]
  5652. ]);
  5653. };
  5654. /**
  5655. * Compute the transpose of the passed Matrix.
  5656. * Returns a new Matrix.
  5657. */
  5658. Matrix.Transpose = function (matrix) {
  5659. var result = new Matrix();
  5660. Matrix.TransposeToRef(matrix, result);
  5661. return result;
  5662. };
  5663. /**
  5664. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5665. */
  5666. Matrix.TransposeToRef = function (matrix, result) {
  5667. result.m[0] = matrix.m[0];
  5668. result.m[1] = matrix.m[4];
  5669. result.m[2] = matrix.m[8];
  5670. result.m[3] = matrix.m[12];
  5671. result.m[4] = matrix.m[1];
  5672. result.m[5] = matrix.m[5];
  5673. result.m[6] = matrix.m[9];
  5674. result.m[7] = matrix.m[13];
  5675. result.m[8] = matrix.m[2];
  5676. result.m[9] = matrix.m[6];
  5677. result.m[10] = matrix.m[10];
  5678. result.m[11] = matrix.m[14];
  5679. result.m[12] = matrix.m[3];
  5680. result.m[13] = matrix.m[7];
  5681. result.m[14] = matrix.m[11];
  5682. result.m[15] = matrix.m[15];
  5683. };
  5684. /**
  5685. * Returns a new Matrix as the reflection matrix across the passed plane.
  5686. */
  5687. Matrix.Reflection = function (plane) {
  5688. var matrix = new Matrix();
  5689. Matrix.ReflectionToRef(plane, matrix);
  5690. return matrix;
  5691. };
  5692. /**
  5693. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5694. */
  5695. Matrix.ReflectionToRef = function (plane, result) {
  5696. plane.normalize();
  5697. var x = plane.normal.x;
  5698. var y = plane.normal.y;
  5699. var z = plane.normal.z;
  5700. var temp = -2 * x;
  5701. var temp2 = -2 * y;
  5702. var temp3 = -2 * z;
  5703. result.m[0] = (temp * x) + 1;
  5704. result.m[1] = temp2 * x;
  5705. result.m[2] = temp3 * x;
  5706. result.m[3] = 0.0;
  5707. result.m[4] = temp * y;
  5708. result.m[5] = (temp2 * y) + 1;
  5709. result.m[6] = temp3 * y;
  5710. result.m[7] = 0.0;
  5711. result.m[8] = temp * z;
  5712. result.m[9] = temp2 * z;
  5713. result.m[10] = (temp3 * z) + 1;
  5714. result.m[11] = 0.0;
  5715. result.m[12] = temp * plane.d;
  5716. result.m[13] = temp2 * plane.d;
  5717. result.m[14] = temp3 * plane.d;
  5718. result.m[15] = 1.0;
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5723. */
  5724. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5725. result.m[0] = xaxis.x;
  5726. result.m[1] = xaxis.y;
  5727. result.m[2] = xaxis.z;
  5728. result.m[3] = 0.0;
  5729. result.m[4] = yaxis.x;
  5730. result.m[5] = yaxis.y;
  5731. result.m[6] = yaxis.z;
  5732. result.m[7] = 0.0;
  5733. result.m[8] = zaxis.x;
  5734. result.m[9] = zaxis.y;
  5735. result.m[10] = zaxis.z;
  5736. result.m[11] = 0.0;
  5737. result.m[12] = 0.0;
  5738. result.m[13] = 0.0;
  5739. result.m[14] = 0.0;
  5740. result.m[15] = 1.0;
  5741. result._markAsUpdated();
  5742. };
  5743. /**
  5744. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5745. */
  5746. Matrix.FromQuaternionToRef = function (quat, result) {
  5747. var xx = quat.x * quat.x;
  5748. var yy = quat.y * quat.y;
  5749. var zz = quat.z * quat.z;
  5750. var xy = quat.x * quat.y;
  5751. var zw = quat.z * quat.w;
  5752. var zx = quat.z * quat.x;
  5753. var yw = quat.y * quat.w;
  5754. var yz = quat.y * quat.z;
  5755. var xw = quat.x * quat.w;
  5756. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5757. result.m[1] = 2.0 * (xy + zw);
  5758. result.m[2] = 2.0 * (zx - yw);
  5759. result.m[3] = 0.0;
  5760. result.m[4] = 2.0 * (xy - zw);
  5761. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5762. result.m[6] = 2.0 * (yz + xw);
  5763. result.m[7] = 0.0;
  5764. result.m[8] = 2.0 * (zx + yw);
  5765. result.m[9] = 2.0 * (yz - xw);
  5766. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5767. result.m[11] = 0.0;
  5768. result.m[12] = 0.0;
  5769. result.m[13] = 0.0;
  5770. result.m[14] = 0.0;
  5771. result.m[15] = 1.0;
  5772. result._markAsUpdated();
  5773. };
  5774. Matrix._tempQuaternion = new Quaternion();
  5775. Matrix._xAxis = Vector3.Zero();
  5776. Matrix._yAxis = Vector3.Zero();
  5777. Matrix._zAxis = Vector3.Zero();
  5778. Matrix._updateFlagSeed = 0;
  5779. Matrix._identityReadOnly = Matrix.Identity();
  5780. return Matrix;
  5781. }());
  5782. BABYLON.Matrix = Matrix;
  5783. var Plane = /** @class */ (function () {
  5784. /**
  5785. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5786. */
  5787. function Plane(a, b, c, d) {
  5788. this.normal = new Vector3(a, b, c);
  5789. this.d = d;
  5790. }
  5791. /**
  5792. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5793. */
  5794. Plane.prototype.asArray = function () {
  5795. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5796. };
  5797. // Methods
  5798. /**
  5799. * Returns a new plane copied from the current Plane.
  5800. */
  5801. Plane.prototype.clone = function () {
  5802. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5803. };
  5804. /**
  5805. * Returns the string "Plane".
  5806. */
  5807. Plane.prototype.getClassName = function () {
  5808. return "Plane";
  5809. };
  5810. /**
  5811. * Returns the Plane hash code.
  5812. */
  5813. Plane.prototype.getHashCode = function () {
  5814. var hash = this.normal.getHashCode();
  5815. hash = (hash * 397) ^ (this.d || 0);
  5816. return hash;
  5817. };
  5818. /**
  5819. * Normalize the current Plane in place.
  5820. * Returns the updated Plane.
  5821. */
  5822. Plane.prototype.normalize = function () {
  5823. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5824. var magnitude = 0.0;
  5825. if (norm !== 0) {
  5826. magnitude = 1.0 / norm;
  5827. }
  5828. this.normal.x *= magnitude;
  5829. this.normal.y *= magnitude;
  5830. this.normal.z *= magnitude;
  5831. this.d *= magnitude;
  5832. return this;
  5833. };
  5834. /**
  5835. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5836. */
  5837. Plane.prototype.transform = function (transformation) {
  5838. var transposedMatrix = Matrix.Transpose(transformation);
  5839. var x = this.normal.x;
  5840. var y = this.normal.y;
  5841. var z = this.normal.z;
  5842. var d = this.d;
  5843. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5844. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5845. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5846. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5847. return new Plane(normalX, normalY, normalZ, finalD);
  5848. };
  5849. /**
  5850. * Returns the dot product (float) of the point coordinates and the plane normal.
  5851. */
  5852. Plane.prototype.dotCoordinate = function (point) {
  5853. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5854. };
  5855. /**
  5856. * Updates the current Plane from the plane defined by the three passed points.
  5857. * Returns the updated Plane.
  5858. */
  5859. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5860. var x1 = point2.x - point1.x;
  5861. var y1 = point2.y - point1.y;
  5862. var z1 = point2.z - point1.z;
  5863. var x2 = point3.x - point1.x;
  5864. var y2 = point3.y - point1.y;
  5865. var z2 = point3.z - point1.z;
  5866. var yz = (y1 * z2) - (z1 * y2);
  5867. var xz = (z1 * x2) - (x1 * z2);
  5868. var xy = (x1 * y2) - (y1 * x2);
  5869. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5870. var invPyth;
  5871. if (pyth !== 0) {
  5872. invPyth = 1.0 / pyth;
  5873. }
  5874. else {
  5875. invPyth = 0.0;
  5876. }
  5877. this.normal.x = yz * invPyth;
  5878. this.normal.y = xz * invPyth;
  5879. this.normal.z = xy * invPyth;
  5880. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5881. return this;
  5882. };
  5883. /**
  5884. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5885. */
  5886. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5887. var dot = Vector3.Dot(this.normal, direction);
  5888. return (dot <= epsilon);
  5889. };
  5890. /**
  5891. * Returns the signed distance (float) from the passed point to the Plane.
  5892. */
  5893. Plane.prototype.signedDistanceTo = function (point) {
  5894. return Vector3.Dot(point, this.normal) + this.d;
  5895. };
  5896. // Statics
  5897. /**
  5898. * Returns a new Plane from the passed array.
  5899. */
  5900. Plane.FromArray = function (array) {
  5901. return new Plane(array[0], array[1], array[2], array[3]);
  5902. };
  5903. /**
  5904. * Returns a new Plane defined by the three passed points.
  5905. */
  5906. Plane.FromPoints = function (point1, point2, point3) {
  5907. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5908. result.copyFromPoints(point1, point2, point3);
  5909. return result;
  5910. };
  5911. /**
  5912. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5913. * Note : the vector "normal" is updated because normalized.
  5914. */
  5915. Plane.FromPositionAndNormal = function (origin, normal) {
  5916. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5917. normal.normalize();
  5918. result.normal = normal;
  5919. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5920. return result;
  5921. };
  5922. /**
  5923. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5924. */
  5925. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5926. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5927. return Vector3.Dot(point, normal) + d;
  5928. };
  5929. return Plane;
  5930. }());
  5931. BABYLON.Plane = Plane;
  5932. var Viewport = /** @class */ (function () {
  5933. /**
  5934. * Creates a Viewport object located at (x, y) and sized (width, height).
  5935. */
  5936. function Viewport(x, y, width, height) {
  5937. this.x = x;
  5938. this.y = y;
  5939. this.width = width;
  5940. this.height = height;
  5941. }
  5942. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5943. if (renderWidthOrEngine.getRenderWidth) {
  5944. var engine = renderWidthOrEngine;
  5945. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5946. }
  5947. var renderWidth = renderWidthOrEngine;
  5948. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5949. };
  5950. /**
  5951. * Returns a new Viewport copied from the current one.
  5952. */
  5953. Viewport.prototype.clone = function () {
  5954. return new Viewport(this.x, this.y, this.width, this.height);
  5955. };
  5956. return Viewport;
  5957. }());
  5958. BABYLON.Viewport = Viewport;
  5959. var Frustum = /** @class */ (function () {
  5960. function Frustum() {
  5961. }
  5962. /**
  5963. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5964. */
  5965. Frustum.GetPlanes = function (transform) {
  5966. var frustumPlanes = [];
  5967. for (var index = 0; index < 6; index++) {
  5968. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5969. }
  5970. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5971. return frustumPlanes;
  5972. };
  5973. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5974. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5975. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5976. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5977. frustumPlane.d = transform.m[15] + transform.m[14];
  5978. frustumPlane.normalize();
  5979. };
  5980. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5981. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5982. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5983. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5984. frustumPlane.d = transform.m[15] - transform.m[14];
  5985. frustumPlane.normalize();
  5986. };
  5987. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5988. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5989. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5990. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5991. frustumPlane.d = transform.m[15] + transform.m[12];
  5992. frustumPlane.normalize();
  5993. };
  5994. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5995. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5996. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5997. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5998. frustumPlane.d = transform.m[15] - transform.m[12];
  5999. frustumPlane.normalize();
  6000. };
  6001. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6002. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6003. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6004. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6005. frustumPlane.d = transform.m[15] - transform.m[13];
  6006. frustumPlane.normalize();
  6007. };
  6008. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6009. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6010. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6011. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6012. frustumPlane.d = transform.m[15] + transform.m[13];
  6013. frustumPlane.normalize();
  6014. };
  6015. /**
  6016. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6017. */
  6018. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6019. // Near
  6020. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6021. // Far
  6022. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6023. // Left
  6024. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6025. // Right
  6026. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6027. // Top
  6028. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6029. // Bottom
  6030. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6031. };
  6032. return Frustum;
  6033. }());
  6034. BABYLON.Frustum = Frustum;
  6035. var Space;
  6036. (function (Space) {
  6037. Space[Space["LOCAL"] = 0] = "LOCAL";
  6038. Space[Space["WORLD"] = 1] = "WORLD";
  6039. Space[Space["BONE"] = 2] = "BONE";
  6040. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6041. var Axis = /** @class */ (function () {
  6042. function Axis() {
  6043. }
  6044. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6045. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6046. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6047. return Axis;
  6048. }());
  6049. BABYLON.Axis = Axis;
  6050. ;
  6051. var BezierCurve = /** @class */ (function () {
  6052. function BezierCurve() {
  6053. }
  6054. /**
  6055. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6056. */
  6057. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6058. // Extract X (which is equal to time here)
  6059. var f0 = 1 - 3 * x2 + 3 * x1;
  6060. var f1 = 3 * x2 - 6 * x1;
  6061. var f2 = 3 * x1;
  6062. var refinedT = t;
  6063. for (var i = 0; i < 5; i++) {
  6064. var refinedT2 = refinedT * refinedT;
  6065. var refinedT3 = refinedT2 * refinedT;
  6066. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6067. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6068. refinedT -= (x - t) * slope;
  6069. refinedT = Math.min(1, Math.max(0, refinedT));
  6070. }
  6071. // Resolve cubic bezier for the given x
  6072. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6073. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6074. Math.pow(refinedT, 3);
  6075. };
  6076. return BezierCurve;
  6077. }());
  6078. BABYLON.BezierCurve = BezierCurve;
  6079. var Orientation;
  6080. (function (Orientation) {
  6081. Orientation[Orientation["CW"] = 0] = "CW";
  6082. Orientation[Orientation["CCW"] = 1] = "CCW";
  6083. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6084. var Angle = /** @class */ (function () {
  6085. /**
  6086. * Creates an Angle object of "radians" radians (float).
  6087. */
  6088. function Angle(radians) {
  6089. var _this = this;
  6090. /**
  6091. * Returns the Angle value in degrees (float).
  6092. */
  6093. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6094. /**
  6095. * Returns the Angle value in radians (float).
  6096. */
  6097. this.radians = function () { return _this._radians; };
  6098. this._radians = radians;
  6099. if (this._radians < 0.0)
  6100. this._radians += (2.0 * Math.PI);
  6101. }
  6102. /**
  6103. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6104. */
  6105. Angle.BetweenTwoPoints = function (a, b) {
  6106. var delta = b.subtract(a);
  6107. var theta = Math.atan2(delta.y, delta.x);
  6108. return new Angle(theta);
  6109. };
  6110. /**
  6111. * Returns a new Angle object from the passed float in radians.
  6112. */
  6113. Angle.FromRadians = function (radians) {
  6114. return new Angle(radians);
  6115. };
  6116. /**
  6117. * Returns a new Angle object from the passed float in degrees.
  6118. */
  6119. Angle.FromDegrees = function (degrees) {
  6120. return new Angle(degrees * Math.PI / 180.0);
  6121. };
  6122. return Angle;
  6123. }());
  6124. BABYLON.Angle = Angle;
  6125. var Arc2 = /** @class */ (function () {
  6126. /**
  6127. * Creates an Arc object from the three passed points : start, middle and end.
  6128. */
  6129. function Arc2(startPoint, midPoint, endPoint) {
  6130. this.startPoint = startPoint;
  6131. this.midPoint = midPoint;
  6132. this.endPoint = endPoint;
  6133. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6134. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6135. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6136. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6137. 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);
  6138. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6139. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6140. var a1 = this.startAngle.degrees();
  6141. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6142. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6143. // angles correction
  6144. if (a2 - a1 > +180.0)
  6145. a2 -= 360.0;
  6146. if (a2 - a1 < -180.0)
  6147. a2 += 360.0;
  6148. if (a3 - a2 > +180.0)
  6149. a3 -= 360.0;
  6150. if (a3 - a2 < -180.0)
  6151. a3 += 360.0;
  6152. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6153. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6154. }
  6155. return Arc2;
  6156. }());
  6157. BABYLON.Arc2 = Arc2;
  6158. var Path2 = /** @class */ (function () {
  6159. /**
  6160. * Creates a Path2 object from the starting 2D coordinates x and y.
  6161. */
  6162. function Path2(x, y) {
  6163. this._points = new Array();
  6164. this._length = 0.0;
  6165. this.closed = false;
  6166. this._points.push(new Vector2(x, y));
  6167. }
  6168. /**
  6169. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6170. * Returns the updated Path2.
  6171. */
  6172. Path2.prototype.addLineTo = function (x, y) {
  6173. if (this.closed) {
  6174. return this;
  6175. }
  6176. var newPoint = new Vector2(x, y);
  6177. var previousPoint = this._points[this._points.length - 1];
  6178. this._points.push(newPoint);
  6179. this._length += newPoint.subtract(previousPoint).length();
  6180. return this;
  6181. };
  6182. /**
  6183. * 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.
  6184. * Returns the updated Path2.
  6185. */
  6186. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6187. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6188. if (this.closed) {
  6189. return this;
  6190. }
  6191. var startPoint = this._points[this._points.length - 1];
  6192. var midPoint = new Vector2(midX, midY);
  6193. var endPoint = new Vector2(endX, endY);
  6194. var arc = new Arc2(startPoint, midPoint, endPoint);
  6195. var increment = arc.angle.radians() / numberOfSegments;
  6196. if (arc.orientation === Orientation.CW)
  6197. increment *= -1;
  6198. var currentAngle = arc.startAngle.radians() + increment;
  6199. for (var i = 0; i < numberOfSegments; i++) {
  6200. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6201. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6202. this.addLineTo(x, y);
  6203. currentAngle += increment;
  6204. }
  6205. return this;
  6206. };
  6207. /**
  6208. * Closes the Path2.
  6209. * Returns the Path2.
  6210. */
  6211. Path2.prototype.close = function () {
  6212. this.closed = true;
  6213. return this;
  6214. };
  6215. /**
  6216. * Returns the Path2 total length (float).
  6217. */
  6218. Path2.prototype.length = function () {
  6219. var result = this._length;
  6220. if (!this.closed) {
  6221. var lastPoint = this._points[this._points.length - 1];
  6222. var firstPoint = this._points[0];
  6223. result += (firstPoint.subtract(lastPoint).length());
  6224. }
  6225. return result;
  6226. };
  6227. /**
  6228. * Returns the Path2 internal array of points.
  6229. */
  6230. Path2.prototype.getPoints = function () {
  6231. return this._points;
  6232. };
  6233. /**
  6234. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6235. */
  6236. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6237. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6238. return Vector2.Zero();
  6239. }
  6240. var lengthPosition = normalizedLengthPosition * this.length();
  6241. var previousOffset = 0;
  6242. for (var i = 0; i < this._points.length; i++) {
  6243. var j = (i + 1) % this._points.length;
  6244. var a = this._points[i];
  6245. var b = this._points[j];
  6246. var bToA = b.subtract(a);
  6247. var nextOffset = (bToA.length() + previousOffset);
  6248. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6249. var dir = bToA.normalize();
  6250. var localOffset = lengthPosition - previousOffset;
  6251. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6252. }
  6253. previousOffset = nextOffset;
  6254. }
  6255. return Vector2.Zero();
  6256. };
  6257. /**
  6258. * Returns a new Path2 starting at the coordinates (x, y).
  6259. */
  6260. Path2.StartingAt = function (x, y) {
  6261. return new Path2(x, y);
  6262. };
  6263. return Path2;
  6264. }());
  6265. BABYLON.Path2 = Path2;
  6266. var Path3D = /** @class */ (function () {
  6267. /**
  6268. * new Path3D(path, normal, raw)
  6269. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6270. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6271. * path : an array of Vector3, the curve axis of the Path3D
  6272. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6273. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6274. */
  6275. function Path3D(path, firstNormal, raw) {
  6276. if (firstNormal === void 0) { firstNormal = null; }
  6277. this.path = path;
  6278. this._curve = new Array();
  6279. this._distances = new Array();
  6280. this._tangents = new Array();
  6281. this._normals = new Array();
  6282. this._binormals = new Array();
  6283. for (var p = 0; p < path.length; p++) {
  6284. this._curve[p] = path[p].clone(); // hard copy
  6285. }
  6286. this._raw = raw || false;
  6287. this._compute(firstNormal);
  6288. }
  6289. /**
  6290. * Returns the Path3D array of successive Vector3 designing its curve.
  6291. */
  6292. Path3D.prototype.getCurve = function () {
  6293. return this._curve;
  6294. };
  6295. /**
  6296. * Returns an array populated with tangent vectors on each Path3D curve point.
  6297. */
  6298. Path3D.prototype.getTangents = function () {
  6299. return this._tangents;
  6300. };
  6301. /**
  6302. * Returns an array populated with normal vectors on each Path3D curve point.
  6303. */
  6304. Path3D.prototype.getNormals = function () {
  6305. return this._normals;
  6306. };
  6307. /**
  6308. * Returns an array populated with binormal vectors on each Path3D curve point.
  6309. */
  6310. Path3D.prototype.getBinormals = function () {
  6311. return this._binormals;
  6312. };
  6313. /**
  6314. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6315. */
  6316. Path3D.prototype.getDistances = function () {
  6317. return this._distances;
  6318. };
  6319. /**
  6320. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6321. * Returns the same object updated.
  6322. */
  6323. Path3D.prototype.update = function (path, firstNormal) {
  6324. if (firstNormal === void 0) { firstNormal = null; }
  6325. for (var p = 0; p < path.length; p++) {
  6326. this._curve[p].x = path[p].x;
  6327. this._curve[p].y = path[p].y;
  6328. this._curve[p].z = path[p].z;
  6329. }
  6330. this._compute(firstNormal);
  6331. return this;
  6332. };
  6333. // private function compute() : computes tangents, normals and binormals
  6334. Path3D.prototype._compute = function (firstNormal) {
  6335. var l = this._curve.length;
  6336. // first and last tangents
  6337. this._tangents[0] = this._getFirstNonNullVector(0);
  6338. if (!this._raw) {
  6339. this._tangents[0].normalize();
  6340. }
  6341. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6342. if (!this._raw) {
  6343. this._tangents[l - 1].normalize();
  6344. }
  6345. // normals and binormals at first point : arbitrary vector with _normalVector()
  6346. var tg0 = this._tangents[0];
  6347. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6348. this._normals[0] = pp0;
  6349. if (!this._raw) {
  6350. this._normals[0].normalize();
  6351. }
  6352. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6353. if (!this._raw) {
  6354. this._binormals[0].normalize();
  6355. }
  6356. this._distances[0] = 0.0;
  6357. // normals and binormals : next points
  6358. var prev; // previous vector (segment)
  6359. var cur; // current vector (segment)
  6360. var curTang; // current tangent
  6361. // previous normal
  6362. var prevBinor; // previous binormal
  6363. for (var i = 1; i < l; i++) {
  6364. // tangents
  6365. prev = this._getLastNonNullVector(i);
  6366. if (i < l - 1) {
  6367. cur = this._getFirstNonNullVector(i);
  6368. this._tangents[i] = prev.add(cur);
  6369. this._tangents[i].normalize();
  6370. }
  6371. this._distances[i] = this._distances[i - 1] + prev.length();
  6372. // normals and binormals
  6373. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6374. curTang = this._tangents[i];
  6375. prevBinor = this._binormals[i - 1];
  6376. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6377. if (!this._raw) {
  6378. this._normals[i].normalize();
  6379. }
  6380. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6381. if (!this._raw) {
  6382. this._binormals[i].normalize();
  6383. }
  6384. }
  6385. };
  6386. // private function getFirstNonNullVector(index)
  6387. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6388. Path3D.prototype._getFirstNonNullVector = function (index) {
  6389. var i = 1;
  6390. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6391. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6392. i++;
  6393. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6394. }
  6395. return nNVector;
  6396. };
  6397. // private function getLastNonNullVector(index)
  6398. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6399. Path3D.prototype._getLastNonNullVector = function (index) {
  6400. var i = 1;
  6401. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6402. while (nLVector.length() === 0 && index > i + 1) {
  6403. i++;
  6404. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6405. }
  6406. return nLVector;
  6407. };
  6408. // private function normalVector(v0, vt, va) :
  6409. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6410. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6411. Path3D.prototype._normalVector = function (v0, vt, va) {
  6412. var normal0;
  6413. var tgl = vt.length();
  6414. if (tgl === 0.0) {
  6415. tgl = 1.0;
  6416. }
  6417. if (va === undefined || va === null) {
  6418. var point;
  6419. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6420. point = new Vector3(0.0, -1.0, 0.0);
  6421. }
  6422. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6423. point = new Vector3(1.0, 0.0, 0.0);
  6424. }
  6425. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6426. point = new Vector3(0.0, 0.0, 1.0);
  6427. }
  6428. else {
  6429. point = Vector3.Zero();
  6430. }
  6431. normal0 = Vector3.Cross(vt, point);
  6432. }
  6433. else {
  6434. normal0 = Vector3.Cross(vt, va);
  6435. Vector3.CrossToRef(normal0, vt, normal0);
  6436. }
  6437. normal0.normalize();
  6438. return normal0;
  6439. };
  6440. return Path3D;
  6441. }());
  6442. BABYLON.Path3D = Path3D;
  6443. var Curve3 = /** @class */ (function () {
  6444. /**
  6445. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6446. * A Curve3 is designed from a series of successive Vector3.
  6447. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6448. */
  6449. function Curve3(points) {
  6450. this._length = 0.0;
  6451. this._points = points;
  6452. this._length = this._computeLength(points);
  6453. }
  6454. /**
  6455. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6456. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6457. * @param v1 (Vector3) the control point
  6458. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6459. * @param nbPoints (integer) the wanted number of points in the curve
  6460. */
  6461. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6462. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6463. var bez = new Array();
  6464. var equation = function (t, val0, val1, val2) {
  6465. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6466. return res;
  6467. };
  6468. for (var i = 0; i <= nbPoints; i++) {
  6469. 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)));
  6470. }
  6471. return new Curve3(bez);
  6472. };
  6473. /**
  6474. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6475. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6476. * @param v1 (Vector3) the first control point
  6477. * @param v2 (Vector3) the second control point
  6478. * @param v3 (Vector3) the end point of the Cubic Bezier
  6479. * @param nbPoints (integer) the wanted number of points in the curve
  6480. */
  6481. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6482. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6483. var bez = new Array();
  6484. var equation = function (t, val0, val1, val2, val3) {
  6485. 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;
  6486. return res;
  6487. };
  6488. for (var i = 0; i <= nbPoints; i++) {
  6489. 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)));
  6490. }
  6491. return new Curve3(bez);
  6492. };
  6493. /**
  6494. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6495. * @param p1 (Vector3) the origin point of the Hermite Spline
  6496. * @param t1 (Vector3) the tangent vector at the origin point
  6497. * @param p2 (Vector3) the end point of the Hermite Spline
  6498. * @param t2 (Vector3) the tangent vector at the end point
  6499. * @param nbPoints (integer) the wanted number of points in the curve
  6500. */
  6501. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6502. var hermite = new Array();
  6503. var step = 1.0 / nbPoints;
  6504. for (var i = 0; i <= nbPoints; i++) {
  6505. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6506. }
  6507. return new Curve3(hermite);
  6508. };
  6509. /**
  6510. * Returns a Curve3 object along a CatmullRom Spline curve :
  6511. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6512. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6513. */
  6514. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6515. var totalPoints = new Array();
  6516. totalPoints.push(points[0].clone());
  6517. Array.prototype.push.apply(totalPoints, points);
  6518. totalPoints.push(points[points.length - 1].clone());
  6519. var catmullRom = new Array();
  6520. var step = 1.0 / nbPoints;
  6521. var amount = 0.0;
  6522. for (var i = 0; i < totalPoints.length - 3; i++) {
  6523. amount = 0;
  6524. for (var c = 0; c < nbPoints; c++) {
  6525. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6526. amount += step;
  6527. }
  6528. }
  6529. i--;
  6530. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6531. return new Curve3(catmullRom);
  6532. };
  6533. /**
  6534. * Returns the Curve3 stored array of successive Vector3
  6535. */
  6536. Curve3.prototype.getPoints = function () {
  6537. return this._points;
  6538. };
  6539. /**
  6540. * Returns the computed length (float) of the curve.
  6541. */
  6542. Curve3.prototype.length = function () {
  6543. return this._length;
  6544. };
  6545. /**
  6546. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6547. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6548. * curveA and curveB keep unchanged.
  6549. */
  6550. Curve3.prototype.continue = function (curve) {
  6551. var lastPoint = this._points[this._points.length - 1];
  6552. var continuedPoints = this._points.slice();
  6553. var curvePoints = curve.getPoints();
  6554. for (var i = 1; i < curvePoints.length; i++) {
  6555. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6556. }
  6557. var continuedCurve = new Curve3(continuedPoints);
  6558. return continuedCurve;
  6559. };
  6560. Curve3.prototype._computeLength = function (path) {
  6561. var l = 0;
  6562. for (var i = 1; i < path.length; i++) {
  6563. l += (path[i].subtract(path[i - 1])).length();
  6564. }
  6565. return l;
  6566. };
  6567. return Curve3;
  6568. }());
  6569. BABYLON.Curve3 = Curve3;
  6570. // Vertex formats
  6571. var PositionNormalVertex = /** @class */ (function () {
  6572. function PositionNormalVertex(position, normal) {
  6573. if (position === void 0) { position = Vector3.Zero(); }
  6574. if (normal === void 0) { normal = Vector3.Up(); }
  6575. this.position = position;
  6576. this.normal = normal;
  6577. }
  6578. PositionNormalVertex.prototype.clone = function () {
  6579. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6580. };
  6581. return PositionNormalVertex;
  6582. }());
  6583. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6584. var PositionNormalTextureVertex = /** @class */ (function () {
  6585. function PositionNormalTextureVertex(position, normal, uv) {
  6586. if (position === void 0) { position = Vector3.Zero(); }
  6587. if (normal === void 0) { normal = Vector3.Up(); }
  6588. if (uv === void 0) { uv = Vector2.Zero(); }
  6589. this.position = position;
  6590. this.normal = normal;
  6591. this.uv = uv;
  6592. }
  6593. PositionNormalTextureVertex.prototype.clone = function () {
  6594. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6595. };
  6596. return PositionNormalTextureVertex;
  6597. }());
  6598. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6599. // Temporary pre-allocated objects for engine internal use
  6600. // usage in any internal function :
  6601. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6602. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6603. var Tmp = /** @class */ (function () {
  6604. function Tmp() {
  6605. }
  6606. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6607. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6608. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6609. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6610. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6611. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6612. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6613. Matrix.Zero(), Matrix.Zero(),
  6614. Matrix.Zero(), Matrix.Zero(),
  6615. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6616. return Tmp;
  6617. }());
  6618. BABYLON.Tmp = Tmp;
  6619. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6620. var MathTmp = /** @class */ (function () {
  6621. function MathTmp() {
  6622. }
  6623. MathTmp.Vector3 = [Vector3.Zero()];
  6624. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6625. MathTmp.Quaternion = [Quaternion.Zero()];
  6626. return MathTmp;
  6627. }());
  6628. })(BABYLON || (BABYLON = {}));
  6629. //# sourceMappingURL=babylon.math.js.map
  6630. var BABYLON;
  6631. (function (BABYLON) {
  6632. var Scalar = /** @class */ (function () {
  6633. function Scalar() {
  6634. }
  6635. /**
  6636. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6637. */
  6638. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6639. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6640. var num = a - b;
  6641. return -epsilon <= num && num <= epsilon;
  6642. };
  6643. /**
  6644. * Returns a string : the upper case translation of the number i to hexadecimal.
  6645. */
  6646. Scalar.ToHex = function (i) {
  6647. var str = i.toString(16);
  6648. if (i <= 15) {
  6649. return ("0" + str).toUpperCase();
  6650. }
  6651. return str.toUpperCase();
  6652. };
  6653. /**
  6654. * Returns -1 if value is negative and +1 is value is positive.
  6655. * Returns the value itself if it's equal to zero.
  6656. */
  6657. Scalar.Sign = function (value) {
  6658. value = +value; // convert to a number
  6659. if (value === 0 || isNaN(value))
  6660. return value;
  6661. return value > 0 ? 1 : -1;
  6662. };
  6663. /**
  6664. * Returns the value itself if it's between min and max.
  6665. * Returns min if the value is lower than min.
  6666. * Returns max if the value is greater than max.
  6667. */
  6668. Scalar.Clamp = function (value, min, max) {
  6669. if (min === void 0) { min = 0; }
  6670. if (max === void 0) { max = 1; }
  6671. return Math.min(max, Math.max(min, value));
  6672. };
  6673. /**
  6674. * Returns the log2 of value.
  6675. */
  6676. Scalar.Log2 = function (value) {
  6677. return Math.log(value) * Math.LOG2E;
  6678. };
  6679. /**
  6680. * Loops the value, so that it is never larger than length and never smaller than 0.
  6681. *
  6682. * This is similar to the modulo operator but it works with floating point numbers.
  6683. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6684. * With t = 5 and length = 2.5, the result would be 0.0.
  6685. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6686. */
  6687. Scalar.Repeat = function (value, length) {
  6688. return value - Math.floor(value / length) * length;
  6689. };
  6690. /**
  6691. * Normalize the value between 0.0 and 1.0 using min and max values
  6692. */
  6693. Scalar.Normalize = function (value, min, max) {
  6694. return (value - min) / (max - min);
  6695. };
  6696. /**
  6697. * Denormalize the value from 0.0 and 1.0 using min and max values
  6698. */
  6699. Scalar.Denormalize = function (normalized, min, max) {
  6700. return (normalized * (max - min) + min);
  6701. };
  6702. /**
  6703. * Calculates the shortest difference between two given angles given in degrees.
  6704. */
  6705. Scalar.DeltaAngle = function (current, target) {
  6706. var num = Scalar.Repeat(target - current, 360.0);
  6707. if (num > 180.0) {
  6708. num -= 360.0;
  6709. }
  6710. return num;
  6711. };
  6712. /**
  6713. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6714. *
  6715. * The returned value will move back and forth between 0 and length
  6716. */
  6717. Scalar.PingPong = function (tx, length) {
  6718. var t = Scalar.Repeat(tx, length * 2.0);
  6719. return length - Math.abs(t - length);
  6720. };
  6721. /**
  6722. * Interpolates between min and max with smoothing at the limits.
  6723. *
  6724. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6725. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6726. */
  6727. Scalar.SmoothStep = function (from, to, tx) {
  6728. var t = Scalar.Clamp(tx);
  6729. t = -2.0 * t * t * t + 3.0 * t * t;
  6730. return to * t + from * (1.0 - t);
  6731. };
  6732. /**
  6733. * Moves a value current towards target.
  6734. *
  6735. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6736. * Negative values of maxDelta pushes the value away from target.
  6737. */
  6738. Scalar.MoveTowards = function (current, target, maxDelta) {
  6739. var result = 0;
  6740. if (Math.abs(target - current) <= maxDelta) {
  6741. result = target;
  6742. }
  6743. else {
  6744. result = current + Scalar.Sign(target - current) * maxDelta;
  6745. }
  6746. return result;
  6747. };
  6748. /**
  6749. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6750. *
  6751. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6752. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6753. */
  6754. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6755. var num = Scalar.DeltaAngle(current, target);
  6756. var result = 0;
  6757. if (-maxDelta < num && num < maxDelta) {
  6758. result = target;
  6759. }
  6760. else {
  6761. target = current + num;
  6762. result = Scalar.MoveTowards(current, target, maxDelta);
  6763. }
  6764. return result;
  6765. };
  6766. /**
  6767. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6768. */
  6769. Scalar.Lerp = function (start, end, amount) {
  6770. return start + ((end - start) * amount);
  6771. };
  6772. /**
  6773. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6774. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6775. */
  6776. Scalar.LerpAngle = function (start, end, amount) {
  6777. var num = Scalar.Repeat(end - start, 360.0);
  6778. if (num > 180.0) {
  6779. num -= 360.0;
  6780. }
  6781. return start + num * Scalar.Clamp(amount);
  6782. };
  6783. /**
  6784. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6785. */
  6786. Scalar.InverseLerp = function (a, b, value) {
  6787. var result = 0;
  6788. if (a != b) {
  6789. result = Scalar.Clamp((value - a) / (b - a));
  6790. }
  6791. else {
  6792. result = 0.0;
  6793. }
  6794. return result;
  6795. };
  6796. /**
  6797. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6798. */
  6799. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6800. var squared = amount * amount;
  6801. var cubed = amount * squared;
  6802. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6803. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6804. var part3 = (cubed - (2.0 * squared)) + amount;
  6805. var part4 = cubed - squared;
  6806. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6807. };
  6808. /**
  6809. * Returns a random float number between and min and max values
  6810. */
  6811. Scalar.RandomRange = function (min, max) {
  6812. if (min === max)
  6813. return min;
  6814. return ((Math.random() * (max - min)) + min);
  6815. };
  6816. /**
  6817. * This function returns percentage of a number in a given range.
  6818. *
  6819. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6820. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6821. */
  6822. Scalar.RangeToPercent = function (number, min, max) {
  6823. return ((number - min) / (max - min));
  6824. };
  6825. /**
  6826. * This function returns number that corresponds to the percentage in a given range.
  6827. *
  6828. * PercentToRange(0.34,0,100) will return 34.
  6829. */
  6830. Scalar.PercentToRange = function (percent, min, max) {
  6831. return ((max - min) * percent + min);
  6832. };
  6833. /**
  6834. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6835. * @param angle The angle to normalize in radian.
  6836. * @return The converted angle.
  6837. */
  6838. Scalar.NormalizeRadians = function (angle) {
  6839. // More precise but slower version kept for reference.
  6840. // angle = angle % Tools.TwoPi;
  6841. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6842. //if (angle > Math.PI) {
  6843. // angle -= Tools.TwoPi;
  6844. //}
  6845. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6846. return angle;
  6847. };
  6848. /**
  6849. * Two pi constants convenient for computation.
  6850. */
  6851. Scalar.TwoPi = Math.PI * 2;
  6852. return Scalar;
  6853. }());
  6854. BABYLON.Scalar = Scalar;
  6855. })(BABYLON || (BABYLON = {}));
  6856. //# sourceMappingURL=babylon.math.scalar.js.map
  6857. //# sourceMappingURL=babylon.mixins.js.map
  6858. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6859. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6860. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6861. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6862. //# sourceMappingURL=babylon.webgl2.js.map
  6863. var BABYLON;
  6864. (function (BABYLON) {
  6865. var __decoratorInitialStore = {};
  6866. var __mergedStore = {};
  6867. var _copySource = function (creationFunction, source, instanciate) {
  6868. var destination = creationFunction();
  6869. // Tags
  6870. if (BABYLON.Tags) {
  6871. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6872. }
  6873. var classStore = getMergedStore(destination);
  6874. // Properties
  6875. for (var property in classStore) {
  6876. var propertyDescriptor = classStore[property];
  6877. var sourceProperty = source[property];
  6878. var propertyType = propertyDescriptor.type;
  6879. if (sourceProperty !== undefined && sourceProperty !== null) {
  6880. switch (propertyType) {
  6881. case 0: // Value
  6882. case 6:// Mesh reference
  6883. destination[property] = sourceProperty;
  6884. break;
  6885. case 1:// Texture
  6886. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6887. break;
  6888. case 2: // Color3
  6889. case 3: // FresnelParameters
  6890. case 4: // Vector2
  6891. case 5: // Vector3
  6892. case 7: // Color Curves
  6893. case 10:// Quaternion
  6894. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6895. break;
  6896. }
  6897. }
  6898. }
  6899. return destination;
  6900. };
  6901. function getDirectStore(target) {
  6902. var classKey = target.getClassName();
  6903. if (!__decoratorInitialStore[classKey]) {
  6904. __decoratorInitialStore[classKey] = {};
  6905. }
  6906. return __decoratorInitialStore[classKey];
  6907. }
  6908. /**
  6909. * Return the list of properties flagged as serializable
  6910. * @param target: host object
  6911. */
  6912. function getMergedStore(target) {
  6913. var classKey = target.getClassName();
  6914. if (__mergedStore[classKey]) {
  6915. return __mergedStore[classKey];
  6916. }
  6917. __mergedStore[classKey] = {};
  6918. var store = __mergedStore[classKey];
  6919. var currentTarget = target;
  6920. var currentKey = classKey;
  6921. while (currentKey) {
  6922. var initialStore = __decoratorInitialStore[currentKey];
  6923. for (var property in initialStore) {
  6924. store[property] = initialStore[property];
  6925. }
  6926. var parent_1 = void 0;
  6927. var done = false;
  6928. do {
  6929. parent_1 = Object.getPrototypeOf(currentTarget);
  6930. if (!parent_1.getClassName) {
  6931. done = true;
  6932. break;
  6933. }
  6934. if (parent_1.getClassName() !== currentKey) {
  6935. break;
  6936. }
  6937. currentTarget = parent_1;
  6938. } while (parent_1);
  6939. if (done) {
  6940. break;
  6941. }
  6942. currentKey = parent_1.getClassName();
  6943. currentTarget = parent_1;
  6944. }
  6945. return store;
  6946. }
  6947. function generateSerializableMember(type, sourceName) {
  6948. return function (target, propertyKey) {
  6949. var classStore = getDirectStore(target);
  6950. if (!classStore[propertyKey]) {
  6951. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6952. }
  6953. };
  6954. }
  6955. function generateExpandMember(setCallback, targetKey) {
  6956. if (targetKey === void 0) { targetKey = null; }
  6957. return function (target, propertyKey) {
  6958. var key = targetKey || ("_" + propertyKey);
  6959. Object.defineProperty(target, propertyKey, {
  6960. get: function () {
  6961. return this[key];
  6962. },
  6963. set: function (value) {
  6964. if (this[key] === value) {
  6965. return;
  6966. }
  6967. this[key] = value;
  6968. target[setCallback].apply(this);
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. };
  6974. }
  6975. function expandToProperty(callback, targetKey) {
  6976. if (targetKey === void 0) { targetKey = null; }
  6977. return generateExpandMember(callback, targetKey);
  6978. }
  6979. BABYLON.expandToProperty = expandToProperty;
  6980. function serialize(sourceName) {
  6981. return generateSerializableMember(0, sourceName); // value member
  6982. }
  6983. BABYLON.serialize = serialize;
  6984. function serializeAsTexture(sourceName) {
  6985. return generateSerializableMember(1, sourceName); // texture member
  6986. }
  6987. BABYLON.serializeAsTexture = serializeAsTexture;
  6988. function serializeAsColor3(sourceName) {
  6989. return generateSerializableMember(2, sourceName); // color3 member
  6990. }
  6991. BABYLON.serializeAsColor3 = serializeAsColor3;
  6992. function serializeAsFresnelParameters(sourceName) {
  6993. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6994. }
  6995. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6996. function serializeAsVector2(sourceName) {
  6997. return generateSerializableMember(4, sourceName); // vector2 member
  6998. }
  6999. BABYLON.serializeAsVector2 = serializeAsVector2;
  7000. function serializeAsVector3(sourceName) {
  7001. return generateSerializableMember(5, sourceName); // vector3 member
  7002. }
  7003. BABYLON.serializeAsVector3 = serializeAsVector3;
  7004. function serializeAsMeshReference(sourceName) {
  7005. return generateSerializableMember(6, sourceName); // mesh reference member
  7006. }
  7007. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7008. function serializeAsColorCurves(sourceName) {
  7009. return generateSerializableMember(7, sourceName); // color curves
  7010. }
  7011. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7012. function serializeAsColor4(sourceName) {
  7013. return generateSerializableMember(8, sourceName); // color 4
  7014. }
  7015. BABYLON.serializeAsColor4 = serializeAsColor4;
  7016. function serializeAsImageProcessingConfiguration(sourceName) {
  7017. return generateSerializableMember(9, sourceName); // image processing
  7018. }
  7019. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7020. function serializeAsQuaternion(sourceName) {
  7021. return generateSerializableMember(10, sourceName); // quaternion member
  7022. }
  7023. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7024. var SerializationHelper = /** @class */ (function () {
  7025. function SerializationHelper() {
  7026. }
  7027. SerializationHelper.Serialize = function (entity, serializationObject) {
  7028. if (!serializationObject) {
  7029. serializationObject = {};
  7030. }
  7031. // Tags
  7032. if (BABYLON.Tags) {
  7033. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7034. }
  7035. var serializedProperties = getMergedStore(entity);
  7036. // Properties
  7037. for (var property in serializedProperties) {
  7038. var propertyDescriptor = serializedProperties[property];
  7039. var targetPropertyName = propertyDescriptor.sourceName || property;
  7040. var propertyType = propertyDescriptor.type;
  7041. var sourceProperty = entity[property];
  7042. if (sourceProperty !== undefined && sourceProperty !== null) {
  7043. switch (propertyType) {
  7044. case 0:// Value
  7045. serializationObject[targetPropertyName] = sourceProperty;
  7046. break;
  7047. case 1:// Texture
  7048. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7049. break;
  7050. case 2:// Color3
  7051. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7052. break;
  7053. case 3:// FresnelParameters
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. case 4:// Vector2
  7057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7058. break;
  7059. case 5:// Vector3
  7060. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7061. break;
  7062. case 6:// Mesh reference
  7063. serializationObject[targetPropertyName] = sourceProperty.id;
  7064. break;
  7065. case 7:// Color Curves
  7066. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7067. break;
  7068. case 8:// Color 4
  7069. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7070. break;
  7071. case 9:// Image Processing
  7072. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7073. break;
  7074. }
  7075. }
  7076. }
  7077. return serializationObject;
  7078. };
  7079. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7080. if (rootUrl === void 0) { rootUrl = null; }
  7081. var destination = creationFunction();
  7082. if (!rootUrl) {
  7083. rootUrl = "";
  7084. }
  7085. // Tags
  7086. if (BABYLON.Tags) {
  7087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7088. }
  7089. var classStore = getMergedStore(destination);
  7090. // Properties
  7091. for (var property in classStore) {
  7092. var propertyDescriptor = classStore[property];
  7093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7094. var propertyType = propertyDescriptor.type;
  7095. if (sourceProperty !== undefined && sourceProperty !== null) {
  7096. var dest = destination;
  7097. switch (propertyType) {
  7098. case 0:// Value
  7099. dest[property] = sourceProperty;
  7100. break;
  7101. case 1:// Texture
  7102. if (scene) {
  7103. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7104. }
  7105. break;
  7106. case 2:// Color3
  7107. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7108. break;
  7109. case 3:// FresnelParameters
  7110. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7111. break;
  7112. case 4:// Vector2
  7113. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7114. break;
  7115. case 5:// Vector3
  7116. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7117. break;
  7118. case 6:// Mesh reference
  7119. if (scene) {
  7120. dest[property] = scene.getLastMeshByID(sourceProperty);
  7121. }
  7122. break;
  7123. case 7:// Color Curves
  7124. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7125. break;
  7126. case 8:// Color 4
  7127. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7128. break;
  7129. case 9:// Image Processing
  7130. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7131. break;
  7132. }
  7133. }
  7134. }
  7135. return destination;
  7136. };
  7137. SerializationHelper.Clone = function (creationFunction, source) {
  7138. return _copySource(creationFunction, source, false);
  7139. };
  7140. SerializationHelper.Instanciate = function (creationFunction, source) {
  7141. return _copySource(creationFunction, source, true);
  7142. };
  7143. return SerializationHelper;
  7144. }());
  7145. BABYLON.SerializationHelper = SerializationHelper;
  7146. })(BABYLON || (BABYLON = {}));
  7147. //# sourceMappingURL=babylon.decorators.js.map
  7148. var BABYLON;
  7149. (function (BABYLON) {
  7150. /**
  7151. * Wrapper class for promise with external resolve and reject.
  7152. */
  7153. var Deferred = /** @class */ (function () {
  7154. /**
  7155. * Constructor for this deferred object.
  7156. */
  7157. function Deferred() {
  7158. var _this = this;
  7159. this.promise = new Promise(function (resolve, reject) {
  7160. _this._resolve = resolve;
  7161. _this._reject = reject;
  7162. });
  7163. }
  7164. Object.defineProperty(Deferred.prototype, "resolve", {
  7165. /**
  7166. * The resolve method of the promise associated with this deferred object.
  7167. */
  7168. get: function () {
  7169. return this._resolve;
  7170. },
  7171. enumerable: true,
  7172. configurable: true
  7173. });
  7174. Object.defineProperty(Deferred.prototype, "reject", {
  7175. /**
  7176. * The reject method of the promise associated with this deferred object.
  7177. */
  7178. get: function () {
  7179. return this._reject;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184. return Deferred;
  7185. }());
  7186. BABYLON.Deferred = Deferred;
  7187. })(BABYLON || (BABYLON = {}));
  7188. //# sourceMappingURL=babylon.deferred.js.map
  7189. var BABYLON;
  7190. (function (BABYLON) {
  7191. /**
  7192. * A class serves as a medium between the observable and its observers
  7193. */
  7194. var EventState = /** @class */ (function () {
  7195. /**
  7196. * Create a new EventState
  7197. * @param mask defines the mask associated with this state
  7198. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7199. * @param target defines the original target of the state
  7200. * @param currentTarget defines the current target of the state
  7201. */
  7202. function EventState(mask, skipNextObservers, target, currentTarget) {
  7203. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7204. this.initalize(mask, skipNextObservers, target, currentTarget);
  7205. }
  7206. /**
  7207. * Initialize the current event state
  7208. * @param mask defines the mask associated with this state
  7209. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7210. * @param target defines the original target of the state
  7211. * @param currentTarget defines the current target of the state
  7212. * @returns the current event state
  7213. */
  7214. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7215. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7216. this.mask = mask;
  7217. this.skipNextObservers = skipNextObservers;
  7218. this.target = target;
  7219. this.currentTarget = currentTarget;
  7220. return this;
  7221. };
  7222. return EventState;
  7223. }());
  7224. BABYLON.EventState = EventState;
  7225. /**
  7226. * Represent an Observer registered to a given Observable object.
  7227. */
  7228. var Observer = /** @class */ (function () {
  7229. /**
  7230. * Creates a new observer
  7231. * @param callback defines the callback to call when the observer is notified
  7232. * @param mask defines the mask of the observer (used to filter notifications)
  7233. * @param scope defines the current scope used to restore the JS context
  7234. */
  7235. function Observer(
  7236. /**
  7237. * Defines the callback to call when the observer is notified
  7238. */
  7239. callback,
  7240. /**
  7241. * Defines the mask of the observer (used to filter notifications)
  7242. */
  7243. mask,
  7244. /**
  7245. * Defines the current scope used to restore the JS context
  7246. */
  7247. scope) {
  7248. if (scope === void 0) { scope = null; }
  7249. this.callback = callback;
  7250. this.mask = mask;
  7251. this.scope = scope;
  7252. /** @ignore */
  7253. this._willBeUnregistered = false;
  7254. /**
  7255. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7256. */
  7257. this.unregisterOnNextCall = false;
  7258. }
  7259. return Observer;
  7260. }());
  7261. BABYLON.Observer = Observer;
  7262. /**
  7263. * Represent a list of observers registered to multiple Observables object.
  7264. */
  7265. var MultiObserver = /** @class */ (function () {
  7266. function MultiObserver() {
  7267. }
  7268. /**
  7269. * Release associated resources
  7270. */
  7271. MultiObserver.prototype.dispose = function () {
  7272. if (this._observers && this._observables) {
  7273. for (var index = 0; index < this._observers.length; index++) {
  7274. this._observables[index].remove(this._observers[index]);
  7275. }
  7276. }
  7277. this._observers = null;
  7278. this._observables = null;
  7279. };
  7280. /**
  7281. * Raise a callback when one of the observable will notify
  7282. * @param observables defines a list of observables to watch
  7283. * @param callback defines the callback to call on notification
  7284. * @param mask defines the mask used to filter notifications
  7285. * @param scope defines the current scope used to restore the JS context
  7286. * @returns the new MultiObserver
  7287. */
  7288. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7289. if (mask === void 0) { mask = -1; }
  7290. if (scope === void 0) { scope = null; }
  7291. var result = new MultiObserver();
  7292. result._observers = new Array();
  7293. result._observables = observables;
  7294. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7295. var observable = observables_1[_i];
  7296. var observer = observable.add(callback, mask, false, scope);
  7297. if (observer) {
  7298. result._observers.push(observer);
  7299. }
  7300. }
  7301. return result;
  7302. };
  7303. return MultiObserver;
  7304. }());
  7305. BABYLON.MultiObserver = MultiObserver;
  7306. /**
  7307. * The Observable class is a simple implementation of the Observable pattern.
  7308. * 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.
  7309. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7310. * 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).
  7311. * 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.
  7312. */
  7313. var Observable = /** @class */ (function () {
  7314. /**
  7315. * Creates a new observable
  7316. * @param onObserverAdded defines a callback to call when a new observer is added
  7317. */
  7318. function Observable(onObserverAdded) {
  7319. this._observers = new Array();
  7320. this._eventState = new EventState(0);
  7321. if (onObserverAdded) {
  7322. this._onObserverAdded = onObserverAdded;
  7323. }
  7324. }
  7325. /**
  7326. * Create a new Observer with the specified callback
  7327. * @param callback the callback that will be executed for that Observer
  7328. * @param mask the mask used to filter observers
  7329. * @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.
  7330. * @param scope optional scope for the callback to be called from
  7331. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7332. * @returns the new observer created for the callback
  7333. */
  7334. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7335. if (mask === void 0) { mask = -1; }
  7336. if (insertFirst === void 0) { insertFirst = false; }
  7337. if (scope === void 0) { scope = null; }
  7338. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7339. if (!callback) {
  7340. return null;
  7341. }
  7342. var observer = new Observer(callback, mask, scope);
  7343. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7344. if (insertFirst) {
  7345. this._observers.unshift(observer);
  7346. }
  7347. else {
  7348. this._observers.push(observer);
  7349. }
  7350. if (this._onObserverAdded) {
  7351. this._onObserverAdded(observer);
  7352. }
  7353. return observer;
  7354. };
  7355. /**
  7356. * Remove an Observer from the Observable object
  7357. * @param observer the instance of the Observer to remove
  7358. * @returns false if it doesn't belong to this Observable
  7359. */
  7360. Observable.prototype.remove = function (observer) {
  7361. if (!observer) {
  7362. return false;
  7363. }
  7364. var index = this._observers.indexOf(observer);
  7365. if (index !== -1) {
  7366. this._observers.splice(index, 1);
  7367. return true;
  7368. }
  7369. return false;
  7370. };
  7371. /**
  7372. * Remove a callback from the Observable object
  7373. * @param callback the callback to remove
  7374. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7375. * @returns false if it doesn't belong to this Observable
  7376. */
  7377. Observable.prototype.removeCallback = function (callback, scope) {
  7378. for (var index = 0; index < this._observers.length; index++) {
  7379. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7380. this._observers.splice(index, 1);
  7381. return true;
  7382. }
  7383. }
  7384. return false;
  7385. };
  7386. Observable.prototype._deferUnregister = function (observer) {
  7387. var _this = this;
  7388. observer.unregisterOnNextCall = false;
  7389. observer._willBeUnregistered = true;
  7390. BABYLON.Tools.SetImmediate(function () {
  7391. _this.remove(observer);
  7392. });
  7393. };
  7394. /**
  7395. * Notify all Observers by calling their respective callback with the given data
  7396. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7397. * @param eventData defines the data to send to all observers
  7398. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7399. * @param target defines the original target of the state
  7400. * @param currentTarget defines the current target of the state
  7401. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7402. */
  7403. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7404. if (mask === void 0) { mask = -1; }
  7405. if (!this._observers.length) {
  7406. return true;
  7407. }
  7408. var state = this._eventState;
  7409. state.mask = mask;
  7410. state.target = target;
  7411. state.currentTarget = currentTarget;
  7412. state.skipNextObservers = false;
  7413. state.lastReturnValue = eventData;
  7414. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7415. var obs = _a[_i];
  7416. if (obs._willBeUnregistered) {
  7417. continue;
  7418. }
  7419. if (obs.mask & mask) {
  7420. if (obs.scope) {
  7421. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7422. }
  7423. else {
  7424. state.lastReturnValue = obs.callback(eventData, state);
  7425. }
  7426. if (obs.unregisterOnNextCall) {
  7427. this._deferUnregister(obs);
  7428. }
  7429. }
  7430. if (state.skipNextObservers) {
  7431. return false;
  7432. }
  7433. }
  7434. return true;
  7435. };
  7436. /**
  7437. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7438. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7439. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7440. * and it is crucial that all callbacks will be executed.
  7441. * The order of the callbacks is kept, callbacks are not executed parallel.
  7442. *
  7443. * @param eventData The data to be sent to each callback
  7444. * @param mask is used to filter observers defaults to -1
  7445. * @param target defines the callback target (see EventState)
  7446. * @param currentTarget defines he current object in the bubbling phase
  7447. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7448. */
  7449. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7450. var _this = this;
  7451. if (mask === void 0) { mask = -1; }
  7452. // create an empty promise
  7453. var p = Promise.resolve(eventData);
  7454. // no observers? return this promise.
  7455. if (!this._observers.length) {
  7456. return p;
  7457. }
  7458. var state = this._eventState;
  7459. state.mask = mask;
  7460. state.target = target;
  7461. state.currentTarget = currentTarget;
  7462. state.skipNextObservers = false;
  7463. // execute one callback after another (not using Promise.all, the order is important)
  7464. this._observers.forEach(function (obs) {
  7465. if (state.skipNextObservers) {
  7466. return;
  7467. }
  7468. if (obs._willBeUnregistered) {
  7469. return;
  7470. }
  7471. if (obs.mask & mask) {
  7472. if (obs.scope) {
  7473. p = p.then(function (lastReturnedValue) {
  7474. state.lastReturnValue = lastReturnedValue;
  7475. return obs.callback.apply(obs.scope, [eventData, state]);
  7476. });
  7477. }
  7478. else {
  7479. p = p.then(function (lastReturnedValue) {
  7480. state.lastReturnValue = lastReturnedValue;
  7481. return obs.callback(eventData, state);
  7482. });
  7483. }
  7484. if (obs.unregisterOnNextCall) {
  7485. _this._deferUnregister(obs);
  7486. }
  7487. }
  7488. });
  7489. // return the eventData
  7490. return p.then(function () { return eventData; });
  7491. };
  7492. /**
  7493. * Notify a specific observer
  7494. * @param observer defines the observer to notify
  7495. * @param eventData defines the data to be sent to each callback
  7496. * @param mask is used to filter observers defaults to -1
  7497. */
  7498. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7499. if (mask === void 0) { mask = -1; }
  7500. var state = this._eventState;
  7501. state.mask = mask;
  7502. state.skipNextObservers = false;
  7503. observer.callback(eventData, state);
  7504. };
  7505. /**
  7506. * Gets a boolean indicating if the observable has at least one observer
  7507. * @returns true is the Observable has at least one Observer registered
  7508. */
  7509. Observable.prototype.hasObservers = function () {
  7510. return this._observers.length > 0;
  7511. };
  7512. /**
  7513. * Clear the list of observers
  7514. */
  7515. Observable.prototype.clear = function () {
  7516. this._observers = new Array();
  7517. this._onObserverAdded = null;
  7518. };
  7519. /**
  7520. * Clone the current observable
  7521. * @returns a new observable
  7522. */
  7523. Observable.prototype.clone = function () {
  7524. var result = new Observable();
  7525. result._observers = this._observers.slice(0);
  7526. return result;
  7527. };
  7528. /**
  7529. * Does this observable handles observer registered with a given mask
  7530. * @param mask defines the mask to be tested
  7531. * @return whether or not one observer registered with the given mask is handeled
  7532. **/
  7533. Observable.prototype.hasSpecificMask = function (mask) {
  7534. if (mask === void 0) { mask = -1; }
  7535. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7536. var obs = _a[_i];
  7537. if (obs.mask & mask || obs.mask === mask) {
  7538. return true;
  7539. }
  7540. }
  7541. return false;
  7542. };
  7543. return Observable;
  7544. }());
  7545. BABYLON.Observable = Observable;
  7546. })(BABYLON || (BABYLON = {}));
  7547. //# sourceMappingURL=babylon.observable.js.map
  7548. var BABYLON;
  7549. (function (BABYLON) {
  7550. var SmartArray = /** @class */ (function () {
  7551. function SmartArray(capacity) {
  7552. this.length = 0;
  7553. this.data = new Array(capacity);
  7554. this._id = SmartArray._GlobalId++;
  7555. }
  7556. SmartArray.prototype.push = function (value) {
  7557. this.data[this.length++] = value;
  7558. if (this.length > this.data.length) {
  7559. this.data.length *= 2;
  7560. }
  7561. };
  7562. SmartArray.prototype.forEach = function (func) {
  7563. for (var index = 0; index < this.length; index++) {
  7564. func(this.data[index]);
  7565. }
  7566. };
  7567. SmartArray.prototype.sort = function (compareFn) {
  7568. this.data.sort(compareFn);
  7569. };
  7570. SmartArray.prototype.reset = function () {
  7571. this.length = 0;
  7572. };
  7573. SmartArray.prototype.dispose = function () {
  7574. this.reset();
  7575. if (this.data) {
  7576. this.data.length = 0;
  7577. this.data = [];
  7578. }
  7579. };
  7580. SmartArray.prototype.concat = function (array) {
  7581. if (array.length === 0) {
  7582. return;
  7583. }
  7584. if (this.length + array.length > this.data.length) {
  7585. this.data.length = (this.length + array.length) * 2;
  7586. }
  7587. for (var index = 0; index < array.length; index++) {
  7588. this.data[this.length++] = (array.data || array)[index];
  7589. }
  7590. };
  7591. SmartArray.prototype.indexOf = function (value) {
  7592. var position = this.data.indexOf(value);
  7593. if (position >= this.length) {
  7594. return -1;
  7595. }
  7596. return position;
  7597. };
  7598. SmartArray.prototype.contains = function (value) {
  7599. return this.data.indexOf(value) !== -1;
  7600. };
  7601. // Statics
  7602. SmartArray._GlobalId = 0;
  7603. return SmartArray;
  7604. }());
  7605. BABYLON.SmartArray = SmartArray;
  7606. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7607. __extends(SmartArrayNoDuplicate, _super);
  7608. function SmartArrayNoDuplicate() {
  7609. var _this = _super !== null && _super.apply(this, arguments) || this;
  7610. _this._duplicateId = 0;
  7611. return _this;
  7612. }
  7613. SmartArrayNoDuplicate.prototype.push = function (value) {
  7614. _super.prototype.push.call(this, value);
  7615. if (!value.__smartArrayFlags) {
  7616. value.__smartArrayFlags = {};
  7617. }
  7618. value.__smartArrayFlags[this._id] = this._duplicateId;
  7619. };
  7620. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7621. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7622. return false;
  7623. }
  7624. this.push(value);
  7625. return true;
  7626. };
  7627. SmartArrayNoDuplicate.prototype.reset = function () {
  7628. _super.prototype.reset.call(this);
  7629. this._duplicateId++;
  7630. };
  7631. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7632. if (array.length === 0) {
  7633. return;
  7634. }
  7635. if (this.length + array.length > this.data.length) {
  7636. this.data.length = (this.length + array.length) * 2;
  7637. }
  7638. for (var index = 0; index < array.length; index++) {
  7639. var item = (array.data || array)[index];
  7640. this.pushNoDuplicate(item);
  7641. }
  7642. };
  7643. return SmartArrayNoDuplicate;
  7644. }(SmartArray));
  7645. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7646. })(BABYLON || (BABYLON = {}));
  7647. //# sourceMappingURL=babylon.smartArray.js.map
  7648. var BABYLON;
  7649. (function (BABYLON) {
  7650. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7651. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7652. var LoadFileError = /** @class */ (function (_super) {
  7653. __extends(LoadFileError, _super);
  7654. function LoadFileError(message, request) {
  7655. var _this = _super.call(this, message) || this;
  7656. _this.request = request;
  7657. _this.name = "LoadFileError";
  7658. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7659. return _this;
  7660. }
  7661. // Polyfill for Object.setPrototypeOf if necessary.
  7662. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7663. return LoadFileError;
  7664. }(Error));
  7665. BABYLON.LoadFileError = LoadFileError;
  7666. var RetryStrategy = /** @class */ (function () {
  7667. function RetryStrategy() {
  7668. }
  7669. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7670. if (maxRetries === void 0) { maxRetries = 3; }
  7671. if (baseInterval === void 0) { baseInterval = 500; }
  7672. return function (url, request, retryIndex) {
  7673. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7674. return -1;
  7675. }
  7676. return Math.pow(2, retryIndex) * baseInterval;
  7677. };
  7678. };
  7679. return RetryStrategy;
  7680. }());
  7681. BABYLON.RetryStrategy = RetryStrategy;
  7682. // Screenshots
  7683. var screenshotCanvas;
  7684. var cloneValue = function (source, destinationObject) {
  7685. if (!source)
  7686. return null;
  7687. if (source instanceof BABYLON.Mesh) {
  7688. return null;
  7689. }
  7690. if (source instanceof BABYLON.SubMesh) {
  7691. return source.clone(destinationObject);
  7692. }
  7693. else if (source.clone) {
  7694. return source.clone();
  7695. }
  7696. return null;
  7697. };
  7698. var Tools = /** @class */ (function () {
  7699. function Tools() {
  7700. }
  7701. /**
  7702. * Interpolates between a and b via alpha
  7703. * @param a The lower value (returned when alpha = 0)
  7704. * @param b The upper value (returned when alpha = 1)
  7705. * @param alpha The interpolation-factor
  7706. * @return The mixed value
  7707. */
  7708. Tools.Mix = function (a, b, alpha) {
  7709. return a * (1 - alpha) + b * alpha;
  7710. };
  7711. Tools.Instantiate = function (className) {
  7712. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7713. return Tools.RegisteredExternalClasses[className];
  7714. }
  7715. var arr = className.split(".");
  7716. var fn = (window || this);
  7717. for (var i = 0, len = arr.length; i < len; i++) {
  7718. fn = fn[arr[i]];
  7719. }
  7720. if (typeof fn !== "function") {
  7721. return null;
  7722. }
  7723. return fn;
  7724. };
  7725. /**
  7726. * Provides a slice function that will work even on IE
  7727. * @param data defines the array to slice
  7728. * @returns the new sliced array
  7729. */
  7730. Tools.Slice = function (data) {
  7731. if (data.slice) {
  7732. return data.slice();
  7733. }
  7734. return Array.prototype.slice.call(data);
  7735. };
  7736. Tools.SetImmediate = function (action) {
  7737. if (window.setImmediate) {
  7738. window.setImmediate(action);
  7739. }
  7740. else {
  7741. setTimeout(action, 1);
  7742. }
  7743. };
  7744. Tools.IsExponentOfTwo = function (value) {
  7745. var count = 1;
  7746. do {
  7747. count *= 2;
  7748. } while (count < value);
  7749. return count === value;
  7750. };
  7751. /**
  7752. * Find the next highest power of two.
  7753. * @param x Number to start search from.
  7754. * @return Next highest power of two.
  7755. */
  7756. Tools.CeilingPOT = function (x) {
  7757. x--;
  7758. x |= x >> 1;
  7759. x |= x >> 2;
  7760. x |= x >> 4;
  7761. x |= x >> 8;
  7762. x |= x >> 16;
  7763. x++;
  7764. return x;
  7765. };
  7766. /**
  7767. * Find the next lowest power of two.
  7768. * @param x Number to start search from.
  7769. * @return Next lowest power of two.
  7770. */
  7771. Tools.FloorPOT = function (x) {
  7772. x = x | (x >> 1);
  7773. x = x | (x >> 2);
  7774. x = x | (x >> 4);
  7775. x = x | (x >> 8);
  7776. x = x | (x >> 16);
  7777. return x - (x >> 1);
  7778. };
  7779. /**
  7780. * Find the nearest power of two.
  7781. * @param x Number to start search from.
  7782. * @return Next nearest power of two.
  7783. */
  7784. Tools.NearestPOT = function (x) {
  7785. var c = Tools.CeilingPOT(x);
  7786. var f = Tools.FloorPOT(x);
  7787. return (c - x) > (x - f) ? f : c;
  7788. };
  7789. Tools.GetExponentOfTwo = function (value, max, mode) {
  7790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7791. var pot;
  7792. switch (mode) {
  7793. case BABYLON.Engine.SCALEMODE_FLOOR:
  7794. pot = Tools.FloorPOT(value);
  7795. break;
  7796. case BABYLON.Engine.SCALEMODE_NEAREST:
  7797. pot = Tools.NearestPOT(value);
  7798. break;
  7799. case BABYLON.Engine.SCALEMODE_CEILING:
  7800. default:
  7801. pot = Tools.CeilingPOT(value);
  7802. break;
  7803. }
  7804. return Math.min(pot, max);
  7805. };
  7806. Tools.GetFilename = function (path) {
  7807. var index = path.lastIndexOf("/");
  7808. if (index < 0)
  7809. return path;
  7810. return path.substring(index + 1);
  7811. };
  7812. /**
  7813. * Extracts the "folder" part of a path (everything before the filename).
  7814. * @param uri The URI to extract the info from
  7815. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7816. * @returns The "folder" part of the path
  7817. */
  7818. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7819. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7820. var index = uri.lastIndexOf("/");
  7821. if (index < 0) {
  7822. if (returnUnchangedIfNoSlash) {
  7823. return uri;
  7824. }
  7825. return "";
  7826. }
  7827. return uri.substring(0, index + 1);
  7828. };
  7829. Tools.GetDOMTextContent = function (element) {
  7830. var result = "";
  7831. var child = element.firstChild;
  7832. while (child) {
  7833. if (child.nodeType === 3) {
  7834. result += child.textContent;
  7835. }
  7836. child = child.nextSibling;
  7837. }
  7838. return result;
  7839. };
  7840. Tools.ToDegrees = function (angle) {
  7841. return angle * 180 / Math.PI;
  7842. };
  7843. Tools.ToRadians = function (angle) {
  7844. return angle * Math.PI / 180;
  7845. };
  7846. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7847. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7848. var output = "";
  7849. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7850. var i = 0;
  7851. var bytes = new Uint8Array(buffer);
  7852. while (i < bytes.length) {
  7853. chr1 = bytes[i++];
  7854. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7855. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7856. enc1 = chr1 >> 2;
  7857. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7858. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7859. enc4 = chr3 & 63;
  7860. if (isNaN(chr2)) {
  7861. enc3 = enc4 = 64;
  7862. }
  7863. else if (isNaN(chr3)) {
  7864. enc4 = 64;
  7865. }
  7866. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7867. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7868. }
  7869. return "data:image/png;base64," + output;
  7870. };
  7871. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7872. if (bias === void 0) { bias = null; }
  7873. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7874. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7875. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7876. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7877. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7878. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7879. }
  7880. if (bias) {
  7881. minimum.x -= minimum.x * bias.x + bias.y;
  7882. minimum.y -= minimum.y * bias.x + bias.y;
  7883. minimum.z -= minimum.z * bias.x + bias.y;
  7884. maximum.x += maximum.x * bias.x + bias.y;
  7885. maximum.y += maximum.y * bias.x + bias.y;
  7886. maximum.z += maximum.z * bias.x + bias.y;
  7887. }
  7888. return {
  7889. minimum: minimum,
  7890. maximum: maximum
  7891. };
  7892. };
  7893. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7894. if (bias === void 0) { bias = null; }
  7895. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7896. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7897. if (!stride) {
  7898. stride = 3;
  7899. }
  7900. for (var index = start; index < start + count; index++) {
  7901. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7904. }
  7905. if (bias) {
  7906. minimum.x -= minimum.x * bias.x + bias.y;
  7907. minimum.y -= minimum.y * bias.x + bias.y;
  7908. minimum.z -= minimum.z * bias.x + bias.y;
  7909. maximum.x += maximum.x * bias.x + bias.y;
  7910. maximum.y += maximum.y * bias.x + bias.y;
  7911. maximum.z += maximum.z * bias.x + bias.y;
  7912. }
  7913. return {
  7914. minimum: minimum,
  7915. maximum: maximum
  7916. };
  7917. };
  7918. Tools.Vector2ArrayFeeder = function (array) {
  7919. return function (index) {
  7920. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7921. var length = isFloatArray ? array.length / 2 : array.length;
  7922. if (index >= length) {
  7923. return null;
  7924. }
  7925. if (isFloatArray) {
  7926. var fa = array;
  7927. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7928. }
  7929. var a = array;
  7930. return a[index];
  7931. };
  7932. };
  7933. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7934. if (bias === void 0) { bias = null; }
  7935. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7936. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7937. var i = 0;
  7938. var cur = feeder(i++);
  7939. while (cur) {
  7940. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7941. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7942. cur = feeder(i++);
  7943. }
  7944. if (bias) {
  7945. minimum.x -= minimum.x * bias.x + bias.y;
  7946. minimum.y -= minimum.y * bias.x + bias.y;
  7947. maximum.x += maximum.x * bias.x + bias.y;
  7948. maximum.y += maximum.y * bias.x + bias.y;
  7949. }
  7950. return {
  7951. minimum: minimum,
  7952. maximum: maximum
  7953. };
  7954. };
  7955. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7956. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7957. return null;
  7958. return Array.isArray(obj) ? obj : [obj];
  7959. };
  7960. // Misc.
  7961. Tools.GetPointerPrefix = function () {
  7962. var eventPrefix = "pointer";
  7963. // Check if pointer events are supported
  7964. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7965. eventPrefix = "mouse";
  7966. }
  7967. return eventPrefix;
  7968. };
  7969. /**
  7970. * @param func - the function to be called
  7971. * @param requester - the object that will request the next frame. Falls back to window.
  7972. */
  7973. Tools.QueueNewFrame = function (func, requester) {
  7974. if (!Tools.IsWindowObjectExist()) {
  7975. return setTimeout(func, 16);
  7976. }
  7977. if (!requester) {
  7978. requester = window;
  7979. }
  7980. if (requester.requestAnimationFrame) {
  7981. return requester.requestAnimationFrame(func);
  7982. }
  7983. else if (requester.msRequestAnimationFrame) {
  7984. return requester.msRequestAnimationFrame(func);
  7985. }
  7986. else if (requester.webkitRequestAnimationFrame) {
  7987. return requester.webkitRequestAnimationFrame(func);
  7988. }
  7989. else if (requester.mozRequestAnimationFrame) {
  7990. return requester.mozRequestAnimationFrame(func);
  7991. }
  7992. else if (requester.oRequestAnimationFrame) {
  7993. return requester.oRequestAnimationFrame(func);
  7994. }
  7995. else {
  7996. return window.setTimeout(func, 16);
  7997. }
  7998. };
  7999. Tools.RequestFullscreen = function (element) {
  8000. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8001. if (!requestFunction)
  8002. return;
  8003. requestFunction.call(element);
  8004. };
  8005. Tools.ExitFullscreen = function () {
  8006. if (document.exitFullscreen) {
  8007. document.exitFullscreen();
  8008. }
  8009. else if (document.mozCancelFullScreen) {
  8010. document.mozCancelFullScreen();
  8011. }
  8012. else if (document.webkitCancelFullScreen) {
  8013. document.webkitCancelFullScreen();
  8014. }
  8015. else if (document.msCancelFullScreen) {
  8016. document.msCancelFullScreen();
  8017. }
  8018. };
  8019. Tools.SetCorsBehavior = function (url, element) {
  8020. if (url && url.indexOf("data:") === 0) {
  8021. return;
  8022. }
  8023. if (Tools.CorsBehavior) {
  8024. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8025. element.crossOrigin = Tools.CorsBehavior;
  8026. }
  8027. else {
  8028. var result = Tools.CorsBehavior(url);
  8029. if (result) {
  8030. element.crossOrigin = result;
  8031. }
  8032. }
  8033. }
  8034. };
  8035. // External files
  8036. Tools.CleanUrl = function (url) {
  8037. url = url.replace(/#/mg, "%23");
  8038. return url;
  8039. };
  8040. Tools.LoadImage = function (url, onLoad, onError, database) {
  8041. if (url instanceof ArrayBuffer) {
  8042. url = Tools.EncodeArrayBufferTobase64(url);
  8043. }
  8044. url = Tools.CleanUrl(url);
  8045. url = Tools.PreprocessUrl(url);
  8046. var img = new Image();
  8047. Tools.SetCorsBehavior(url, img);
  8048. var loadHandler = function () {
  8049. img.removeEventListener("load", loadHandler);
  8050. img.removeEventListener("error", errorHandler);
  8051. onLoad(img);
  8052. };
  8053. var errorHandler = function (err) {
  8054. img.removeEventListener("load", loadHandler);
  8055. img.removeEventListener("error", errorHandler);
  8056. Tools.Error("Error while trying to load image: " + url);
  8057. if (onError) {
  8058. onError("Error while trying to load image: " + url, err);
  8059. }
  8060. };
  8061. img.addEventListener("load", loadHandler);
  8062. img.addEventListener("error", errorHandler);
  8063. var noIndexedDB = function () {
  8064. img.src = url;
  8065. };
  8066. var loadFromIndexedDB = function () {
  8067. if (database) {
  8068. database.loadImageFromDB(url, img);
  8069. }
  8070. };
  8071. //ANY database to do!
  8072. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8073. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8074. }
  8075. else {
  8076. if (url.indexOf("file:") !== -1) {
  8077. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8078. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8079. try {
  8080. var blobURL;
  8081. try {
  8082. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8083. }
  8084. catch (ex) {
  8085. // Chrome doesn't support oneTimeOnly parameter
  8086. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8087. }
  8088. img.src = blobURL;
  8089. }
  8090. catch (e) {
  8091. img.src = "";
  8092. }
  8093. return img;
  8094. }
  8095. }
  8096. noIndexedDB();
  8097. }
  8098. return img;
  8099. };
  8100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8101. url = Tools.CleanUrl(url);
  8102. url = Tools.PreprocessUrl(url);
  8103. // If file and file input are set
  8104. if (url.indexOf("file:") !== -1) {
  8105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8108. }
  8109. }
  8110. var loadUrl = Tools.BaseUrl + url;
  8111. var aborted = false;
  8112. var fileRequest = {
  8113. onCompleteObservable: new BABYLON.Observable(),
  8114. abort: function () { return aborted = true; },
  8115. };
  8116. var requestFile = function () {
  8117. var request = new XMLHttpRequest();
  8118. var retryHandle = null;
  8119. fileRequest.abort = function () {
  8120. aborted = true;
  8121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8122. request.abort();
  8123. }
  8124. if (retryHandle !== null) {
  8125. clearTimeout(retryHandle);
  8126. retryHandle = null;
  8127. }
  8128. };
  8129. var retryLoop = function (retryIndex) {
  8130. request.open('GET', loadUrl, true);
  8131. if (useArrayBuffer) {
  8132. request.responseType = "arraybuffer";
  8133. }
  8134. if (onProgress) {
  8135. request.addEventListener("progress", onProgress);
  8136. }
  8137. var onLoadEnd = function () {
  8138. request.removeEventListener("loadend", onLoadEnd);
  8139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8140. fileRequest.onCompleteObservable.clear();
  8141. };
  8142. request.addEventListener("loadend", onLoadEnd);
  8143. var onReadyStateChange = function () {
  8144. if (aborted) {
  8145. return;
  8146. }
  8147. // In case of undefined state in some browsers.
  8148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8150. request.removeEventListener("readystatechange", onReadyStateChange);
  8151. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8153. return;
  8154. }
  8155. var retryStrategy = Tools.DefaultRetryStrategy;
  8156. if (retryStrategy) {
  8157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8158. if (waitTime !== -1) {
  8159. // Prevent the request from completing for retry.
  8160. request.removeEventListener("loadend", onLoadEnd);
  8161. request = new XMLHttpRequest();
  8162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8163. return;
  8164. }
  8165. }
  8166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8167. if (onError) {
  8168. onError(request, e);
  8169. }
  8170. else {
  8171. throw e;
  8172. }
  8173. }
  8174. };
  8175. request.addEventListener("readystatechange", onReadyStateChange);
  8176. request.send();
  8177. };
  8178. retryLoop(0);
  8179. };
  8180. // Caching all files
  8181. if (database && database.enableSceneOffline) {
  8182. var noIndexedDB_1 = function () {
  8183. if (!aborted) {
  8184. requestFile();
  8185. }
  8186. };
  8187. var loadFromIndexedDB = function () {
  8188. // TODO: database needs to support aborting and should return a IFileRequest
  8189. if (aborted) {
  8190. return;
  8191. }
  8192. if (database) {
  8193. database.loadFileFromDB(url, function (data) {
  8194. if (!aborted) {
  8195. onSuccess(data);
  8196. }
  8197. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8198. }, onProgress ? function (event) {
  8199. if (!aborted) {
  8200. onProgress(event);
  8201. }
  8202. } : undefined, noIndexedDB_1, useArrayBuffer);
  8203. }
  8204. };
  8205. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8206. }
  8207. else {
  8208. requestFile();
  8209. }
  8210. return fileRequest;
  8211. };
  8212. /**
  8213. * Load a script (identified by an url). When the url returns, the
  8214. * content of this file is added into a new script element, attached to the DOM (body element)
  8215. */
  8216. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8217. var head = document.getElementsByTagName('head')[0];
  8218. var script = document.createElement('script');
  8219. script.type = 'text/javascript';
  8220. script.src = scriptUrl;
  8221. script.onload = function () {
  8222. if (onSuccess) {
  8223. onSuccess();
  8224. }
  8225. };
  8226. script.onerror = function (e) {
  8227. if (onError) {
  8228. onError("Unable to load script", e);
  8229. }
  8230. };
  8231. head.appendChild(script);
  8232. };
  8233. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8234. var reader = new FileReader();
  8235. var request = {
  8236. onCompleteObservable: new BABYLON.Observable(),
  8237. abort: function () { return reader.abort(); },
  8238. };
  8239. reader.onloadend = function (e) {
  8240. request.onCompleteObservable.notifyObservers(request);
  8241. };
  8242. reader.onload = function (e) {
  8243. //target doesn't have result from ts 1.3
  8244. callback(e.target['result']);
  8245. };
  8246. reader.onprogress = progressCallback;
  8247. reader.readAsDataURL(fileToLoad);
  8248. return request;
  8249. };
  8250. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8251. var reader = new FileReader();
  8252. var request = {
  8253. onCompleteObservable: new BABYLON.Observable(),
  8254. abort: function () { return reader.abort(); },
  8255. };
  8256. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8257. reader.onerror = function (e) {
  8258. Tools.Log("Error while reading file: " + fileToLoad.name);
  8259. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8260. };
  8261. reader.onload = function (e) {
  8262. //target doesn't have result from ts 1.3
  8263. callback(e.target['result']);
  8264. };
  8265. if (progressCallBack) {
  8266. reader.onprogress = progressCallBack;
  8267. }
  8268. if (!useArrayBuffer) {
  8269. // Asynchronous read
  8270. reader.readAsText(fileToLoad);
  8271. }
  8272. else {
  8273. reader.readAsArrayBuffer(fileToLoad);
  8274. }
  8275. return request;
  8276. };
  8277. //returns a downloadable url to a file content.
  8278. Tools.FileAsURL = function (content) {
  8279. var fileBlob = new Blob([content]);
  8280. var url = window.URL || window.webkitURL;
  8281. var link = url.createObjectURL(fileBlob);
  8282. return link;
  8283. };
  8284. // Misc.
  8285. Tools.Format = function (value, decimals) {
  8286. if (decimals === void 0) { decimals = 2; }
  8287. return value.toFixed(decimals);
  8288. };
  8289. Tools.CheckExtends = function (v, min, max) {
  8290. if (v.x < min.x)
  8291. min.x = v.x;
  8292. if (v.y < min.y)
  8293. min.y = v.y;
  8294. if (v.z < min.z)
  8295. min.z = v.z;
  8296. if (v.x > max.x)
  8297. max.x = v.x;
  8298. if (v.y > max.y)
  8299. max.y = v.y;
  8300. if (v.z > max.z)
  8301. max.z = v.z;
  8302. };
  8303. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8304. for (var prop in source) {
  8305. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8306. continue;
  8307. }
  8308. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8309. continue;
  8310. }
  8311. var sourceValue = source[prop];
  8312. var typeOfSourceValue = typeof sourceValue;
  8313. if (typeOfSourceValue === "function") {
  8314. continue;
  8315. }
  8316. if (typeOfSourceValue === "object") {
  8317. if (sourceValue instanceof Array) {
  8318. destination[prop] = [];
  8319. if (sourceValue.length > 0) {
  8320. if (typeof sourceValue[0] == "object") {
  8321. for (var index = 0; index < sourceValue.length; index++) {
  8322. var clonedValue = cloneValue(sourceValue[index], destination);
  8323. if (destination[prop].indexOf(clonedValue) === -1) {
  8324. destination[prop].push(clonedValue);
  8325. }
  8326. }
  8327. }
  8328. else {
  8329. destination[prop] = sourceValue.slice(0);
  8330. }
  8331. }
  8332. }
  8333. else {
  8334. destination[prop] = cloneValue(sourceValue, destination);
  8335. }
  8336. }
  8337. else {
  8338. destination[prop] = sourceValue;
  8339. }
  8340. }
  8341. };
  8342. Tools.IsEmpty = function (obj) {
  8343. for (var i in obj) {
  8344. if (obj.hasOwnProperty(i)) {
  8345. return false;
  8346. }
  8347. }
  8348. return true;
  8349. };
  8350. Tools.RegisterTopRootEvents = function (events) {
  8351. for (var index = 0; index < events.length; index++) {
  8352. var event = events[index];
  8353. window.addEventListener(event.name, event.handler, false);
  8354. try {
  8355. if (window.parent) {
  8356. window.parent.addEventListener(event.name, event.handler, false);
  8357. }
  8358. }
  8359. catch (e) {
  8360. // Silently fails...
  8361. }
  8362. }
  8363. };
  8364. Tools.UnregisterTopRootEvents = function (events) {
  8365. for (var index = 0; index < events.length; index++) {
  8366. var event = events[index];
  8367. window.removeEventListener(event.name, event.handler);
  8368. try {
  8369. if (window.parent) {
  8370. window.parent.removeEventListener(event.name, event.handler);
  8371. }
  8372. }
  8373. catch (e) {
  8374. // Silently fails...
  8375. }
  8376. }
  8377. };
  8378. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8379. if (mimeType === void 0) { mimeType = "image/png"; }
  8380. // Read the contents of the framebuffer
  8381. var numberOfChannelsByLine = width * 4;
  8382. var halfHeight = height / 2;
  8383. //Reading datas from WebGL
  8384. var data = engine.readPixels(0, 0, width, height);
  8385. //To flip image on Y axis.
  8386. for (var i = 0; i < halfHeight; i++) {
  8387. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8388. var currentCell = j + i * numberOfChannelsByLine;
  8389. var targetLine = height - i - 1;
  8390. var targetCell = j + targetLine * numberOfChannelsByLine;
  8391. var temp = data[currentCell];
  8392. data[currentCell] = data[targetCell];
  8393. data[targetCell] = temp;
  8394. }
  8395. }
  8396. // Create a 2D canvas to store the result
  8397. if (!screenshotCanvas) {
  8398. screenshotCanvas = document.createElement('canvas');
  8399. }
  8400. screenshotCanvas.width = width;
  8401. screenshotCanvas.height = height;
  8402. var context = screenshotCanvas.getContext('2d');
  8403. if (context) {
  8404. // Copy the pixels to a 2D canvas
  8405. var imageData = context.createImageData(width, height);
  8406. var castData = (imageData.data);
  8407. castData.set(data);
  8408. context.putImageData(imageData, 0, 0);
  8409. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8410. }
  8411. };
  8412. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8413. if (mimeType === void 0) { mimeType = "image/png"; }
  8414. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8415. if (successCallback) {
  8416. successCallback(base64Image);
  8417. }
  8418. else {
  8419. // We need HTMLCanvasElement.toBlob for HD screenshots
  8420. if (!screenshotCanvas.toBlob) {
  8421. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8422. screenshotCanvas.toBlob = function (callback, type, quality) {
  8423. var _this = this;
  8424. setTimeout(function () {
  8425. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8426. for (var i = 0; i < len; i++) {
  8427. arr[i] = binStr.charCodeAt(i);
  8428. }
  8429. callback(new Blob([arr], { type: type || 'image/png' }));
  8430. });
  8431. };
  8432. }
  8433. screenshotCanvas.toBlob(function (blob) {
  8434. var url = URL.createObjectURL(blob);
  8435. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8436. if (("download" in document.createElement("a"))) {
  8437. var a = window.document.createElement("a");
  8438. a.href = url;
  8439. if (fileName) {
  8440. a.setAttribute("download", fileName);
  8441. }
  8442. else {
  8443. var date = new Date();
  8444. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8445. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8446. }
  8447. window.document.body.appendChild(a);
  8448. a.addEventListener("click", function () {
  8449. if (a.parentElement) {
  8450. a.parentElement.removeChild(a);
  8451. }
  8452. });
  8453. a.click();
  8454. }
  8455. else {
  8456. var newWindow = window.open("");
  8457. if (!newWindow)
  8458. return;
  8459. var img = newWindow.document.createElement("img");
  8460. img.onload = function () {
  8461. // no longer need to read the blob so it's revoked
  8462. URL.revokeObjectURL(url);
  8463. };
  8464. img.src = url;
  8465. newWindow.document.body.appendChild(img);
  8466. }
  8467. });
  8468. }
  8469. };
  8470. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8471. if (mimeType === void 0) { mimeType = "image/png"; }
  8472. var width;
  8473. var height;
  8474. // If a precision value is specified
  8475. if (size.precision) {
  8476. width = Math.round(engine.getRenderWidth() * size.precision);
  8477. height = Math.round(width / engine.getAspectRatio(camera));
  8478. }
  8479. else if (size.width && size.height) {
  8480. width = size.width;
  8481. height = size.height;
  8482. }
  8483. else if (size.width && !size.height) {
  8484. width = size.width;
  8485. height = Math.round(width / engine.getAspectRatio(camera));
  8486. }
  8487. else if (size.height && !size.width) {
  8488. height = size.height;
  8489. width = Math.round(height * engine.getAspectRatio(camera));
  8490. }
  8491. else if (!isNaN(size)) {
  8492. height = size;
  8493. width = size;
  8494. }
  8495. else {
  8496. Tools.Error("Invalid 'size' parameter !");
  8497. return;
  8498. }
  8499. if (!screenshotCanvas) {
  8500. screenshotCanvas = document.createElement('canvas');
  8501. }
  8502. screenshotCanvas.width = width;
  8503. screenshotCanvas.height = height;
  8504. var renderContext = screenshotCanvas.getContext("2d");
  8505. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8506. var newWidth = width;
  8507. var newHeight = newWidth / ratio;
  8508. if (newHeight > height) {
  8509. newHeight = height;
  8510. newWidth = newHeight * ratio;
  8511. }
  8512. var offsetX = Math.max(0, width - newWidth) / 2;
  8513. var offsetY = Math.max(0, height - newHeight) / 2;
  8514. var renderingCanvas = engine.getRenderingCanvas();
  8515. if (renderContext && renderingCanvas) {
  8516. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8517. }
  8518. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8519. };
  8520. /**
  8521. * Generates an image screenshot from the specified camera.
  8522. *
  8523. * @param engine The engine to use for rendering
  8524. * @param camera The camera to use for rendering
  8525. * @param size This parameter can be set to a single number or to an object with the
  8526. * following (optional) properties: precision, width, height. If a single number is passed,
  8527. * it will be used for both width and height. If an object is passed, the screenshot size
  8528. * will be derived from the parameters. The precision property is a multiplier allowing
  8529. * rendering at a higher or lower resolution.
  8530. * @param successCallback The callback receives a single parameter which contains the
  8531. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8532. * src parameter of an <img> to display it.
  8533. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8534. * Check your browser for supported MIME types.
  8535. * @param samples Texture samples (default: 1)
  8536. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8537. * @param fileName A name for for the downloaded file.
  8538. * @constructor
  8539. */
  8540. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8541. if (mimeType === void 0) { mimeType = "image/png"; }
  8542. if (samples === void 0) { samples = 1; }
  8543. if (antialiasing === void 0) { antialiasing = false; }
  8544. var width;
  8545. var height;
  8546. //If a precision value is specified
  8547. if (size.precision) {
  8548. width = Math.round(engine.getRenderWidth() * size.precision);
  8549. height = Math.round(width / engine.getAspectRatio(camera));
  8550. size = { width: width, height: height };
  8551. }
  8552. else if (size.width && size.height) {
  8553. width = size.width;
  8554. height = size.height;
  8555. }
  8556. else if (size.width && !size.height) {
  8557. width = size.width;
  8558. height = Math.round(width / engine.getAspectRatio(camera));
  8559. size = { width: width, height: height };
  8560. }
  8561. else if (size.height && !size.width) {
  8562. height = size.height;
  8563. width = Math.round(height * engine.getAspectRatio(camera));
  8564. size = { width: width, height: height };
  8565. }
  8566. else if (!isNaN(size)) {
  8567. height = size;
  8568. width = size;
  8569. }
  8570. else {
  8571. Tools.Error("Invalid 'size' parameter !");
  8572. return;
  8573. }
  8574. var scene = camera.getScene();
  8575. var previousCamera = null;
  8576. if (scene.activeCamera !== camera) {
  8577. previousCamera = scene.activeCamera;
  8578. scene.activeCamera = camera;
  8579. }
  8580. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8581. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8582. texture.renderList = null;
  8583. texture.samples = samples;
  8584. if (antialiasing) {
  8585. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8586. }
  8587. texture.onAfterRenderObservable.add(function () {
  8588. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8589. });
  8590. scene.incrementRenderId();
  8591. scene.resetCachedMaterial();
  8592. texture.render(true);
  8593. texture.dispose();
  8594. if (previousCamera) {
  8595. scene.activeCamera = previousCamera;
  8596. }
  8597. camera.getProjectionMatrix(true); // Force cache refresh;
  8598. };
  8599. // XHR response validator for local file scenario
  8600. Tools.ValidateXHRData = function (xhr, dataType) {
  8601. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8602. if (dataType === void 0) { dataType = 7; }
  8603. try {
  8604. if (dataType & 1) {
  8605. if (xhr.responseText && xhr.responseText.length > 0) {
  8606. return true;
  8607. }
  8608. else if (dataType === 1) {
  8609. return false;
  8610. }
  8611. }
  8612. if (dataType & 2) {
  8613. // Check header width and height since there is no "TGA" magic number
  8614. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8615. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8616. return true;
  8617. }
  8618. else if (dataType === 2) {
  8619. return false;
  8620. }
  8621. }
  8622. if (dataType & 4) {
  8623. // Check for the "DDS" magic number
  8624. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8625. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8626. return true;
  8627. }
  8628. else {
  8629. return false;
  8630. }
  8631. }
  8632. }
  8633. catch (e) {
  8634. // Global protection
  8635. }
  8636. return false;
  8637. };
  8638. /**
  8639. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8640. * Be aware Math.random() could cause collisions, but:
  8641. * "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"
  8642. */
  8643. Tools.RandomId = function () {
  8644. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8645. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8646. return v.toString(16);
  8647. });
  8648. };
  8649. /**
  8650. * Test if the given uri is a base64 string.
  8651. * @param uri The uri to test
  8652. * @return True if the uri is a base64 string or false otherwise.
  8653. */
  8654. Tools.IsBase64 = function (uri) {
  8655. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8656. };
  8657. /**
  8658. * Decode the given base64 uri.
  8659. * @param uri The uri to decode
  8660. * @return The decoded base64 data.
  8661. */
  8662. Tools.DecodeBase64 = function (uri) {
  8663. var decodedString = atob(uri.split(",")[1]);
  8664. var bufferLength = decodedString.length;
  8665. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8666. for (var i = 0; i < bufferLength; i++) {
  8667. bufferView[i] = decodedString.charCodeAt(i);
  8668. }
  8669. return bufferView.buffer;
  8670. };
  8671. Object.defineProperty(Tools, "NoneLogLevel", {
  8672. get: function () {
  8673. return Tools._NoneLogLevel;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(Tools, "MessageLogLevel", {
  8679. get: function () {
  8680. return Tools._MessageLogLevel;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. Object.defineProperty(Tools, "WarningLogLevel", {
  8686. get: function () {
  8687. return Tools._WarningLogLevel;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Tools, "ErrorLogLevel", {
  8693. get: function () {
  8694. return Tools._ErrorLogLevel;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Tools, "AllLogLevel", {
  8700. get: function () {
  8701. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Tools._AddLogEntry = function (entry) {
  8707. Tools._LogCache = entry + Tools._LogCache;
  8708. if (Tools.OnNewCacheEntry) {
  8709. Tools.OnNewCacheEntry(entry);
  8710. }
  8711. };
  8712. Tools._FormatMessage = function (message) {
  8713. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8714. var date = new Date();
  8715. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8716. };
  8717. Tools._LogDisabled = function (message) {
  8718. // nothing to do
  8719. };
  8720. Tools._LogEnabled = function (message) {
  8721. var formattedMessage = Tools._FormatMessage(message);
  8722. console.log("BJS - " + formattedMessage);
  8723. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8724. Tools._AddLogEntry(entry);
  8725. };
  8726. Tools._WarnDisabled = function (message) {
  8727. // nothing to do
  8728. };
  8729. Tools._WarnEnabled = function (message) {
  8730. var formattedMessage = Tools._FormatMessage(message);
  8731. console.warn("BJS - " + formattedMessage);
  8732. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8733. Tools._AddLogEntry(entry);
  8734. };
  8735. Tools._ErrorDisabled = function (message) {
  8736. // nothing to do
  8737. };
  8738. Tools._ErrorEnabled = function (message) {
  8739. Tools.errorsCount++;
  8740. var formattedMessage = Tools._FormatMessage(message);
  8741. console.error("BJS - " + formattedMessage);
  8742. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8743. Tools._AddLogEntry(entry);
  8744. };
  8745. Object.defineProperty(Tools, "LogCache", {
  8746. get: function () {
  8747. return Tools._LogCache;
  8748. },
  8749. enumerable: true,
  8750. configurable: true
  8751. });
  8752. Tools.ClearLogCache = function () {
  8753. Tools._LogCache = "";
  8754. Tools.errorsCount = 0;
  8755. };
  8756. Object.defineProperty(Tools, "LogLevels", {
  8757. set: function (level) {
  8758. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8759. Tools.Log = Tools._LogEnabled;
  8760. }
  8761. else {
  8762. Tools.Log = Tools._LogDisabled;
  8763. }
  8764. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8765. Tools.Warn = Tools._WarnEnabled;
  8766. }
  8767. else {
  8768. Tools.Warn = Tools._WarnDisabled;
  8769. }
  8770. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8771. Tools.Error = Tools._ErrorEnabled;
  8772. }
  8773. else {
  8774. Tools.Error = Tools._ErrorDisabled;
  8775. }
  8776. },
  8777. enumerable: true,
  8778. configurable: true
  8779. });
  8780. Tools.IsWindowObjectExist = function () {
  8781. return (typeof window) !== "undefined";
  8782. };
  8783. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8784. get: function () {
  8785. return Tools._PerformanceNoneLogLevel;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8791. get: function () {
  8792. return Tools._PerformanceUserMarkLogLevel;
  8793. },
  8794. enumerable: true,
  8795. configurable: true
  8796. });
  8797. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8798. get: function () {
  8799. return Tools._PerformanceConsoleLogLevel;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8805. set: function (level) {
  8806. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8807. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8808. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8809. return;
  8810. }
  8811. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8812. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8813. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8814. return;
  8815. }
  8816. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8817. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8823. };
  8824. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8825. };
  8826. Tools._StartUserMark = function (counterName, condition) {
  8827. if (condition === void 0) { condition = true; }
  8828. if (!Tools._performance) {
  8829. if (!Tools.IsWindowObjectExist()) {
  8830. return;
  8831. }
  8832. Tools._performance = window.performance;
  8833. }
  8834. if (!condition || !Tools._performance.mark) {
  8835. return;
  8836. }
  8837. Tools._performance.mark(counterName + "-Begin");
  8838. };
  8839. Tools._EndUserMark = function (counterName, condition) {
  8840. if (condition === void 0) { condition = true; }
  8841. if (!condition || !Tools._performance.mark) {
  8842. return;
  8843. }
  8844. Tools._performance.mark(counterName + "-End");
  8845. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8846. };
  8847. Tools._StartPerformanceConsole = function (counterName, condition) {
  8848. if (condition === void 0) { condition = true; }
  8849. if (!condition) {
  8850. return;
  8851. }
  8852. Tools._StartUserMark(counterName, condition);
  8853. if (console.time) {
  8854. console.time(counterName);
  8855. }
  8856. };
  8857. Tools._EndPerformanceConsole = function (counterName, condition) {
  8858. if (condition === void 0) { condition = true; }
  8859. if (!condition) {
  8860. return;
  8861. }
  8862. Tools._EndUserMark(counterName, condition);
  8863. if (console.time) {
  8864. console.timeEnd(counterName);
  8865. }
  8866. };
  8867. Object.defineProperty(Tools, "Now", {
  8868. get: function () {
  8869. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8870. return window.performance.now();
  8871. }
  8872. return new Date().getTime();
  8873. },
  8874. enumerable: true,
  8875. configurable: true
  8876. });
  8877. /**
  8878. * This method will return the name of the class used to create the instance of the given object.
  8879. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8880. * @param object the object to get the class name from
  8881. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8882. */
  8883. Tools.GetClassName = function (object, isType) {
  8884. if (isType === void 0) { isType = false; }
  8885. var name = null;
  8886. if (!isType && object.getClassName) {
  8887. name = object.getClassName();
  8888. }
  8889. else {
  8890. if (object instanceof Object) {
  8891. var classObj = isType ? object : Object.getPrototypeOf(object);
  8892. name = classObj.constructor["__bjsclassName__"];
  8893. }
  8894. if (!name) {
  8895. name = typeof object;
  8896. }
  8897. }
  8898. return name;
  8899. };
  8900. Tools.First = function (array, predicate) {
  8901. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8902. var el = array_1[_i];
  8903. if (predicate(el)) {
  8904. return el;
  8905. }
  8906. }
  8907. return null;
  8908. };
  8909. /**
  8910. * This method will return the name of the full name of the class, including its owning module (if any).
  8911. * 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).
  8912. * @param object the object to get the class name from
  8913. * @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.
  8914. */
  8915. Tools.getFullClassName = function (object, isType) {
  8916. if (isType === void 0) { isType = false; }
  8917. var className = null;
  8918. var moduleName = null;
  8919. if (!isType && object.getClassName) {
  8920. className = object.getClassName();
  8921. }
  8922. else {
  8923. if (object instanceof Object) {
  8924. var classObj = isType ? object : Object.getPrototypeOf(object);
  8925. className = classObj.constructor["__bjsclassName__"];
  8926. moduleName = classObj.constructor["__bjsmoduleName__"];
  8927. }
  8928. if (!className) {
  8929. className = typeof object;
  8930. }
  8931. }
  8932. if (!className) {
  8933. return null;
  8934. }
  8935. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8936. };
  8937. /**
  8938. * 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.
  8939. * @param array
  8940. */
  8941. Tools.arrayOrStringFeeder = function (array) {
  8942. return function (index) {
  8943. if (index >= array.length) {
  8944. return null;
  8945. }
  8946. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8947. if (val && val.getHashCode) {
  8948. val = val.getHashCode();
  8949. }
  8950. if (typeof val === "string") {
  8951. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8952. }
  8953. return val;
  8954. };
  8955. };
  8956. /**
  8957. * Compute the hashCode of a stream of number
  8958. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8959. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8960. * @return the hash code computed
  8961. */
  8962. Tools.hashCodeFromStream = function (feeder) {
  8963. // Based from here: http://stackoverflow.com/a/7616484/802124
  8964. var hash = 0;
  8965. var index = 0;
  8966. var chr = feeder(index++);
  8967. while (chr != null) {
  8968. hash = ((hash << 5) - hash) + chr;
  8969. hash |= 0; // Convert to 32bit integer
  8970. chr = feeder(index++);
  8971. }
  8972. return hash;
  8973. };
  8974. /**
  8975. * Returns a promise that resolves after the given amount of time.
  8976. * @param delay Number of milliseconds to delay
  8977. * @returns Promise that resolves after the given amount of time
  8978. */
  8979. Tools.DelayAsync = function (delay) {
  8980. return new Promise(function (resolve) {
  8981. setTimeout(function () {
  8982. resolve();
  8983. }, delay);
  8984. });
  8985. };
  8986. Tools.BaseUrl = "";
  8987. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8988. /**
  8989. * Default behaviour for cors in the application.
  8990. * It can be a string if the expected behavior is identical in the entire app.
  8991. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8992. */
  8993. Tools.CorsBehavior = "anonymous";
  8994. Tools.UseFallbackTexture = true;
  8995. /**
  8996. * Use this object to register external classes like custom textures or material
  8997. * to allow the laoders to instantiate them
  8998. */
  8999. Tools.RegisteredExternalClasses = {};
  9000. // Used in case of a texture loading problem
  9001. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9002. Tools.PreprocessUrl = function (url) {
  9003. return url;
  9004. };
  9005. // Logs
  9006. Tools._NoneLogLevel = 0;
  9007. Tools._MessageLogLevel = 1;
  9008. Tools._WarningLogLevel = 2;
  9009. Tools._ErrorLogLevel = 4;
  9010. Tools._LogCache = "";
  9011. Tools.errorsCount = 0;
  9012. Tools.Log = Tools._LogEnabled;
  9013. Tools.Warn = Tools._WarnEnabled;
  9014. Tools.Error = Tools._ErrorEnabled;
  9015. // Performances
  9016. Tools._PerformanceNoneLogLevel = 0;
  9017. Tools._PerformanceUserMarkLogLevel = 1;
  9018. Tools._PerformanceConsoleLogLevel = 2;
  9019. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9020. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9021. return Tools;
  9022. }());
  9023. BABYLON.Tools = Tools;
  9024. /**
  9025. * This class is used to track a performance counter which is number based.
  9026. * The user has access to many properties which give statistics of different nature
  9027. *
  9028. * The implementer can track two kinds of Performance Counter: time and count
  9029. * 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.
  9030. * 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.
  9031. */
  9032. var PerfCounter = /** @class */ (function () {
  9033. function PerfCounter() {
  9034. this._startMonitoringTime = 0;
  9035. this._min = 0;
  9036. this._max = 0;
  9037. this._average = 0;
  9038. this._lastSecAverage = 0;
  9039. this._current = 0;
  9040. this._totalValueCount = 0;
  9041. this._totalAccumulated = 0;
  9042. this._lastSecAccumulated = 0;
  9043. this._lastSecTime = 0;
  9044. this._lastSecValueCount = 0;
  9045. }
  9046. Object.defineProperty(PerfCounter.prototype, "min", {
  9047. /**
  9048. * Returns the smallest value ever
  9049. */
  9050. get: function () {
  9051. return this._min;
  9052. },
  9053. enumerable: true,
  9054. configurable: true
  9055. });
  9056. Object.defineProperty(PerfCounter.prototype, "max", {
  9057. /**
  9058. * Returns the biggest value ever
  9059. */
  9060. get: function () {
  9061. return this._max;
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. Object.defineProperty(PerfCounter.prototype, "average", {
  9067. /**
  9068. * Returns the average value since the performance counter is running
  9069. */
  9070. get: function () {
  9071. return this._average;
  9072. },
  9073. enumerable: true,
  9074. configurable: true
  9075. });
  9076. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9077. /**
  9078. * Returns the average value of the last second the counter was monitored
  9079. */
  9080. get: function () {
  9081. return this._lastSecAverage;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(PerfCounter.prototype, "current", {
  9087. /**
  9088. * Returns the current value
  9089. */
  9090. get: function () {
  9091. return this._current;
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(PerfCounter.prototype, "total", {
  9097. get: function () {
  9098. return this._totalAccumulated;
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. Object.defineProperty(PerfCounter.prototype, "count", {
  9104. get: function () {
  9105. return this._totalValueCount;
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. /**
  9111. * Call this method to start monitoring a new frame.
  9112. * 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.
  9113. */
  9114. PerfCounter.prototype.fetchNewFrame = function () {
  9115. this._totalValueCount++;
  9116. this._current = 0;
  9117. this._lastSecValueCount++;
  9118. };
  9119. /**
  9120. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9121. * @param newCount the count value to add to the monitored count
  9122. * @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.
  9123. */
  9124. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9125. if (!PerfCounter.Enabled) {
  9126. return;
  9127. }
  9128. this._current += newCount;
  9129. if (fetchResult) {
  9130. this._fetchResult();
  9131. }
  9132. };
  9133. /**
  9134. * Start monitoring this performance counter
  9135. */
  9136. PerfCounter.prototype.beginMonitoring = function () {
  9137. if (!PerfCounter.Enabled) {
  9138. return;
  9139. }
  9140. this._startMonitoringTime = Tools.Now;
  9141. };
  9142. /**
  9143. * Compute the time lapsed since the previous beginMonitoring() call.
  9144. * @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
  9145. */
  9146. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9147. if (newFrame === void 0) { newFrame = true; }
  9148. if (!PerfCounter.Enabled) {
  9149. return;
  9150. }
  9151. if (newFrame) {
  9152. this.fetchNewFrame();
  9153. }
  9154. var currentTime = Tools.Now;
  9155. this._current = currentTime - this._startMonitoringTime;
  9156. if (newFrame) {
  9157. this._fetchResult();
  9158. }
  9159. };
  9160. PerfCounter.prototype._fetchResult = function () {
  9161. this._totalAccumulated += this._current;
  9162. this._lastSecAccumulated += this._current;
  9163. // Min/Max update
  9164. this._min = Math.min(this._min, this._current);
  9165. this._max = Math.max(this._max, this._current);
  9166. this._average = this._totalAccumulated / this._totalValueCount;
  9167. // Reset last sec?
  9168. var now = Tools.Now;
  9169. if ((now - this._lastSecTime) > 1000) {
  9170. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9171. this._lastSecTime = now;
  9172. this._lastSecAccumulated = 0;
  9173. this._lastSecValueCount = 0;
  9174. }
  9175. };
  9176. PerfCounter.Enabled = true;
  9177. return PerfCounter;
  9178. }());
  9179. BABYLON.PerfCounter = PerfCounter;
  9180. /**
  9181. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9182. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9183. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9184. * @param name The name of the class, case should be preserved
  9185. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9186. */
  9187. function className(name, module) {
  9188. return function (target) {
  9189. target["__bjsclassName__"] = name;
  9190. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9191. };
  9192. }
  9193. BABYLON.className = className;
  9194. /**
  9195. * An implementation of a loop for asynchronous functions.
  9196. */
  9197. var AsyncLoop = /** @class */ (function () {
  9198. /**
  9199. * Constroctor.
  9200. * @param iterations the number of iterations.
  9201. * @param _fn the function to run each iteration
  9202. * @param _successCallback the callback that will be called upon succesful execution
  9203. * @param offset starting offset.
  9204. */
  9205. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9206. if (offset === void 0) { offset = 0; }
  9207. this.iterations = iterations;
  9208. this._fn = _fn;
  9209. this._successCallback = _successCallback;
  9210. this.index = offset - 1;
  9211. this._done = false;
  9212. }
  9213. /**
  9214. * Execute the next iteration. Must be called after the last iteration was finished.
  9215. */
  9216. AsyncLoop.prototype.executeNext = function () {
  9217. if (!this._done) {
  9218. if (this.index + 1 < this.iterations) {
  9219. ++this.index;
  9220. this._fn(this);
  9221. }
  9222. else {
  9223. this.breakLoop();
  9224. }
  9225. }
  9226. };
  9227. /**
  9228. * Break the loop and run the success callback.
  9229. */
  9230. AsyncLoop.prototype.breakLoop = function () {
  9231. this._done = true;
  9232. this._successCallback();
  9233. };
  9234. /**
  9235. * Helper function
  9236. */
  9237. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9238. if (offset === void 0) { offset = 0; }
  9239. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9240. loop.executeNext();
  9241. return loop;
  9242. };
  9243. /**
  9244. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9245. * @param iterations total number of iterations
  9246. * @param syncedIterations number of synchronous iterations in each async iteration.
  9247. * @param fn the function to call each iteration.
  9248. * @param callback a success call back that will be called when iterating stops.
  9249. * @param breakFunction a break condition (optional)
  9250. * @param timeout timeout settings for the setTimeout function. default - 0.
  9251. * @constructor
  9252. */
  9253. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9254. if (timeout === void 0) { timeout = 0; }
  9255. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9256. if (breakFunction && breakFunction())
  9257. loop.breakLoop();
  9258. else {
  9259. setTimeout(function () {
  9260. for (var i = 0; i < syncedIterations; ++i) {
  9261. var iteration = (loop.index * syncedIterations) + i;
  9262. if (iteration >= iterations)
  9263. break;
  9264. fn(iteration);
  9265. if (breakFunction && breakFunction()) {
  9266. loop.breakLoop();
  9267. break;
  9268. }
  9269. }
  9270. loop.executeNext();
  9271. }, timeout);
  9272. }
  9273. }, callback);
  9274. };
  9275. return AsyncLoop;
  9276. }());
  9277. BABYLON.AsyncLoop = AsyncLoop;
  9278. })(BABYLON || (BABYLON = {}));
  9279. //# sourceMappingURL=babylon.tools.js.map
  9280. var BABYLON;
  9281. (function (BABYLON) {
  9282. var PromiseStates;
  9283. (function (PromiseStates) {
  9284. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9285. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9286. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9287. })(PromiseStates || (PromiseStates = {}));
  9288. var FulFillmentAgregator = /** @class */ (function () {
  9289. function FulFillmentAgregator() {
  9290. this.count = 0;
  9291. this.target = 0;
  9292. this.results = [];
  9293. }
  9294. return FulFillmentAgregator;
  9295. }());
  9296. var InternalPromise = /** @class */ (function () {
  9297. function InternalPromise(resolver) {
  9298. var _this = this;
  9299. this._state = PromiseStates.Pending;
  9300. this._children = new Array();
  9301. this._rejectWasConsumed = false;
  9302. if (!resolver) {
  9303. return;
  9304. }
  9305. try {
  9306. resolver(function (value) {
  9307. _this._resolve(value);
  9308. }, function (reason) {
  9309. _this._reject(reason);
  9310. });
  9311. }
  9312. catch (e) {
  9313. this._reject(e);
  9314. }
  9315. }
  9316. InternalPromise.prototype.catch = function (onRejected) {
  9317. return this.then(undefined, onRejected);
  9318. };
  9319. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9320. var _this = this;
  9321. var newPromise = new InternalPromise();
  9322. newPromise._onFulfilled = onFulfilled;
  9323. newPromise._onRejected = onRejected;
  9324. // Composition
  9325. this._children.push(newPromise);
  9326. if (this._state !== PromiseStates.Pending) {
  9327. BABYLON.Tools.SetImmediate(function () {
  9328. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9329. var returnedValue = newPromise._resolve(_this._result);
  9330. if (returnedValue !== undefined && returnedValue !== null) {
  9331. if (returnedValue._state !== undefined) {
  9332. var returnedPromise = returnedValue;
  9333. newPromise._children.push(returnedPromise);
  9334. newPromise = returnedPromise;
  9335. }
  9336. else {
  9337. newPromise._result = returnedValue;
  9338. }
  9339. }
  9340. }
  9341. else {
  9342. newPromise._reject(_this._reason);
  9343. }
  9344. });
  9345. }
  9346. return newPromise;
  9347. };
  9348. InternalPromise.prototype._moveChildren = function (children) {
  9349. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9350. if (this._state === PromiseStates.Fulfilled) {
  9351. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9352. var child = _b[_i];
  9353. child._resolve(this._result);
  9354. }
  9355. }
  9356. else if (this._state === PromiseStates.Rejected) {
  9357. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9358. var child = _d[_c];
  9359. child._reject(this._reason);
  9360. }
  9361. }
  9362. var _a;
  9363. };
  9364. InternalPromise.prototype._resolve = function (value) {
  9365. try {
  9366. this._state = PromiseStates.Fulfilled;
  9367. this._result = value;
  9368. var returnedValue = null;
  9369. if (this._onFulfilled) {
  9370. returnedValue = this._onFulfilled(value);
  9371. }
  9372. if (returnedValue !== undefined && returnedValue !== null) {
  9373. if (returnedValue._state !== undefined) {
  9374. // Transmit children
  9375. var returnedPromise = returnedValue;
  9376. returnedPromise._moveChildren(this._children);
  9377. }
  9378. else {
  9379. value = returnedValue;
  9380. }
  9381. }
  9382. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9383. var child = _a[_i];
  9384. child._resolve(value);
  9385. }
  9386. this._children.length = 0;
  9387. delete this._onFulfilled;
  9388. delete this._onRejected;
  9389. return returnedValue;
  9390. }
  9391. catch (e) {
  9392. this._reject(e, true);
  9393. }
  9394. return null;
  9395. };
  9396. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9397. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9398. this._state = PromiseStates.Rejected;
  9399. this._reason = reason;
  9400. if (this._onRejected && !onLocalThrow) {
  9401. try {
  9402. this._onRejected(reason);
  9403. this._rejectWasConsumed = true;
  9404. }
  9405. catch (e) {
  9406. reason = e;
  9407. }
  9408. }
  9409. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9410. var child = _a[_i];
  9411. if (this._rejectWasConsumed) {
  9412. child._resolve(null);
  9413. }
  9414. else {
  9415. child._reject(reason);
  9416. }
  9417. }
  9418. this._children.length = 0;
  9419. delete this._onFulfilled;
  9420. delete this._onRejected;
  9421. };
  9422. InternalPromise.resolve = function (value) {
  9423. var newPromise = new InternalPromise();
  9424. newPromise._resolve(value);
  9425. return newPromise;
  9426. };
  9427. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9428. promise.then(function (value) {
  9429. agregator.results[index] = value;
  9430. agregator.count++;
  9431. if (agregator.count === agregator.target) {
  9432. agregator.rootPromise._resolve(agregator.results);
  9433. }
  9434. return null;
  9435. }, function (reason) {
  9436. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9437. agregator.rootPromise._reject(reason);
  9438. }
  9439. });
  9440. };
  9441. InternalPromise.all = function (promises) {
  9442. var newPromise = new InternalPromise();
  9443. var agregator = new FulFillmentAgregator();
  9444. agregator.target = promises.length;
  9445. agregator.rootPromise = newPromise;
  9446. if (promises.length) {
  9447. for (var index = 0; index < promises.length; index++) {
  9448. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9449. }
  9450. }
  9451. else {
  9452. newPromise._resolve([]);
  9453. }
  9454. return newPromise;
  9455. };
  9456. InternalPromise.race = function (promises) {
  9457. var newPromise = new InternalPromise();
  9458. if (promises.length) {
  9459. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9460. var promise = promises_1[_i];
  9461. promise.then(function (value) {
  9462. if (newPromise) {
  9463. newPromise._resolve(value);
  9464. newPromise = null;
  9465. }
  9466. return null;
  9467. }, function (reason) {
  9468. if (newPromise) {
  9469. newPromise._reject(reason);
  9470. newPromise = null;
  9471. }
  9472. });
  9473. }
  9474. }
  9475. return newPromise;
  9476. };
  9477. return InternalPromise;
  9478. }());
  9479. /**
  9480. * Helper class that provides a small promise polyfill
  9481. */
  9482. var PromisePolyfill = /** @class */ (function () {
  9483. function PromisePolyfill() {
  9484. }
  9485. /**
  9486. * Static function used to check if the polyfill is required
  9487. * If this is the case then the function will inject the polyfill to window.Promise
  9488. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9489. */
  9490. PromisePolyfill.Apply = function (force) {
  9491. if (force === void 0) { force = false; }
  9492. if (force || typeof Promise === 'undefined') {
  9493. var root = window;
  9494. root.Promise = InternalPromise;
  9495. }
  9496. };
  9497. return PromisePolyfill;
  9498. }());
  9499. BABYLON.PromisePolyfill = PromisePolyfill;
  9500. })(BABYLON || (BABYLON = {}));
  9501. //# sourceMappingURL=babylon.promise.js.map
  9502. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9503. var BABYLON;
  9504. (function (BABYLON) {
  9505. /**
  9506. * Helper class to push actions to a pool of workers.
  9507. */
  9508. var WorkerPool = /** @class */ (function () {
  9509. /**
  9510. * Constructor
  9511. * @param workers Array of workers to use for actions
  9512. */
  9513. function WorkerPool(workers) {
  9514. this._pendingActions = new Array();
  9515. this._workerInfos = workers.map(function (worker) { return ({
  9516. worker: worker,
  9517. active: false
  9518. }); });
  9519. }
  9520. /**
  9521. * Terminates all workers and clears any pending actions.
  9522. */
  9523. WorkerPool.prototype.dispose = function () {
  9524. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9525. var workerInfo = _a[_i];
  9526. workerInfo.worker.terminate();
  9527. }
  9528. delete this._workerInfos;
  9529. delete this._pendingActions;
  9530. };
  9531. /**
  9532. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9533. * pended until a worker has completed its action.
  9534. * @param action The action to perform. Call onComplete when the action is complete.
  9535. */
  9536. WorkerPool.prototype.push = function (action) {
  9537. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9538. var workerInfo = _a[_i];
  9539. if (!workerInfo.active) {
  9540. this._execute(workerInfo, action);
  9541. return;
  9542. }
  9543. }
  9544. this._pendingActions.push(action);
  9545. };
  9546. WorkerPool.prototype._execute = function (workerInfo, action) {
  9547. var _this = this;
  9548. workerInfo.active = true;
  9549. action(workerInfo.worker, function () {
  9550. workerInfo.active = false;
  9551. var nextAction = _this._pendingActions.shift();
  9552. if (nextAction) {
  9553. _this._execute(workerInfo, nextAction);
  9554. }
  9555. });
  9556. };
  9557. return WorkerPool;
  9558. }());
  9559. BABYLON.WorkerPool = WorkerPool;
  9560. })(BABYLON || (BABYLON = {}));
  9561. //# sourceMappingURL=babylon.workerPool.js.map
  9562. var BABYLON;
  9563. (function (BABYLON) {
  9564. var _AlphaState = /** @class */ (function () {
  9565. /**
  9566. * Initializes the state.
  9567. */
  9568. function _AlphaState() {
  9569. this._isAlphaBlendDirty = false;
  9570. this._isBlendFunctionParametersDirty = false;
  9571. this._isBlendEquationParametersDirty = false;
  9572. this._isBlendConstantsDirty = false;
  9573. this._alphaBlend = false;
  9574. this._blendFunctionParameters = new Array(4);
  9575. this._blendEquationParameters = new Array(2);
  9576. this._blendConstants = new Array(4);
  9577. this.reset();
  9578. }
  9579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9580. get: function () {
  9581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9582. },
  9583. enumerable: true,
  9584. configurable: true
  9585. });
  9586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9587. get: function () {
  9588. return this._alphaBlend;
  9589. },
  9590. set: function (value) {
  9591. if (this._alphaBlend === value) {
  9592. return;
  9593. }
  9594. this._alphaBlend = value;
  9595. this._isAlphaBlendDirty = true;
  9596. },
  9597. enumerable: true,
  9598. configurable: true
  9599. });
  9600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9601. if (this._blendConstants[0] === r &&
  9602. this._blendConstants[1] === g &&
  9603. this._blendConstants[2] === b &&
  9604. this._blendConstants[3] === a) {
  9605. return;
  9606. }
  9607. this._blendConstants[0] = r;
  9608. this._blendConstants[1] = g;
  9609. this._blendConstants[2] = b;
  9610. this._blendConstants[3] = a;
  9611. this._isBlendConstantsDirty = true;
  9612. };
  9613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9614. if (this._blendFunctionParameters[0] === value0 &&
  9615. this._blendFunctionParameters[1] === value1 &&
  9616. this._blendFunctionParameters[2] === value2 &&
  9617. this._blendFunctionParameters[3] === value3) {
  9618. return;
  9619. }
  9620. this._blendFunctionParameters[0] = value0;
  9621. this._blendFunctionParameters[1] = value1;
  9622. this._blendFunctionParameters[2] = value2;
  9623. this._blendFunctionParameters[3] = value3;
  9624. this._isBlendFunctionParametersDirty = true;
  9625. };
  9626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9627. if (this._blendEquationParameters[0] === rgb &&
  9628. this._blendEquationParameters[1] === alpha) {
  9629. return;
  9630. }
  9631. this._blendEquationParameters[0] = rgb;
  9632. this._blendEquationParameters[1] = alpha;
  9633. this._isBlendEquationParametersDirty = true;
  9634. };
  9635. _AlphaState.prototype.reset = function () {
  9636. this._alphaBlend = false;
  9637. this._blendFunctionParameters[0] = null;
  9638. this._blendFunctionParameters[1] = null;
  9639. this._blendFunctionParameters[2] = null;
  9640. this._blendFunctionParameters[3] = null;
  9641. this._blendEquationParameters[0] = null;
  9642. this._blendEquationParameters[1] = null;
  9643. this._blendConstants[0] = null;
  9644. this._blendConstants[1] = null;
  9645. this._blendConstants[2] = null;
  9646. this._blendConstants[3] = null;
  9647. this._isAlphaBlendDirty = true;
  9648. this._isBlendFunctionParametersDirty = false;
  9649. this._isBlendEquationParametersDirty = false;
  9650. this._isBlendConstantsDirty = false;
  9651. };
  9652. _AlphaState.prototype.apply = function (gl) {
  9653. if (!this.isDirty) {
  9654. return;
  9655. }
  9656. // Alpha blend
  9657. if (this._isAlphaBlendDirty) {
  9658. if (this._alphaBlend) {
  9659. gl.enable(gl.BLEND);
  9660. }
  9661. else {
  9662. gl.disable(gl.BLEND);
  9663. }
  9664. this._isAlphaBlendDirty = false;
  9665. }
  9666. // Alpha function
  9667. if (this._isBlendFunctionParametersDirty) {
  9668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9669. this._isBlendFunctionParametersDirty = false;
  9670. }
  9671. // Alpha equation
  9672. if (this._isBlendEquationParametersDirty) {
  9673. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9674. this._isBlendEquationParametersDirty = false;
  9675. }
  9676. // Constants
  9677. if (this._isBlendConstantsDirty) {
  9678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9679. this._isBlendConstantsDirty = false;
  9680. }
  9681. };
  9682. return _AlphaState;
  9683. }());
  9684. BABYLON._AlphaState = _AlphaState;
  9685. })(BABYLON || (BABYLON = {}));
  9686. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9687. var BABYLON;
  9688. (function (BABYLON) {
  9689. var _DepthCullingState = /** @class */ (function () {
  9690. /**
  9691. * Initializes the state.
  9692. */
  9693. function _DepthCullingState() {
  9694. this._isDepthTestDirty = false;
  9695. this._isDepthMaskDirty = false;
  9696. this._isDepthFuncDirty = false;
  9697. this._isCullFaceDirty = false;
  9698. this._isCullDirty = false;
  9699. this._isZOffsetDirty = false;
  9700. this._isFrontFaceDirty = false;
  9701. this.reset();
  9702. }
  9703. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9704. get: function () {
  9705. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9706. },
  9707. enumerable: true,
  9708. configurable: true
  9709. });
  9710. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9711. get: function () {
  9712. return this._zOffset;
  9713. },
  9714. set: function (value) {
  9715. if (this._zOffset === value) {
  9716. return;
  9717. }
  9718. this._zOffset = value;
  9719. this._isZOffsetDirty = true;
  9720. },
  9721. enumerable: true,
  9722. configurable: true
  9723. });
  9724. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9725. get: function () {
  9726. return this._cullFace;
  9727. },
  9728. set: function (value) {
  9729. if (this._cullFace === value) {
  9730. return;
  9731. }
  9732. this._cullFace = value;
  9733. this._isCullFaceDirty = true;
  9734. },
  9735. enumerable: true,
  9736. configurable: true
  9737. });
  9738. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9739. get: function () {
  9740. return this._cull;
  9741. },
  9742. set: function (value) {
  9743. if (this._cull === value) {
  9744. return;
  9745. }
  9746. this._cull = value;
  9747. this._isCullDirty = true;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9753. get: function () {
  9754. return this._depthFunc;
  9755. },
  9756. set: function (value) {
  9757. if (this._depthFunc === value) {
  9758. return;
  9759. }
  9760. this._depthFunc = value;
  9761. this._isDepthFuncDirty = true;
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9767. get: function () {
  9768. return this._depthMask;
  9769. },
  9770. set: function (value) {
  9771. if (this._depthMask === value) {
  9772. return;
  9773. }
  9774. this._depthMask = value;
  9775. this._isDepthMaskDirty = true;
  9776. },
  9777. enumerable: true,
  9778. configurable: true
  9779. });
  9780. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9781. get: function () {
  9782. return this._depthTest;
  9783. },
  9784. set: function (value) {
  9785. if (this._depthTest === value) {
  9786. return;
  9787. }
  9788. this._depthTest = value;
  9789. this._isDepthTestDirty = true;
  9790. },
  9791. enumerable: true,
  9792. configurable: true
  9793. });
  9794. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9795. get: function () {
  9796. return this._frontFace;
  9797. },
  9798. set: function (value) {
  9799. if (this._frontFace === value) {
  9800. return;
  9801. }
  9802. this._frontFace = value;
  9803. this._isFrontFaceDirty = true;
  9804. },
  9805. enumerable: true,
  9806. configurable: true
  9807. });
  9808. _DepthCullingState.prototype.reset = function () {
  9809. this._depthMask = true;
  9810. this._depthTest = true;
  9811. this._depthFunc = null;
  9812. this._cullFace = null;
  9813. this._cull = null;
  9814. this._zOffset = 0;
  9815. this._frontFace = null;
  9816. this._isDepthTestDirty = true;
  9817. this._isDepthMaskDirty = true;
  9818. this._isDepthFuncDirty = false;
  9819. this._isCullFaceDirty = false;
  9820. this._isCullDirty = false;
  9821. this._isZOffsetDirty = false;
  9822. this._isFrontFaceDirty = false;
  9823. };
  9824. _DepthCullingState.prototype.apply = function (gl) {
  9825. if (!this.isDirty) {
  9826. return;
  9827. }
  9828. // Cull
  9829. if (this._isCullDirty) {
  9830. if (this.cull) {
  9831. gl.enable(gl.CULL_FACE);
  9832. }
  9833. else {
  9834. gl.disable(gl.CULL_FACE);
  9835. }
  9836. this._isCullDirty = false;
  9837. }
  9838. // Cull face
  9839. if (this._isCullFaceDirty) {
  9840. gl.cullFace(this.cullFace);
  9841. this._isCullFaceDirty = false;
  9842. }
  9843. // Depth mask
  9844. if (this._isDepthMaskDirty) {
  9845. gl.depthMask(this.depthMask);
  9846. this._isDepthMaskDirty = false;
  9847. }
  9848. // Depth test
  9849. if (this._isDepthTestDirty) {
  9850. if (this.depthTest) {
  9851. gl.enable(gl.DEPTH_TEST);
  9852. }
  9853. else {
  9854. gl.disable(gl.DEPTH_TEST);
  9855. }
  9856. this._isDepthTestDirty = false;
  9857. }
  9858. // Depth func
  9859. if (this._isDepthFuncDirty) {
  9860. gl.depthFunc(this.depthFunc);
  9861. this._isDepthFuncDirty = false;
  9862. }
  9863. // zOffset
  9864. if (this._isZOffsetDirty) {
  9865. if (this.zOffset) {
  9866. gl.enable(gl.POLYGON_OFFSET_FILL);
  9867. gl.polygonOffset(this.zOffset, 0);
  9868. }
  9869. else {
  9870. gl.disable(gl.POLYGON_OFFSET_FILL);
  9871. }
  9872. this._isZOffsetDirty = false;
  9873. }
  9874. // Front face
  9875. if (this._isFrontFaceDirty) {
  9876. gl.frontFace(this.frontFace);
  9877. this._isFrontFaceDirty = false;
  9878. }
  9879. };
  9880. return _DepthCullingState;
  9881. }());
  9882. BABYLON._DepthCullingState = _DepthCullingState;
  9883. })(BABYLON || (BABYLON = {}));
  9884. //# sourceMappingURL=babylon.depthCullingState.js.map
  9885. var BABYLON;
  9886. (function (BABYLON) {
  9887. var _StencilState = /** @class */ (function () {
  9888. function _StencilState() {
  9889. this._isStencilTestDirty = false;
  9890. this._isStencilMaskDirty = false;
  9891. this._isStencilFuncDirty = false;
  9892. this._isStencilOpDirty = false;
  9893. this.reset();
  9894. }
  9895. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9896. get: function () {
  9897. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9903. get: function () {
  9904. return this._stencilFunc;
  9905. },
  9906. set: function (value) {
  9907. if (this._stencilFunc === value) {
  9908. return;
  9909. }
  9910. this._stencilFunc = value;
  9911. this._isStencilFuncDirty = true;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9917. get: function () {
  9918. return this._stencilFuncRef;
  9919. },
  9920. set: function (value) {
  9921. if (this._stencilFuncRef === value) {
  9922. return;
  9923. }
  9924. this._stencilFuncRef = value;
  9925. this._isStencilFuncDirty = true;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9931. get: function () {
  9932. return this._stencilFuncMask;
  9933. },
  9934. set: function (value) {
  9935. if (this._stencilFuncMask === value) {
  9936. return;
  9937. }
  9938. this._stencilFuncMask = value;
  9939. this._isStencilFuncDirty = true;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9945. get: function () {
  9946. return this._stencilOpStencilFail;
  9947. },
  9948. set: function (value) {
  9949. if (this._stencilOpStencilFail === value) {
  9950. return;
  9951. }
  9952. this._stencilOpStencilFail = value;
  9953. this._isStencilOpDirty = true;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9959. get: function () {
  9960. return this._stencilOpDepthFail;
  9961. },
  9962. set: function (value) {
  9963. if (this._stencilOpDepthFail === value) {
  9964. return;
  9965. }
  9966. this._stencilOpDepthFail = value;
  9967. this._isStencilOpDirty = true;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9973. get: function () {
  9974. return this._stencilOpStencilDepthPass;
  9975. },
  9976. set: function (value) {
  9977. if (this._stencilOpStencilDepthPass === value) {
  9978. return;
  9979. }
  9980. this._stencilOpStencilDepthPass = value;
  9981. this._isStencilOpDirty = true;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9987. get: function () {
  9988. return this._stencilMask;
  9989. },
  9990. set: function (value) {
  9991. if (this._stencilMask === value) {
  9992. return;
  9993. }
  9994. this._stencilMask = value;
  9995. this._isStencilMaskDirty = true;
  9996. },
  9997. enumerable: true,
  9998. configurable: true
  9999. });
  10000. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10001. get: function () {
  10002. return this._stencilTest;
  10003. },
  10004. set: function (value) {
  10005. if (this._stencilTest === value) {
  10006. return;
  10007. }
  10008. this._stencilTest = value;
  10009. this._isStencilTestDirty = true;
  10010. },
  10011. enumerable: true,
  10012. configurable: true
  10013. });
  10014. _StencilState.prototype.reset = function () {
  10015. this._stencilTest = false;
  10016. this._stencilMask = 0xFF;
  10017. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10018. this._stencilFuncRef = 1;
  10019. this._stencilFuncMask = 0xFF;
  10020. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10021. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10022. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10023. this._isStencilTestDirty = true;
  10024. this._isStencilMaskDirty = true;
  10025. this._isStencilFuncDirty = true;
  10026. this._isStencilOpDirty = true;
  10027. };
  10028. _StencilState.prototype.apply = function (gl) {
  10029. if (!this.isDirty) {
  10030. return;
  10031. }
  10032. // Stencil test
  10033. if (this._isStencilTestDirty) {
  10034. if (this.stencilTest) {
  10035. gl.enable(gl.STENCIL_TEST);
  10036. }
  10037. else {
  10038. gl.disable(gl.STENCIL_TEST);
  10039. }
  10040. this._isStencilTestDirty = false;
  10041. }
  10042. // Stencil mask
  10043. if (this._isStencilMaskDirty) {
  10044. gl.stencilMask(this.stencilMask);
  10045. this._isStencilMaskDirty = false;
  10046. }
  10047. // Stencil func
  10048. if (this._isStencilFuncDirty) {
  10049. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10050. this._isStencilFuncDirty = false;
  10051. }
  10052. // Stencil op
  10053. if (this._isStencilOpDirty) {
  10054. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10055. this._isStencilOpDirty = false;
  10056. }
  10057. };
  10058. return _StencilState;
  10059. }());
  10060. BABYLON._StencilState = _StencilState;
  10061. })(BABYLON || (BABYLON = {}));
  10062. //# sourceMappingURL=babylon.stencilState.js.map
  10063. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10064. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10065. s = arguments[i];
  10066. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10067. t[p] = s[p];
  10068. }
  10069. return t;
  10070. };
  10071. var BABYLON;
  10072. (function (BABYLON) {
  10073. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10074. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10075. };
  10076. var compileRawShader = function (gl, source, type) {
  10077. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10078. gl.shaderSource(shader, source);
  10079. gl.compileShader(shader);
  10080. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10081. var log = gl.getShaderInfoLog(shader);
  10082. if (log) {
  10083. throw new Error(log);
  10084. }
  10085. }
  10086. if (!shader) {
  10087. throw new Error("Something went wrong while compile the shader.");
  10088. }
  10089. return shader;
  10090. };
  10091. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10092. var magFilter = gl.NEAREST;
  10093. var minFilter = gl.NEAREST;
  10094. switch (samplingMode) {
  10095. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10096. magFilter = gl.LINEAR;
  10097. if (generateMipMaps) {
  10098. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10099. }
  10100. else {
  10101. minFilter = gl.LINEAR;
  10102. }
  10103. break;
  10104. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10105. magFilter = gl.LINEAR;
  10106. if (generateMipMaps) {
  10107. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10108. }
  10109. else {
  10110. minFilter = gl.LINEAR;
  10111. }
  10112. break;
  10113. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10114. magFilter = gl.NEAREST;
  10115. if (generateMipMaps) {
  10116. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10117. }
  10118. else {
  10119. minFilter = gl.NEAREST;
  10120. }
  10121. break;
  10122. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10123. magFilter = gl.NEAREST;
  10124. if (generateMipMaps) {
  10125. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10126. }
  10127. else {
  10128. minFilter = gl.NEAREST;
  10129. }
  10130. break;
  10131. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10132. magFilter = gl.NEAREST;
  10133. if (generateMipMaps) {
  10134. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10135. }
  10136. else {
  10137. minFilter = gl.LINEAR;
  10138. }
  10139. break;
  10140. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10141. magFilter = gl.NEAREST;
  10142. if (generateMipMaps) {
  10143. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10144. }
  10145. else {
  10146. minFilter = gl.LINEAR;
  10147. }
  10148. break;
  10149. case BABYLON.Texture.NEAREST_LINEAR:
  10150. magFilter = gl.NEAREST;
  10151. minFilter = gl.LINEAR;
  10152. break;
  10153. case BABYLON.Texture.NEAREST_NEAREST:
  10154. magFilter = gl.NEAREST;
  10155. minFilter = gl.NEAREST;
  10156. break;
  10157. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10158. magFilter = gl.LINEAR;
  10159. if (generateMipMaps) {
  10160. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10161. }
  10162. else {
  10163. minFilter = gl.NEAREST;
  10164. }
  10165. break;
  10166. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10167. magFilter = gl.LINEAR;
  10168. if (generateMipMaps) {
  10169. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10170. }
  10171. else {
  10172. minFilter = gl.NEAREST;
  10173. }
  10174. break;
  10175. case BABYLON.Texture.LINEAR_LINEAR:
  10176. magFilter = gl.LINEAR;
  10177. minFilter = gl.LINEAR;
  10178. break;
  10179. case BABYLON.Texture.LINEAR_NEAREST:
  10180. magFilter = gl.LINEAR;
  10181. minFilter = gl.NEAREST;
  10182. break;
  10183. }
  10184. return {
  10185. min: minFilter,
  10186. mag: magFilter
  10187. };
  10188. };
  10189. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10190. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10191. var img;
  10192. var onload = function () {
  10193. loadedImages[index] = img;
  10194. loadedImages._internalCount++;
  10195. if (scene) {
  10196. scene._removePendingData(img);
  10197. }
  10198. if (loadedImages._internalCount === 6) {
  10199. onfinish(loadedImages);
  10200. }
  10201. };
  10202. var onerror = function (message, exception) {
  10203. if (scene) {
  10204. scene._removePendingData(img);
  10205. }
  10206. if (onErrorCallBack) {
  10207. onErrorCallBack(message, exception);
  10208. }
  10209. };
  10210. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10211. if (scene) {
  10212. scene._addPendingData(img);
  10213. }
  10214. };
  10215. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10216. if (onError === void 0) { onError = null; }
  10217. var loadedImages = [];
  10218. loadedImages._internalCount = 0;
  10219. for (var index = 0; index < 6; index++) {
  10220. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10221. }
  10222. };
  10223. var BufferPointer = /** @class */ (function () {
  10224. function BufferPointer() {
  10225. }
  10226. return BufferPointer;
  10227. }());
  10228. var InstancingAttributeInfo = /** @class */ (function () {
  10229. function InstancingAttributeInfo() {
  10230. }
  10231. return InstancingAttributeInfo;
  10232. }());
  10233. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10234. /**
  10235. * Define options used to create a render target texture
  10236. */
  10237. var RenderTargetCreationOptions = /** @class */ (function () {
  10238. function RenderTargetCreationOptions() {
  10239. }
  10240. return RenderTargetCreationOptions;
  10241. }());
  10242. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10243. /**
  10244. * Define options used to create a depth texture
  10245. */
  10246. var DepthTextureCreationOptions = /** @class */ (function () {
  10247. function DepthTextureCreationOptions() {
  10248. }
  10249. return DepthTextureCreationOptions;
  10250. }());
  10251. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10252. /**
  10253. * Regroup several parameters relative to the browser in use
  10254. */
  10255. var EngineCapabilities = /** @class */ (function () {
  10256. function EngineCapabilities() {
  10257. }
  10258. return EngineCapabilities;
  10259. }());
  10260. BABYLON.EngineCapabilities = EngineCapabilities;
  10261. /**
  10262. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10263. */
  10264. var Engine = /** @class */ (function () {
  10265. /**
  10266. * @constructor
  10267. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10268. * @param antialias defines enable antialiasing (default: false)
  10269. * @param options defines further options to be sent to the getContext() function
  10270. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10271. */
  10272. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10273. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10274. var _this = this;
  10275. // Public members
  10276. this.forcePOTTextures = false;
  10277. this.isFullscreen = false;
  10278. this.isPointerLock = false;
  10279. this.cullBackFaces = true;
  10280. this.renderEvenInBackground = true;
  10281. this.preventCacheWipeBetweenFrames = false;
  10282. // To enable/disable IDB support and avoid XHR on .manifest
  10283. this.enableOfflineSupport = false;
  10284. this.scenes = new Array();
  10285. this.postProcesses = new Array();
  10286. // Observables
  10287. /**
  10288. * Observable event triggered each time the rendering canvas is resized
  10289. */
  10290. this.onResizeObservable = new BABYLON.Observable();
  10291. /**
  10292. * Observable event triggered each time the canvas loses focus
  10293. */
  10294. this.onCanvasBlurObservable = new BABYLON.Observable();
  10295. /**
  10296. * Observable event triggered each time the canvas gains focus
  10297. */
  10298. this.onCanvasFocusObservable = new BABYLON.Observable();
  10299. /**
  10300. * Observable event triggered each time the canvas receives pointerout event
  10301. */
  10302. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10303. /**
  10304. * Observable event triggered before each texture is initialized
  10305. */
  10306. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10307. //WebVR
  10308. this._vrDisplay = undefined;
  10309. this._vrSupported = false;
  10310. this._vrExclusivePointerMode = false;
  10311. // Uniform buffers list
  10312. this.disableUniformBuffers = false;
  10313. this._uniformBuffers = new Array();
  10314. // Observables
  10315. /**
  10316. * Observable raised when the engine begins a new frame
  10317. */
  10318. this.onBeginFrameObservable = new BABYLON.Observable();
  10319. /**
  10320. * Observable raised when the engine ends the current frame
  10321. */
  10322. this.onEndFrameObservable = new BABYLON.Observable();
  10323. /**
  10324. * Observable raised when the engine is about to compile a shader
  10325. */
  10326. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10327. /**
  10328. * Observable raised when the engine has jsut compiled a shader
  10329. */
  10330. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10331. this._windowIsBackground = false;
  10332. this._webGLVersion = 1.0;
  10333. this._badOS = false;
  10334. this._badDesktopOS = false;
  10335. /**
  10336. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10337. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10338. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10339. */
  10340. this.disableTextureBindingOptimization = false;
  10341. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10342. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10343. this.onVRRequestPresentStart = new BABYLON.Observable();
  10344. this._colorWrite = true;
  10345. this._drawCalls = new BABYLON.PerfCounter();
  10346. this._textureCollisions = new BABYLON.PerfCounter();
  10347. this._renderingQueueLaunched = false;
  10348. this._activeRenderLoops = new Array();
  10349. // Deterministic lockstepMaxSteps
  10350. this._deterministicLockstep = false;
  10351. this._lockstepMaxSteps = 4;
  10352. // Lost context
  10353. this.onContextLostObservable = new BABYLON.Observable();
  10354. this.onContextRestoredObservable = new BABYLON.Observable();
  10355. this._contextWasLost = false;
  10356. this._doNotHandleContextLost = false;
  10357. // FPS
  10358. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10359. this._fps = 60;
  10360. this._deltaTime = 0;
  10361. /**
  10362. * Turn this value on if you want to pause FPS computation when in background
  10363. */
  10364. this.disablePerformanceMonitorInBackground = false;
  10365. // States
  10366. this._depthCullingState = new BABYLON._DepthCullingState();
  10367. this._stencilState = new BABYLON._StencilState();
  10368. this._alphaState = new BABYLON._AlphaState();
  10369. this._alphaMode = Engine.ALPHA_DISABLE;
  10370. // Cache
  10371. this._internalTexturesCache = new Array();
  10372. this._activeChannel = 0;
  10373. this._currentTextureChannel = -1;
  10374. this._boundTexturesCache = {};
  10375. this._compiledEffects = {};
  10376. this._vertexAttribArraysEnabled = [];
  10377. this._uintIndicesCurrentlySet = false;
  10378. this._currentBoundBuffer = new Array();
  10379. this._currentBufferPointers = new Array();
  10380. this._currentInstanceLocations = new Array();
  10381. this._currentInstanceBuffers = new Array();
  10382. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10383. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10384. this._vaoRecordInProgress = false;
  10385. this._mustWipeVertexAttributes = false;
  10386. this._nextFreeTextureSlots = new Array();
  10387. this._maxSimultaneousTextures = 0;
  10388. this._activeRequests = new Array();
  10389. // Hardware supported Compressed Textures
  10390. this._texturesSupported = new Array();
  10391. this._onVRFullScreenTriggered = function () {
  10392. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10393. //get the old size before we change
  10394. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10395. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10396. //get the width and height, change the render size
  10397. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10398. _this.setHardwareScalingLevel(1);
  10399. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10400. }
  10401. else {
  10402. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10403. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10404. }
  10405. };
  10406. this._boundUniforms = {};
  10407. // Register promises
  10408. BABYLON.PromisePolyfill.Apply();
  10409. var canvas = null;
  10410. Engine.Instances.push(this);
  10411. if (!canvasOrContext) {
  10412. return;
  10413. }
  10414. options = options || {};
  10415. if (canvasOrContext.getContext) {
  10416. canvas = canvasOrContext;
  10417. this._renderingCanvas = canvas;
  10418. if (antialias != null) {
  10419. options.antialias = antialias;
  10420. }
  10421. if (options.deterministicLockstep === undefined) {
  10422. options.deterministicLockstep = false;
  10423. }
  10424. if (options.lockstepMaxSteps === undefined) {
  10425. options.lockstepMaxSteps = 4;
  10426. }
  10427. if (options.preserveDrawingBuffer === undefined) {
  10428. options.preserveDrawingBuffer = false;
  10429. }
  10430. if (options.audioEngine === undefined) {
  10431. options.audioEngine = true;
  10432. }
  10433. if (options.stencil === undefined) {
  10434. options.stencil = true;
  10435. }
  10436. this._deterministicLockstep = options.deterministicLockstep;
  10437. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10438. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10439. // Exceptions
  10440. if (navigator && navigator.userAgent) {
  10441. var ua = navigator.userAgent;
  10442. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10443. var exception = _a[_i];
  10444. var key = exception.key;
  10445. var targets = exception.targets;
  10446. if (ua.indexOf(key) > -1) {
  10447. if (exception.capture && exception.captureConstraint) {
  10448. var capture = exception.capture;
  10449. var constraint = exception.captureConstraint;
  10450. var regex = new RegExp(capture);
  10451. var matches = regex.exec(ua);
  10452. if (matches && matches.length > 0) {
  10453. var capturedValue = parseInt(matches[matches.length - 1]);
  10454. if (capturedValue >= constraint) {
  10455. continue;
  10456. }
  10457. }
  10458. }
  10459. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10460. var target = targets_1[_b];
  10461. switch (target) {
  10462. case "uniformBuffer":
  10463. this.disableUniformBuffers = true;
  10464. break;
  10465. case "textureBindingOptimization":
  10466. this.disableTextureBindingOptimization = true;
  10467. break;
  10468. }
  10469. }
  10470. break;
  10471. }
  10472. }
  10473. }
  10474. // GL
  10475. if (!options.disableWebGL2Support) {
  10476. try {
  10477. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10478. if (this._gl) {
  10479. this._webGLVersion = 2.0;
  10480. }
  10481. }
  10482. catch (e) {
  10483. // Do nothing
  10484. }
  10485. }
  10486. if (!this._gl) {
  10487. if (!canvas) {
  10488. throw new Error("The provided canvas is null or undefined.");
  10489. }
  10490. try {
  10491. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10492. }
  10493. catch (e) {
  10494. throw new Error("WebGL not supported");
  10495. }
  10496. }
  10497. if (!this._gl) {
  10498. throw new Error("WebGL not supported");
  10499. }
  10500. this._onCanvasFocus = function () {
  10501. _this.onCanvasFocusObservable.notifyObservers(_this);
  10502. };
  10503. this._onCanvasBlur = function () {
  10504. _this.onCanvasBlurObservable.notifyObservers(_this);
  10505. };
  10506. canvas.addEventListener("focus", this._onCanvasFocus);
  10507. canvas.addEventListener("blur", this._onCanvasBlur);
  10508. this._onBlur = function () {
  10509. if (_this.disablePerformanceMonitorInBackground) {
  10510. _this._performanceMonitor.disable();
  10511. }
  10512. _this._windowIsBackground = true;
  10513. };
  10514. this._onFocus = function () {
  10515. if (_this.disablePerformanceMonitorInBackground) {
  10516. _this._performanceMonitor.enable();
  10517. }
  10518. _this._windowIsBackground = false;
  10519. };
  10520. this._onCanvasPointerOut = function (ev) {
  10521. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10522. };
  10523. window.addEventListener("blur", this._onBlur);
  10524. window.addEventListener("focus", this._onFocus);
  10525. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10526. // Context lost
  10527. if (!this._doNotHandleContextLost) {
  10528. this._onContextLost = function (evt) {
  10529. evt.preventDefault();
  10530. _this._contextWasLost = true;
  10531. BABYLON.Tools.Warn("WebGL context lost.");
  10532. _this.onContextLostObservable.notifyObservers(_this);
  10533. };
  10534. this._onContextRestored = function (evt) {
  10535. // Adding a timeout to avoid race condition at browser level
  10536. setTimeout(function () {
  10537. // Rebuild gl context
  10538. _this._initGLContext();
  10539. // Rebuild effects
  10540. _this._rebuildEffects();
  10541. // Rebuild textures
  10542. _this._rebuildInternalTextures();
  10543. // Rebuild buffers
  10544. _this._rebuildBuffers();
  10545. // Cache
  10546. _this.wipeCaches(true);
  10547. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10548. _this.onContextRestoredObservable.notifyObservers(_this);
  10549. _this._contextWasLost = false;
  10550. }, 0);
  10551. };
  10552. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10553. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10554. }
  10555. }
  10556. else {
  10557. this._gl = canvasOrContext;
  10558. this._renderingCanvas = this._gl.canvas;
  10559. if (this._gl.renderbufferStorageMultisample) {
  10560. this._webGLVersion = 2.0;
  10561. }
  10562. options.stencil = this._gl.getContextAttributes().stencil;
  10563. }
  10564. // Viewport
  10565. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10566. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10567. this.resize();
  10568. this._isStencilEnable = options.stencil ? true : false;
  10569. this._initGLContext();
  10570. if (canvas) {
  10571. // Fullscreen
  10572. this._onFullscreenChange = function () {
  10573. if (document.fullscreen !== undefined) {
  10574. _this.isFullscreen = document.fullscreen;
  10575. }
  10576. else if (document.mozFullScreen !== undefined) {
  10577. _this.isFullscreen = document.mozFullScreen;
  10578. }
  10579. else if (document.webkitIsFullScreen !== undefined) {
  10580. _this.isFullscreen = document.webkitIsFullScreen;
  10581. }
  10582. else if (document.msIsFullScreen !== undefined) {
  10583. _this.isFullscreen = document.msIsFullScreen;
  10584. }
  10585. // Pointer lock
  10586. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10587. canvas.requestPointerLock = canvas.requestPointerLock ||
  10588. canvas.msRequestPointerLock ||
  10589. canvas.mozRequestPointerLock ||
  10590. canvas.webkitRequestPointerLock;
  10591. if (canvas.requestPointerLock) {
  10592. canvas.requestPointerLock();
  10593. }
  10594. }
  10595. };
  10596. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10597. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10598. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10599. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10600. // Pointer lock
  10601. this._onPointerLockChange = function () {
  10602. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10603. document.webkitPointerLockElement === canvas ||
  10604. document.msPointerLockElement === canvas ||
  10605. document.pointerLockElement === canvas);
  10606. };
  10607. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10608. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10609. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10610. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10611. this._onVRDisplayPointerRestricted = function () {
  10612. if (canvas) {
  10613. canvas.requestPointerLock();
  10614. }
  10615. };
  10616. this._onVRDisplayPointerUnrestricted = function () {
  10617. document.exitPointerLock();
  10618. };
  10619. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10620. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10621. }
  10622. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10623. Engine.audioEngine = new BABYLON.AudioEngine();
  10624. }
  10625. // Prepare buffer pointers
  10626. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10627. this._currentBufferPointers[i] = new BufferPointer();
  10628. }
  10629. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10630. // Load WebVR Devices
  10631. if (options.autoEnableWebVR) {
  10632. this.initWebVR();
  10633. }
  10634. // Detect if we are running on a faulty buggy OS.
  10635. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10636. // Detect if we are running on a faulty buggy desktop OS.
  10637. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10638. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10639. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10640. }
  10641. Object.defineProperty(Engine, "LastCreatedEngine", {
  10642. get: function () {
  10643. if (Engine.Instances.length === 0) {
  10644. return null;
  10645. }
  10646. return Engine.Instances[Engine.Instances.length - 1];
  10647. },
  10648. enumerable: true,
  10649. configurable: true
  10650. });
  10651. Object.defineProperty(Engine, "LastCreatedScene", {
  10652. get: function () {
  10653. var lastCreatedEngine = Engine.LastCreatedEngine;
  10654. if (!lastCreatedEngine) {
  10655. return null;
  10656. }
  10657. if (lastCreatedEngine.scenes.length === 0) {
  10658. return null;
  10659. }
  10660. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10661. },
  10662. enumerable: true,
  10663. configurable: true
  10664. });
  10665. /**
  10666. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10667. */
  10668. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10669. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10670. var engine = Engine.Instances[engineIndex];
  10671. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10672. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10673. }
  10674. }
  10675. };
  10676. Object.defineProperty(Engine, "NEVER", {
  10677. get: function () {
  10678. return Engine._NEVER;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "ALWAYS", {
  10684. get: function () {
  10685. return Engine._ALWAYS;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "LESS", {
  10691. get: function () {
  10692. return Engine._LESS;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "EQUAL", {
  10698. get: function () {
  10699. return Engine._EQUAL;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "LEQUAL", {
  10705. get: function () {
  10706. return Engine._LEQUAL;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "GREATER", {
  10712. get: function () {
  10713. return Engine._GREATER;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "GEQUAL", {
  10719. get: function () {
  10720. return Engine._GEQUAL;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "NOTEQUAL", {
  10726. get: function () {
  10727. return Engine._NOTEQUAL;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "KEEP", {
  10733. get: function () {
  10734. return Engine._KEEP;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "REPLACE", {
  10740. get: function () {
  10741. return Engine._REPLACE;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "INCR", {
  10747. get: function () {
  10748. return Engine._INCR;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "DECR", {
  10754. get: function () {
  10755. return Engine._DECR;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "INVERT", {
  10761. get: function () {
  10762. return Engine._INVERT;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "INCR_WRAP", {
  10768. get: function () {
  10769. return Engine._INCR_WRAP;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "DECR_WRAP", {
  10775. get: function () {
  10776. return Engine._DECR_WRAP;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10782. get: function () {
  10783. return Engine._ALPHA_DISABLE;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10789. get: function () {
  10790. return Engine._ALPHA_ONEONE;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "ALPHA_ADD", {
  10796. get: function () {
  10797. return Engine._ALPHA_ADD;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10803. get: function () {
  10804. return Engine._ALPHA_COMBINE;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10810. get: function () {
  10811. return Engine._ALPHA_SUBTRACT;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10817. get: function () {
  10818. return Engine._ALPHA_MULTIPLY;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10824. get: function () {
  10825. return Engine._ALPHA_MAXIMIZED;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10831. get: function () {
  10832. return Engine._ALPHA_PREMULTIPLIED;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10838. get: function () {
  10839. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10845. get: function () {
  10846. return Engine._ALPHA_INTERPOLATE;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10852. get: function () {
  10853. return Engine._ALPHA_SCREENMODE;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10859. get: function () {
  10860. return Engine._DELAYLOADSTATE_NONE;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10866. get: function () {
  10867. return Engine._DELAYLOADSTATE_LOADED;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10873. get: function () {
  10874. return Engine._DELAYLOADSTATE_LOADING;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10880. get: function () {
  10881. return Engine._DELAYLOADSTATE_NOTLOADED;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10887. get: function () {
  10888. return Engine._TEXTUREFORMAT_ALPHA;
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10894. get: function () {
  10895. return Engine._TEXTUREFORMAT_LUMINANCE;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10901. /**
  10902. * R32F
  10903. */
  10904. get: function () {
  10905. return Engine._TEXTUREFORMAT_R32F;
  10906. },
  10907. enumerable: true,
  10908. configurable: true
  10909. });
  10910. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10911. /**
  10912. * RG32F
  10913. */
  10914. get: function () {
  10915. return Engine._TEXTUREFORMAT_RG32F;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10921. /**
  10922. * RGB32F
  10923. */
  10924. get: function () {
  10925. return Engine._TEXTUREFORMAT_RGB32F;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10931. /**
  10932. * RGBA32F
  10933. */
  10934. get: function () {
  10935. return Engine._TEXTUREFORMAT_RGBA32F;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10941. get: function () {
  10942. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10948. get: function () {
  10949. return Engine._TEXTUREFORMAT_RGB;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10955. get: function () {
  10956. return Engine._TEXTUREFORMAT_RGBA;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10962. get: function () {
  10963. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10969. get: function () {
  10970. return Engine._TEXTURETYPE_FLOAT;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10976. get: function () {
  10977. return Engine._TEXTURETYPE_HALF_FLOAT;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10983. get: function () {
  10984. return Engine._SCALEMODE_FLOOR;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10990. get: function () {
  10991. return Engine._SCALEMODE_NEAREST;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10997. get: function () {
  10998. return Engine._SCALEMODE_CEILING;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "Version", {
  11004. get: function () {
  11005. return "3.2.0-alphaB";
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11011. get: function () {
  11012. return this._vrExclusivePointerMode;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11018. get: function () {
  11019. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11025. get: function () {
  11026. return this._webGLVersion < 2 || this.forcePOTTextures;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine.prototype, "badOS", {
  11032. get: function () {
  11033. return this._badOS;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11039. get: function () {
  11040. return this._badDesktopOS;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11046. get: function () {
  11047. return this._performanceMonitor;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11053. get: function () {
  11054. return this._texturesSupported;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11060. get: function () {
  11061. return this._textureFormatInUse;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine.prototype, "currentViewport", {
  11067. get: function () {
  11068. return this._cachedViewport;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11074. // Empty texture
  11075. get: function () {
  11076. if (!this._emptyTexture) {
  11077. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11078. }
  11079. return this._emptyTexture;
  11080. },
  11081. enumerable: true,
  11082. configurable: true
  11083. });
  11084. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11085. get: function () {
  11086. if (!this._emptyTexture3D) {
  11087. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11088. }
  11089. return this._emptyTexture3D;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11095. get: function () {
  11096. if (!this._emptyCubeTexture) {
  11097. var faceData = new Uint8Array(4);
  11098. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11099. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11100. }
  11101. return this._emptyCubeTexture;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Engine.prototype._rebuildInternalTextures = function () {
  11107. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11108. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11109. var internalTexture = currentState_1[_i];
  11110. internalTexture._rebuild();
  11111. }
  11112. };
  11113. Engine.prototype._rebuildEffects = function () {
  11114. for (var key in this._compiledEffects) {
  11115. var effect = this._compiledEffects[key];
  11116. effect._prepareEffect();
  11117. }
  11118. BABYLON.Effect.ResetCache();
  11119. };
  11120. Engine.prototype._rebuildBuffers = function () {
  11121. // Index / Vertex
  11122. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11123. var scene = _a[_i];
  11124. scene.resetCachedMaterial();
  11125. scene._rebuildGeometries();
  11126. scene._rebuildTextures();
  11127. }
  11128. // Uniforms
  11129. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11130. var uniformBuffer = _c[_b];
  11131. uniformBuffer._rebuild();
  11132. }
  11133. };
  11134. Engine.prototype._initGLContext = function () {
  11135. // Caps
  11136. this._caps = new EngineCapabilities();
  11137. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11138. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11139. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11140. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11141. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11142. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11143. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11144. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11145. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11146. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11147. // Infos
  11148. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11149. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11150. if (rendererInfo != null) {
  11151. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11152. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11153. }
  11154. if (!this._glVendor) {
  11155. this._glVendor = "Unknown vendor";
  11156. }
  11157. if (!this._glRenderer) {
  11158. this._glRenderer = "Unknown renderer";
  11159. }
  11160. // Constants
  11161. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11162. if (this._gl.RGBA16F !== 0x881A) {
  11163. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11164. }
  11165. if (this._gl.RGBA32F !== 0x8814) {
  11166. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11167. }
  11168. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11169. this._gl.DEPTH24_STENCIL8 = 35056;
  11170. }
  11171. // Extensions
  11172. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11173. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11174. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11175. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11176. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11177. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11178. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11179. 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');
  11180. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11181. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11182. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11183. this._caps.highPrecisionShaderSupported = true;
  11184. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11185. if (this._caps.timerQuery) {
  11186. if (this._webGLVersion === 1) {
  11187. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11188. }
  11189. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11190. }
  11191. // Checks if some of the format renders first to allow the use of webgl inspector.
  11192. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11193. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11194. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11195. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11196. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11197. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11198. if (this._webGLVersion > 1) {
  11199. this._gl.HALF_FLOAT_OES = 0x140B;
  11200. }
  11201. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11202. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11203. // Draw buffers
  11204. if (this._webGLVersion > 1) {
  11205. this._caps.drawBuffersExtension = true;
  11206. }
  11207. else {
  11208. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11209. if (drawBuffersExtension !== null) {
  11210. this._caps.drawBuffersExtension = true;
  11211. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11212. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11213. for (var i = 0; i < 16; i++) {
  11214. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11215. }
  11216. }
  11217. else {
  11218. this._caps.drawBuffersExtension = false;
  11219. }
  11220. }
  11221. // Depth Texture
  11222. if (this._webGLVersion > 1) {
  11223. this._caps.depthTextureExtension = true;
  11224. }
  11225. else {
  11226. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11227. if (depthTextureExtension != null) {
  11228. this._caps.depthTextureExtension = true;
  11229. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11230. }
  11231. }
  11232. // Vertex array object
  11233. if (this._webGLVersion > 1) {
  11234. this._caps.vertexArrayObject = true;
  11235. }
  11236. else {
  11237. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11238. if (vertexArrayObjectExtension != null) {
  11239. this._caps.vertexArrayObject = true;
  11240. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11241. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11242. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11243. }
  11244. else {
  11245. this._caps.vertexArrayObject = false;
  11246. }
  11247. }
  11248. // Instances count
  11249. if (this._webGLVersion > 1) {
  11250. this._caps.instancedArrays = true;
  11251. }
  11252. else {
  11253. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11254. if (instanceExtension != null) {
  11255. this._caps.instancedArrays = true;
  11256. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11257. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11258. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11259. }
  11260. else {
  11261. this._caps.instancedArrays = false;
  11262. }
  11263. }
  11264. // Intelligently add supported compressed formats in order to check for.
  11265. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11266. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11267. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11268. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11269. if (this._caps.astc)
  11270. this.texturesSupported.push('-astc.ktx');
  11271. if (this._caps.s3tc)
  11272. this.texturesSupported.push('-dxt.ktx');
  11273. if (this._caps.pvrtc)
  11274. this.texturesSupported.push('-pvrtc.ktx');
  11275. if (this._caps.etc2)
  11276. this.texturesSupported.push('-etc2.ktx');
  11277. if (this._caps.etc1)
  11278. this.texturesSupported.push('-etc1.ktx');
  11279. if (this._gl.getShaderPrecisionFormat) {
  11280. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11281. if (highp) {
  11282. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11283. }
  11284. }
  11285. // Depth buffer
  11286. this.setDepthBuffer(true);
  11287. this.setDepthFunctionToLessOrEqual();
  11288. this.setDepthWrite(true);
  11289. // Texture maps
  11290. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11291. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11292. this._nextFreeTextureSlots.push(slot);
  11293. }
  11294. };
  11295. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11296. get: function () {
  11297. return this._webGLVersion;
  11298. },
  11299. enumerable: true,
  11300. configurable: true
  11301. });
  11302. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11303. /**
  11304. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11305. */
  11306. get: function () {
  11307. return this._isStencilEnable;
  11308. },
  11309. enumerable: true,
  11310. configurable: true
  11311. });
  11312. Engine.prototype._prepareWorkingCanvas = function () {
  11313. if (this._workingCanvas) {
  11314. return;
  11315. }
  11316. this._workingCanvas = document.createElement("canvas");
  11317. var context = this._workingCanvas.getContext("2d");
  11318. if (context) {
  11319. this._workingContext = context;
  11320. }
  11321. };
  11322. Engine.prototype.resetTextureCache = function () {
  11323. for (var key in this._boundTexturesCache) {
  11324. var boundTexture = this._boundTexturesCache[key];
  11325. if (boundTexture) {
  11326. this._removeDesignatedSlot(boundTexture);
  11327. }
  11328. this._boundTexturesCache[key] = null;
  11329. }
  11330. if (!this.disableTextureBindingOptimization) {
  11331. this._nextFreeTextureSlots = [];
  11332. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11333. this._nextFreeTextureSlots.push(slot);
  11334. }
  11335. }
  11336. this._currentTextureChannel = -1;
  11337. };
  11338. Engine.prototype.isDeterministicLockStep = function () {
  11339. return this._deterministicLockstep;
  11340. };
  11341. Engine.prototype.getLockstepMaxSteps = function () {
  11342. return this._lockstepMaxSteps;
  11343. };
  11344. Engine.prototype.getGlInfo = function () {
  11345. return {
  11346. vendor: this._glVendor,
  11347. renderer: this._glRenderer,
  11348. version: this._glVersion
  11349. };
  11350. };
  11351. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11352. if (useScreen === void 0) { useScreen = false; }
  11353. var viewport = camera.viewport;
  11354. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11355. };
  11356. Engine.prototype.getRenderWidth = function (useScreen) {
  11357. if (useScreen === void 0) { useScreen = false; }
  11358. if (!useScreen && this._currentRenderTarget) {
  11359. return this._currentRenderTarget.width;
  11360. }
  11361. return this._gl.drawingBufferWidth;
  11362. };
  11363. Engine.prototype.getRenderHeight = function (useScreen) {
  11364. if (useScreen === void 0) { useScreen = false; }
  11365. if (!useScreen && this._currentRenderTarget) {
  11366. return this._currentRenderTarget.height;
  11367. }
  11368. return this._gl.drawingBufferHeight;
  11369. };
  11370. Engine.prototype.getRenderingCanvas = function () {
  11371. return this._renderingCanvas;
  11372. };
  11373. Engine.prototype.getRenderingCanvasClientRect = function () {
  11374. if (!this._renderingCanvas) {
  11375. return null;
  11376. }
  11377. return this._renderingCanvas.getBoundingClientRect();
  11378. };
  11379. Engine.prototype.setHardwareScalingLevel = function (level) {
  11380. this._hardwareScalingLevel = level;
  11381. this.resize();
  11382. };
  11383. Engine.prototype.getHardwareScalingLevel = function () {
  11384. return this._hardwareScalingLevel;
  11385. };
  11386. Engine.prototype.getLoadedTexturesCache = function () {
  11387. return this._internalTexturesCache;
  11388. };
  11389. Engine.prototype.getCaps = function () {
  11390. return this._caps;
  11391. };
  11392. Object.defineProperty(Engine.prototype, "drawCalls", {
  11393. /** The number of draw calls submitted last frame */
  11394. get: function () {
  11395. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11396. return 0;
  11397. },
  11398. enumerable: true,
  11399. configurable: true
  11400. });
  11401. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11402. get: function () {
  11403. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11404. return null;
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Engine.prototype.getDepthFunction = function () {
  11410. return this._depthCullingState.depthFunc;
  11411. };
  11412. Engine.prototype.setDepthFunction = function (depthFunc) {
  11413. this._depthCullingState.depthFunc = depthFunc;
  11414. };
  11415. Engine.prototype.setDepthFunctionToGreater = function () {
  11416. this._depthCullingState.depthFunc = this._gl.GREATER;
  11417. };
  11418. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11419. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11420. };
  11421. Engine.prototype.setDepthFunctionToLess = function () {
  11422. this._depthCullingState.depthFunc = this._gl.LESS;
  11423. };
  11424. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11425. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11426. };
  11427. Engine.prototype.getStencilBuffer = function () {
  11428. return this._stencilState.stencilTest;
  11429. };
  11430. Engine.prototype.setStencilBuffer = function (enable) {
  11431. this._stencilState.stencilTest = enable;
  11432. };
  11433. Engine.prototype.getStencilMask = function () {
  11434. return this._stencilState.stencilMask;
  11435. };
  11436. Engine.prototype.setStencilMask = function (mask) {
  11437. this._stencilState.stencilMask = mask;
  11438. };
  11439. Engine.prototype.getStencilFunction = function () {
  11440. return this._stencilState.stencilFunc;
  11441. };
  11442. Engine.prototype.getStencilFunctionReference = function () {
  11443. return this._stencilState.stencilFuncRef;
  11444. };
  11445. Engine.prototype.getStencilFunctionMask = function () {
  11446. return this._stencilState.stencilFuncMask;
  11447. };
  11448. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11449. this._stencilState.stencilFunc = stencilFunc;
  11450. };
  11451. Engine.prototype.setStencilFunctionReference = function (reference) {
  11452. this._stencilState.stencilFuncRef = reference;
  11453. };
  11454. Engine.prototype.setStencilFunctionMask = function (mask) {
  11455. this._stencilState.stencilFuncMask = mask;
  11456. };
  11457. Engine.prototype.getStencilOperationFail = function () {
  11458. return this._stencilState.stencilOpStencilFail;
  11459. };
  11460. Engine.prototype.getStencilOperationDepthFail = function () {
  11461. return this._stencilState.stencilOpDepthFail;
  11462. };
  11463. Engine.prototype.getStencilOperationPass = function () {
  11464. return this._stencilState.stencilOpStencilDepthPass;
  11465. };
  11466. Engine.prototype.setStencilOperationFail = function (operation) {
  11467. this._stencilState.stencilOpStencilFail = operation;
  11468. };
  11469. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11470. this._stencilState.stencilOpDepthFail = operation;
  11471. };
  11472. Engine.prototype.setStencilOperationPass = function (operation) {
  11473. this._stencilState.stencilOpStencilDepthPass = operation;
  11474. };
  11475. Engine.prototype.setDitheringState = function (value) {
  11476. if (value) {
  11477. this._gl.enable(this._gl.DITHER);
  11478. }
  11479. else {
  11480. this._gl.disable(this._gl.DITHER);
  11481. }
  11482. };
  11483. Engine.prototype.setRasterizerState = function (value) {
  11484. if (value) {
  11485. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11486. }
  11487. else {
  11488. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11489. }
  11490. };
  11491. /**
  11492. * stop executing a render loop function and remove it from the execution array
  11493. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11494. */
  11495. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11496. if (!renderFunction) {
  11497. this._activeRenderLoops = [];
  11498. return;
  11499. }
  11500. var index = this._activeRenderLoops.indexOf(renderFunction);
  11501. if (index >= 0) {
  11502. this._activeRenderLoops.splice(index, 1);
  11503. }
  11504. };
  11505. Engine.prototype._renderLoop = function () {
  11506. if (!this._contextWasLost) {
  11507. var shouldRender = true;
  11508. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11509. shouldRender = false;
  11510. }
  11511. if (shouldRender) {
  11512. // Start new frame
  11513. this.beginFrame();
  11514. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11515. var renderFunction = this._activeRenderLoops[index];
  11516. renderFunction();
  11517. }
  11518. // Present
  11519. this.endFrame();
  11520. }
  11521. }
  11522. if (this._activeRenderLoops.length > 0) {
  11523. // Register new frame
  11524. var requester = null;
  11525. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11526. requester = this._vrDisplay;
  11527. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11528. }
  11529. else {
  11530. this._renderingQueueLaunched = false;
  11531. }
  11532. };
  11533. /**
  11534. * Register and execute a render loop. The engine can have more than one render function.
  11535. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11536. * @example
  11537. * engine.runRenderLoop(function () {
  11538. * scene.render()
  11539. * })
  11540. */
  11541. Engine.prototype.runRenderLoop = function (renderFunction) {
  11542. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11543. return;
  11544. }
  11545. this._activeRenderLoops.push(renderFunction);
  11546. if (!this._renderingQueueLaunched) {
  11547. this._renderingQueueLaunched = true;
  11548. this._bindedRenderFunction = this._renderLoop.bind(this);
  11549. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11550. }
  11551. };
  11552. /**
  11553. * Toggle full screen mode.
  11554. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11555. * @param {any} options - an options object to be sent to the requestFullscreen function
  11556. */
  11557. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11558. if (this.isFullscreen) {
  11559. BABYLON.Tools.ExitFullscreen();
  11560. }
  11561. else {
  11562. this._pointerLockRequested = requestPointerLock;
  11563. if (this._renderingCanvas) {
  11564. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11565. }
  11566. }
  11567. };
  11568. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11569. if (stencil === void 0) { stencil = false; }
  11570. this.applyStates();
  11571. var mode = 0;
  11572. if (backBuffer && color) {
  11573. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11574. mode |= this._gl.COLOR_BUFFER_BIT;
  11575. }
  11576. if (depth) {
  11577. this._gl.clearDepth(1.0);
  11578. mode |= this._gl.DEPTH_BUFFER_BIT;
  11579. }
  11580. if (stencil) {
  11581. this._gl.clearStencil(0);
  11582. mode |= this._gl.STENCIL_BUFFER_BIT;
  11583. }
  11584. this._gl.clear(mode);
  11585. };
  11586. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11587. var gl = this._gl;
  11588. // Save state
  11589. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11590. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11591. // Change state
  11592. gl.enable(gl.SCISSOR_TEST);
  11593. gl.scissor(x, y, width, height);
  11594. // Clear
  11595. this.clear(clearColor, true, true, true);
  11596. // Restore state
  11597. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11598. if (curScissor === true) {
  11599. gl.enable(gl.SCISSOR_TEST);
  11600. }
  11601. else {
  11602. gl.disable(gl.SCISSOR_TEST);
  11603. }
  11604. };
  11605. /**
  11606. * Set the WebGL's viewport
  11607. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11608. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11609. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11610. */
  11611. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11612. var width = requiredWidth || this.getRenderWidth();
  11613. var height = requiredHeight || this.getRenderHeight();
  11614. var x = viewport.x || 0;
  11615. var y = viewport.y || 0;
  11616. this._cachedViewport = viewport;
  11617. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11618. };
  11619. /**
  11620. * Directly set the WebGL Viewport
  11621. * The x, y, width & height are directly passed to the WebGL call
  11622. * @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.
  11623. */
  11624. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11625. var currentViewport = this._cachedViewport;
  11626. this._cachedViewport = null;
  11627. this._gl.viewport(x, y, width, height);
  11628. return currentViewport;
  11629. };
  11630. Engine.prototype.beginFrame = function () {
  11631. this.onBeginFrameObservable.notifyObservers(this);
  11632. this._measureFps();
  11633. };
  11634. Engine.prototype.endFrame = function () {
  11635. //force a flush in case we are using a bad OS.
  11636. if (this._badOS) {
  11637. this.flushFramebuffer();
  11638. }
  11639. //submit frame to the vr device, if enabled
  11640. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11641. // TODO: We should only submit the frame if we read frameData successfully.
  11642. this._vrDisplay.submitFrame();
  11643. }
  11644. this.onEndFrameObservable.notifyObservers(this);
  11645. };
  11646. /**
  11647. * resize the view according to the canvas' size.
  11648. * @example
  11649. * window.addEventListener("resize", function () {
  11650. * engine.resize();
  11651. * });
  11652. */
  11653. Engine.prototype.resize = function () {
  11654. // We're not resizing the size of the canvas while in VR mode & presenting
  11655. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11656. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11657. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11658. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11659. }
  11660. };
  11661. /**
  11662. * force a specific size of the canvas
  11663. * @param {number} width - the new canvas' width
  11664. * @param {number} height - the new canvas' height
  11665. */
  11666. Engine.prototype.setSize = function (width, height) {
  11667. if (!this._renderingCanvas) {
  11668. return;
  11669. }
  11670. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11671. return;
  11672. }
  11673. this._renderingCanvas.width = width;
  11674. this._renderingCanvas.height = height;
  11675. for (var index = 0; index < this.scenes.length; index++) {
  11676. var scene = this.scenes[index];
  11677. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11678. var cam = scene.cameras[camIndex];
  11679. cam._currentRenderId = 0;
  11680. }
  11681. }
  11682. if (this.onResizeObservable.hasObservers) {
  11683. this.onResizeObservable.notifyObservers(this);
  11684. }
  11685. };
  11686. // WebVR functions
  11687. Engine.prototype.isVRDevicePresent = function () {
  11688. return !!this._vrDisplay;
  11689. };
  11690. Engine.prototype.getVRDevice = function () {
  11691. return this._vrDisplay;
  11692. };
  11693. /**
  11694. * Initializes a webVR display and starts listening to display change events.
  11695. * The onVRDisplayChangedObservable will be notified upon these changes.
  11696. * @returns The onVRDisplayChangedObservable.
  11697. */
  11698. Engine.prototype.initWebVR = function () {
  11699. this.initWebVRAsync();
  11700. return this.onVRDisplayChangedObservable;
  11701. };
  11702. /**
  11703. * Initializes a webVR display and starts listening to display change events.
  11704. * The onVRDisplayChangedObservable will be notified upon these changes.
  11705. * @returns A promise containing a VRDisplay and if vr is supported.
  11706. */
  11707. Engine.prototype.initWebVRAsync = function () {
  11708. var _this = this;
  11709. var notifyObservers = function () {
  11710. var eventArgs = {
  11711. vrDisplay: _this._vrDisplay,
  11712. vrSupported: _this._vrSupported
  11713. };
  11714. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11715. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11716. };
  11717. if (!this._onVrDisplayConnect) {
  11718. this._onVrDisplayConnect = function (event) {
  11719. _this._vrDisplay = event.display;
  11720. notifyObservers();
  11721. };
  11722. this._onVrDisplayDisconnect = function () {
  11723. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11724. _this._vrDisplay = undefined;
  11725. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11726. notifyObservers();
  11727. };
  11728. this._onVrDisplayPresentChange = function () {
  11729. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11730. };
  11731. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11732. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11733. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11734. }
  11735. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11736. this._webVRInitPromise.then(notifyObservers);
  11737. return this._webVRInitPromise;
  11738. };
  11739. Engine.prototype.enableVR = function () {
  11740. var _this = this;
  11741. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11742. var onResolved = function () {
  11743. _this.onVRRequestPresentComplete.notifyObservers(true);
  11744. _this._onVRFullScreenTriggered();
  11745. };
  11746. var onRejected = function () {
  11747. _this.onVRRequestPresentComplete.notifyObservers(false);
  11748. };
  11749. this.onVRRequestPresentStart.notifyObservers(this);
  11750. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11751. }
  11752. };
  11753. Engine.prototype.disableVR = function () {
  11754. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11755. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11756. }
  11757. };
  11758. Engine.prototype._getVRDisplaysAsync = function () {
  11759. var _this = this;
  11760. return new Promise(function (res, rej) {
  11761. if (navigator.getVRDisplays) {
  11762. navigator.getVRDisplays().then(function (devices) {
  11763. _this._vrSupported = true;
  11764. // note that devices may actually be an empty array. This is fine;
  11765. // we expect this._vrDisplay to be undefined in this case.
  11766. _this._vrDisplay = devices[0];
  11767. res({
  11768. vrDisplay: _this._vrDisplay,
  11769. vrSupported: _this._vrSupported
  11770. });
  11771. });
  11772. }
  11773. else {
  11774. _this._vrDisplay = undefined;
  11775. _this._vrSupported = false;
  11776. res({
  11777. vrDisplay: _this._vrDisplay,
  11778. vrSupported: _this._vrSupported
  11779. });
  11780. }
  11781. });
  11782. };
  11783. /**
  11784. * Binds the frame buffer to the specified texture.
  11785. * @param texture The texture to render to or null for the default canvas
  11786. * @param faceIndex The face of the texture to render to in case of cube texture
  11787. * @param requiredWidth The width of the target to render to
  11788. * @param requiredHeight The height of the target to render to
  11789. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11790. * @param depthStencilTexture The depth stencil texture to use to render
  11791. */
  11792. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11793. if (this._currentRenderTarget) {
  11794. this.unBindFramebuffer(this._currentRenderTarget);
  11795. }
  11796. this._currentRenderTarget = texture;
  11797. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11798. var gl = this._gl;
  11799. if (texture.isCube) {
  11800. if (faceIndex === undefined) {
  11801. faceIndex = 0;
  11802. }
  11803. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11804. if (depthStencilTexture) {
  11805. if (depthStencilTexture._generateStencilBuffer) {
  11806. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11807. }
  11808. else {
  11809. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11810. }
  11811. }
  11812. }
  11813. if (this._cachedViewport && !forceFullscreenViewport) {
  11814. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11815. }
  11816. else {
  11817. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11818. }
  11819. this.wipeCaches();
  11820. };
  11821. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11822. if (this._currentFramebuffer !== framebuffer) {
  11823. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11824. this._currentFramebuffer = framebuffer;
  11825. }
  11826. };
  11827. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11828. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11829. this._currentRenderTarget = null;
  11830. // If MSAA, we need to bitblt back to main texture
  11831. var gl = this._gl;
  11832. if (texture._MSAAFramebuffer) {
  11833. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11834. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11835. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11836. }
  11837. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11838. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11839. gl.generateMipmap(gl.TEXTURE_2D);
  11840. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11841. }
  11842. if (onBeforeUnbind) {
  11843. if (texture._MSAAFramebuffer) {
  11844. // Bind the correct framebuffer
  11845. this.bindUnboundFramebuffer(texture._framebuffer);
  11846. }
  11847. onBeforeUnbind();
  11848. }
  11849. this.bindUnboundFramebuffer(null);
  11850. };
  11851. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11852. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11853. this._currentRenderTarget = null;
  11854. // If MSAA, we need to bitblt back to main texture
  11855. var gl = this._gl;
  11856. if (textures[0]._MSAAFramebuffer) {
  11857. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11858. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11859. var attachments = textures[0]._attachments;
  11860. if (!attachments) {
  11861. attachments = new Array(textures.length);
  11862. textures[0]._attachments = attachments;
  11863. }
  11864. for (var i = 0; i < textures.length; i++) {
  11865. var texture = textures[i];
  11866. for (var j = 0; j < attachments.length; j++) {
  11867. attachments[j] = gl.NONE;
  11868. }
  11869. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11870. gl.readBuffer(attachments[i]);
  11871. gl.drawBuffers(attachments);
  11872. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11873. }
  11874. for (var i = 0; i < attachments.length; i++) {
  11875. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11876. }
  11877. gl.drawBuffers(attachments);
  11878. }
  11879. for (var i = 0; i < textures.length; i++) {
  11880. var texture = textures[i];
  11881. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11882. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11883. gl.generateMipmap(gl.TEXTURE_2D);
  11884. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11885. }
  11886. }
  11887. if (onBeforeUnbind) {
  11888. if (textures[0]._MSAAFramebuffer) {
  11889. // Bind the correct framebuffer
  11890. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11891. }
  11892. onBeforeUnbind();
  11893. }
  11894. this.bindUnboundFramebuffer(null);
  11895. };
  11896. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11897. if (texture.generateMipMaps) {
  11898. var gl = this._gl;
  11899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11900. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11901. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11902. }
  11903. };
  11904. Engine.prototype.flushFramebuffer = function () {
  11905. this._gl.flush();
  11906. };
  11907. Engine.prototype.restoreDefaultFramebuffer = function () {
  11908. if (this._currentRenderTarget) {
  11909. this.unBindFramebuffer(this._currentRenderTarget);
  11910. }
  11911. else {
  11912. this.bindUnboundFramebuffer(null);
  11913. }
  11914. if (this._cachedViewport) {
  11915. this.setViewport(this._cachedViewport);
  11916. }
  11917. this.wipeCaches();
  11918. };
  11919. // UBOs
  11920. Engine.prototype.createUniformBuffer = function (elements) {
  11921. var ubo = this._gl.createBuffer();
  11922. if (!ubo) {
  11923. throw new Error("Unable to create uniform buffer");
  11924. }
  11925. this.bindUniformBuffer(ubo);
  11926. if (elements instanceof Float32Array) {
  11927. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11928. }
  11929. else {
  11930. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11931. }
  11932. this.bindUniformBuffer(null);
  11933. ubo.references = 1;
  11934. return ubo;
  11935. };
  11936. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11937. var ubo = this._gl.createBuffer();
  11938. if (!ubo) {
  11939. throw new Error("Unable to create dynamic uniform buffer");
  11940. }
  11941. this.bindUniformBuffer(ubo);
  11942. if (elements instanceof Float32Array) {
  11943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11944. }
  11945. else {
  11946. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11947. }
  11948. this.bindUniformBuffer(null);
  11949. ubo.references = 1;
  11950. return ubo;
  11951. };
  11952. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11953. this.bindUniformBuffer(uniformBuffer);
  11954. if (offset === undefined) {
  11955. offset = 0;
  11956. }
  11957. if (count === undefined) {
  11958. if (elements instanceof Float32Array) {
  11959. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11960. }
  11961. else {
  11962. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11963. }
  11964. }
  11965. else {
  11966. if (elements instanceof Float32Array) {
  11967. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11968. }
  11969. else {
  11970. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11971. }
  11972. }
  11973. this.bindUniformBuffer(null);
  11974. };
  11975. // VBOs
  11976. Engine.prototype._resetVertexBufferBinding = function () {
  11977. this.bindArrayBuffer(null);
  11978. this._cachedVertexBuffers = null;
  11979. };
  11980. Engine.prototype.createVertexBuffer = function (vertices) {
  11981. var vbo = this._gl.createBuffer();
  11982. if (!vbo) {
  11983. throw new Error("Unable to create vertex buffer");
  11984. }
  11985. this.bindArrayBuffer(vbo);
  11986. if (vertices instanceof Float32Array) {
  11987. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11988. }
  11989. else {
  11990. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11991. }
  11992. this._resetVertexBufferBinding();
  11993. vbo.references = 1;
  11994. return vbo;
  11995. };
  11996. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11997. var vbo = this._gl.createBuffer();
  11998. if (!vbo) {
  11999. throw new Error("Unable to create dynamic vertex buffer");
  12000. }
  12001. this.bindArrayBuffer(vbo);
  12002. if (vertices instanceof Float32Array) {
  12003. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12004. }
  12005. else {
  12006. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12007. }
  12008. this._resetVertexBufferBinding();
  12009. vbo.references = 1;
  12010. return vbo;
  12011. };
  12012. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12013. if (offset === void 0) { offset = 0; }
  12014. // Force cache update
  12015. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12016. this.bindIndexBuffer(indexBuffer);
  12017. var arrayBuffer;
  12018. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12019. arrayBuffer = indices;
  12020. }
  12021. else {
  12022. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12023. }
  12024. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12025. this._resetIndexBufferBinding();
  12026. };
  12027. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12028. this.bindArrayBuffer(vertexBuffer);
  12029. if (offset === undefined) {
  12030. offset = 0;
  12031. }
  12032. if (count === undefined) {
  12033. if (vertices instanceof Float32Array) {
  12034. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12035. }
  12036. else {
  12037. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12038. }
  12039. }
  12040. else {
  12041. if (vertices instanceof Float32Array) {
  12042. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12043. }
  12044. else {
  12045. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12046. }
  12047. }
  12048. this._resetVertexBufferBinding();
  12049. };
  12050. Engine.prototype._resetIndexBufferBinding = function () {
  12051. this.bindIndexBuffer(null);
  12052. this._cachedIndexBuffer = null;
  12053. };
  12054. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12055. var vbo = this._gl.createBuffer();
  12056. if (!vbo) {
  12057. throw new Error("Unable to create index buffer");
  12058. }
  12059. this.bindIndexBuffer(vbo);
  12060. // Check for 32 bits indices
  12061. var arrayBuffer;
  12062. var need32Bits = false;
  12063. if (indices instanceof Uint16Array) {
  12064. arrayBuffer = indices;
  12065. }
  12066. else {
  12067. //check 32 bit support
  12068. if (this._caps.uintIndices) {
  12069. if (indices instanceof Uint32Array) {
  12070. arrayBuffer = indices;
  12071. need32Bits = true;
  12072. }
  12073. else {
  12074. //number[] or Int32Array, check if 32 bit is necessary
  12075. for (var index = 0; index < indices.length; index++) {
  12076. if (indices[index] > 65535) {
  12077. need32Bits = true;
  12078. break;
  12079. }
  12080. }
  12081. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12082. }
  12083. }
  12084. else {
  12085. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12086. arrayBuffer = new Uint16Array(indices);
  12087. }
  12088. }
  12089. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12090. this._resetIndexBufferBinding();
  12091. vbo.references = 1;
  12092. vbo.is32Bits = need32Bits;
  12093. return vbo;
  12094. };
  12095. Engine.prototype.bindArrayBuffer = function (buffer) {
  12096. if (!this._vaoRecordInProgress) {
  12097. this._unbindVertexArrayObject();
  12098. }
  12099. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12100. };
  12101. Engine.prototype.bindUniformBuffer = function (buffer) {
  12102. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12103. };
  12104. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12105. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12106. };
  12107. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12108. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12109. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12110. };
  12111. ;
  12112. Engine.prototype.bindIndexBuffer = function (buffer) {
  12113. if (!this._vaoRecordInProgress) {
  12114. this._unbindVertexArrayObject();
  12115. }
  12116. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12117. };
  12118. Engine.prototype.bindBuffer = function (buffer, target) {
  12119. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12120. this._gl.bindBuffer(target, buffer);
  12121. this._currentBoundBuffer[target] = buffer;
  12122. }
  12123. };
  12124. Engine.prototype.updateArrayBuffer = function (data) {
  12125. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12126. };
  12127. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12128. var pointer = this._currentBufferPointers[indx];
  12129. var changed = false;
  12130. if (!pointer.active) {
  12131. changed = true;
  12132. pointer.active = true;
  12133. pointer.index = indx;
  12134. pointer.size = size;
  12135. pointer.type = type;
  12136. pointer.normalized = normalized;
  12137. pointer.stride = stride;
  12138. pointer.offset = offset;
  12139. pointer.buffer = buffer;
  12140. }
  12141. else {
  12142. if (pointer.buffer !== buffer) {
  12143. pointer.buffer = buffer;
  12144. changed = true;
  12145. }
  12146. if (pointer.size !== size) {
  12147. pointer.size = size;
  12148. changed = true;
  12149. }
  12150. if (pointer.type !== type) {
  12151. pointer.type = type;
  12152. changed = true;
  12153. }
  12154. if (pointer.normalized !== normalized) {
  12155. pointer.normalized = normalized;
  12156. changed = true;
  12157. }
  12158. if (pointer.stride !== stride) {
  12159. pointer.stride = stride;
  12160. changed = true;
  12161. }
  12162. if (pointer.offset !== offset) {
  12163. pointer.offset = offset;
  12164. changed = true;
  12165. }
  12166. }
  12167. if (changed || this._vaoRecordInProgress) {
  12168. this.bindArrayBuffer(buffer);
  12169. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12170. }
  12171. };
  12172. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12173. if (indexBuffer == null) {
  12174. return;
  12175. }
  12176. if (this._cachedIndexBuffer !== indexBuffer) {
  12177. this._cachedIndexBuffer = indexBuffer;
  12178. this.bindIndexBuffer(indexBuffer);
  12179. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12180. }
  12181. };
  12182. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12183. var attributes = effect.getAttributesNames();
  12184. if (!this._vaoRecordInProgress) {
  12185. this._unbindVertexArrayObject();
  12186. }
  12187. this.unbindAllAttributes();
  12188. for (var index = 0; index < attributes.length; index++) {
  12189. var order = effect.getAttributeLocation(index);
  12190. if (order >= 0) {
  12191. var vertexBuffer = vertexBuffers[attributes[index]];
  12192. if (!vertexBuffer) {
  12193. continue;
  12194. }
  12195. this._gl.enableVertexAttribArray(order);
  12196. if (!this._vaoRecordInProgress) {
  12197. this._vertexAttribArraysEnabled[order] = true;
  12198. }
  12199. var buffer = vertexBuffer.getBuffer();
  12200. if (buffer) {
  12201. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12202. if (vertexBuffer.getIsInstanced()) {
  12203. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12204. if (!this._vaoRecordInProgress) {
  12205. this._currentInstanceLocations.push(order);
  12206. this._currentInstanceBuffers.push(buffer);
  12207. }
  12208. }
  12209. }
  12210. }
  12211. }
  12212. };
  12213. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12214. var vao = this._gl.createVertexArray();
  12215. this._vaoRecordInProgress = true;
  12216. this._gl.bindVertexArray(vao);
  12217. this._mustWipeVertexAttributes = true;
  12218. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12219. this.bindIndexBuffer(indexBuffer);
  12220. this._vaoRecordInProgress = false;
  12221. this._gl.bindVertexArray(null);
  12222. return vao;
  12223. };
  12224. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12225. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12226. this._cachedVertexArrayObject = vertexArrayObject;
  12227. this._gl.bindVertexArray(vertexArrayObject);
  12228. this._cachedVertexBuffers = null;
  12229. this._cachedIndexBuffer = null;
  12230. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12231. this._mustWipeVertexAttributes = true;
  12232. }
  12233. };
  12234. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12235. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12236. this._cachedVertexBuffers = vertexBuffer;
  12237. this._cachedEffectForVertexBuffers = effect;
  12238. var attributesCount = effect.getAttributesCount();
  12239. this._unbindVertexArrayObject();
  12240. this.unbindAllAttributes();
  12241. var offset = 0;
  12242. for (var index = 0; index < attributesCount; index++) {
  12243. if (index < vertexDeclaration.length) {
  12244. var order = effect.getAttributeLocation(index);
  12245. if (order >= 0) {
  12246. this._gl.enableVertexAttribArray(order);
  12247. this._vertexAttribArraysEnabled[order] = true;
  12248. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12249. }
  12250. offset += vertexDeclaration[index] * 4;
  12251. }
  12252. }
  12253. }
  12254. this._bindIndexBufferWithCache(indexBuffer);
  12255. };
  12256. Engine.prototype._unbindVertexArrayObject = function () {
  12257. if (!this._cachedVertexArrayObject) {
  12258. return;
  12259. }
  12260. this._cachedVertexArrayObject = null;
  12261. this._gl.bindVertexArray(null);
  12262. };
  12263. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12264. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12265. this._cachedVertexBuffers = vertexBuffers;
  12266. this._cachedEffectForVertexBuffers = effect;
  12267. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12268. }
  12269. this._bindIndexBufferWithCache(indexBuffer);
  12270. };
  12271. Engine.prototype.unbindInstanceAttributes = function () {
  12272. var boundBuffer;
  12273. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12274. var instancesBuffer = this._currentInstanceBuffers[i];
  12275. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12276. boundBuffer = instancesBuffer;
  12277. this.bindArrayBuffer(instancesBuffer);
  12278. }
  12279. var offsetLocation = this._currentInstanceLocations[i];
  12280. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12281. }
  12282. this._currentInstanceBuffers.length = 0;
  12283. this._currentInstanceLocations.length = 0;
  12284. };
  12285. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12286. this._gl.deleteVertexArray(vao);
  12287. };
  12288. Engine.prototype._releaseBuffer = function (buffer) {
  12289. buffer.references--;
  12290. if (buffer.references === 0) {
  12291. this._gl.deleteBuffer(buffer);
  12292. return true;
  12293. }
  12294. return false;
  12295. };
  12296. Engine.prototype.createInstancesBuffer = function (capacity) {
  12297. var buffer = this._gl.createBuffer();
  12298. if (!buffer) {
  12299. throw new Error("Unable to create instance buffer");
  12300. }
  12301. buffer.capacity = capacity;
  12302. this.bindArrayBuffer(buffer);
  12303. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12304. return buffer;
  12305. };
  12306. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12307. this._gl.deleteBuffer(buffer);
  12308. };
  12309. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12310. this.bindArrayBuffer(instancesBuffer);
  12311. if (data) {
  12312. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12313. }
  12314. if (offsetLocations[0].index !== undefined) {
  12315. var stride = 0;
  12316. for (var i = 0; i < offsetLocations.length; i++) {
  12317. var ai = offsetLocations[i];
  12318. stride += ai.attributeSize * 4;
  12319. }
  12320. for (var i = 0; i < offsetLocations.length; i++) {
  12321. var ai = offsetLocations[i];
  12322. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12323. this._gl.enableVertexAttribArray(ai.index);
  12324. this._vertexAttribArraysEnabled[ai.index] = true;
  12325. }
  12326. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12327. this._gl.vertexAttribDivisor(ai.index, 1);
  12328. this._currentInstanceLocations.push(ai.index);
  12329. this._currentInstanceBuffers.push(instancesBuffer);
  12330. }
  12331. }
  12332. else {
  12333. for (var index = 0; index < 4; index++) {
  12334. var offsetLocation = offsetLocations[index];
  12335. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12336. this._gl.enableVertexAttribArray(offsetLocation);
  12337. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12338. }
  12339. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12340. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12341. this._currentInstanceLocations.push(offsetLocation);
  12342. this._currentInstanceBuffers.push(instancesBuffer);
  12343. }
  12344. }
  12345. };
  12346. Engine.prototype.applyStates = function () {
  12347. this._depthCullingState.apply(this._gl);
  12348. this._stencilState.apply(this._gl);
  12349. this._alphaState.apply(this._gl);
  12350. };
  12351. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12352. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12353. };
  12354. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12355. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12356. };
  12357. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12358. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12359. };
  12360. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12361. // Apply states
  12362. this.applyStates();
  12363. this._drawCalls.addCount(1, false);
  12364. // Render
  12365. var drawMode = this.DrawMode(fillMode);
  12366. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12367. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12368. if (instancesCount) {
  12369. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12370. }
  12371. else {
  12372. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12373. }
  12374. };
  12375. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12376. // Apply states
  12377. this.applyStates();
  12378. this._drawCalls.addCount(1, false);
  12379. var drawMode = this.DrawMode(fillMode);
  12380. if (instancesCount) {
  12381. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12382. }
  12383. else {
  12384. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12385. }
  12386. };
  12387. Engine.prototype.DrawMode = function (fillMode) {
  12388. switch (fillMode) {
  12389. // Triangle views
  12390. case BABYLON.Material.TriangleFillMode:
  12391. return this._gl.TRIANGLES;
  12392. case BABYLON.Material.PointFillMode:
  12393. return this._gl.POINTS;
  12394. case BABYLON.Material.WireFrameFillMode:
  12395. return this._gl.LINES;
  12396. // Draw modes
  12397. case BABYLON.Material.PointListDrawMode:
  12398. return this._gl.POINTS;
  12399. case BABYLON.Material.LineListDrawMode:
  12400. return this._gl.LINES;
  12401. case BABYLON.Material.LineLoopDrawMode:
  12402. return this._gl.LINE_LOOP;
  12403. case BABYLON.Material.LineStripDrawMode:
  12404. return this._gl.LINE_STRIP;
  12405. case BABYLON.Material.TriangleStripDrawMode:
  12406. return this._gl.TRIANGLE_STRIP;
  12407. case BABYLON.Material.TriangleFanDrawMode:
  12408. return this._gl.TRIANGLE_FAN;
  12409. default:
  12410. return this._gl.TRIANGLES;
  12411. }
  12412. };
  12413. // Shaders
  12414. Engine.prototype._releaseEffect = function (effect) {
  12415. if (this._compiledEffects[effect._key]) {
  12416. delete this._compiledEffects[effect._key];
  12417. this._deleteProgram(effect.getProgram());
  12418. }
  12419. };
  12420. Engine.prototype._deleteProgram = function (program) {
  12421. if (program) {
  12422. program.__SPECTOR_rebuildProgram = null;
  12423. if (program.transformFeedback) {
  12424. this.deleteTransformFeedback(program.transformFeedback);
  12425. program.transformFeedback = null;
  12426. }
  12427. this._gl.deleteProgram(program);
  12428. }
  12429. };
  12430. /**
  12431. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12432. * @param samplers An array of string used to represent textures
  12433. */
  12434. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12435. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12436. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12437. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12438. if (this._compiledEffects[name]) {
  12439. var compiledEffect = this._compiledEffects[name];
  12440. if (onCompiled && compiledEffect.isReady()) {
  12441. onCompiled(compiledEffect);
  12442. }
  12443. return compiledEffect;
  12444. }
  12445. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12446. effect._key = name;
  12447. this._compiledEffects[name] = effect;
  12448. return effect;
  12449. };
  12450. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12451. if (uniformsNames === void 0) { uniformsNames = []; }
  12452. if (samplers === void 0) { samplers = []; }
  12453. if (defines === void 0) { defines = ""; }
  12454. return this.createEffect({
  12455. vertex: "particles",
  12456. fragmentElement: fragmentName
  12457. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12458. };
  12459. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12460. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12461. context = context || this._gl;
  12462. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12463. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12464. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12465. };
  12466. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12467. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12468. context = context || this._gl;
  12469. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12470. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12471. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12472. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12473. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12474. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12475. return program;
  12476. };
  12477. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12478. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12479. var shaderProgram = context.createProgram();
  12480. if (!shaderProgram) {
  12481. throw new Error("Unable to create program");
  12482. }
  12483. context.attachShader(shaderProgram, vertexShader);
  12484. context.attachShader(shaderProgram, fragmentShader);
  12485. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12486. var transformFeedback = this.createTransformFeedback();
  12487. this.bindTransformFeedback(transformFeedback);
  12488. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12489. shaderProgram.transformFeedback = transformFeedback;
  12490. }
  12491. context.linkProgram(shaderProgram);
  12492. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12493. this.bindTransformFeedback(null);
  12494. }
  12495. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12496. if (!linked) {
  12497. context.validateProgram(shaderProgram);
  12498. var error = context.getProgramInfoLog(shaderProgram);
  12499. if (error) {
  12500. throw new Error(error);
  12501. }
  12502. }
  12503. context.deleteShader(vertexShader);
  12504. context.deleteShader(fragmentShader);
  12505. return shaderProgram;
  12506. };
  12507. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12508. var results = new Array();
  12509. for (var index = 0; index < uniformsNames.length; index++) {
  12510. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12511. }
  12512. return results;
  12513. };
  12514. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12515. var results = [];
  12516. for (var index = 0; index < attributesNames.length; index++) {
  12517. try {
  12518. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12519. }
  12520. catch (e) {
  12521. results.push(-1);
  12522. }
  12523. }
  12524. return results;
  12525. };
  12526. Engine.prototype.enableEffect = function (effect) {
  12527. if (!effect) {
  12528. return;
  12529. }
  12530. // Use program
  12531. this.bindSamplers(effect);
  12532. this._currentEffect = effect;
  12533. if (effect.onBind) {
  12534. effect.onBind(effect);
  12535. }
  12536. effect.onBindObservable.notifyObservers(effect);
  12537. };
  12538. Engine.prototype.setIntArray = function (uniform, array) {
  12539. if (!uniform)
  12540. return;
  12541. this._gl.uniform1iv(uniform, array);
  12542. };
  12543. Engine.prototype.setIntArray2 = function (uniform, array) {
  12544. if (!uniform || array.length % 2 !== 0)
  12545. return;
  12546. this._gl.uniform2iv(uniform, array);
  12547. };
  12548. Engine.prototype.setIntArray3 = function (uniform, array) {
  12549. if (!uniform || array.length % 3 !== 0)
  12550. return;
  12551. this._gl.uniform3iv(uniform, array);
  12552. };
  12553. Engine.prototype.setIntArray4 = function (uniform, array) {
  12554. if (!uniform || array.length % 4 !== 0)
  12555. return;
  12556. this._gl.uniform4iv(uniform, array);
  12557. };
  12558. Engine.prototype.setFloatArray = function (uniform, array) {
  12559. if (!uniform)
  12560. return;
  12561. this._gl.uniform1fv(uniform, array);
  12562. };
  12563. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12564. if (!uniform || array.length % 2 !== 0)
  12565. return;
  12566. this._gl.uniform2fv(uniform, array);
  12567. };
  12568. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12569. if (!uniform || array.length % 3 !== 0)
  12570. return;
  12571. this._gl.uniform3fv(uniform, array);
  12572. };
  12573. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12574. if (!uniform || array.length % 4 !== 0)
  12575. return;
  12576. this._gl.uniform4fv(uniform, array);
  12577. };
  12578. Engine.prototype.setArray = function (uniform, array) {
  12579. if (!uniform)
  12580. return;
  12581. this._gl.uniform1fv(uniform, array);
  12582. };
  12583. Engine.prototype.setArray2 = function (uniform, array) {
  12584. if (!uniform || array.length % 2 !== 0)
  12585. return;
  12586. this._gl.uniform2fv(uniform, array);
  12587. };
  12588. Engine.prototype.setArray3 = function (uniform, array) {
  12589. if (!uniform || array.length % 3 !== 0)
  12590. return;
  12591. this._gl.uniform3fv(uniform, array);
  12592. };
  12593. Engine.prototype.setArray4 = function (uniform, array) {
  12594. if (!uniform || array.length % 4 !== 0)
  12595. return;
  12596. this._gl.uniform4fv(uniform, array);
  12597. };
  12598. Engine.prototype.setMatrices = function (uniform, matrices) {
  12599. if (!uniform)
  12600. return;
  12601. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12602. };
  12603. Engine.prototype.setMatrix = function (uniform, matrix) {
  12604. if (!uniform)
  12605. return;
  12606. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12607. };
  12608. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12609. if (!uniform)
  12610. return;
  12611. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12612. };
  12613. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12614. if (!uniform)
  12615. return;
  12616. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12617. };
  12618. Engine.prototype.setInt = function (uniform, value) {
  12619. if (!uniform)
  12620. return;
  12621. this._gl.uniform1i(uniform, value);
  12622. };
  12623. Engine.prototype.setFloat = function (uniform, value) {
  12624. if (!uniform)
  12625. return;
  12626. this._gl.uniform1f(uniform, value);
  12627. };
  12628. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12629. if (!uniform)
  12630. return;
  12631. this._gl.uniform2f(uniform, x, y);
  12632. };
  12633. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12634. if (!uniform)
  12635. return;
  12636. this._gl.uniform3f(uniform, x, y, z);
  12637. };
  12638. Engine.prototype.setBool = function (uniform, bool) {
  12639. if (!uniform)
  12640. return;
  12641. this._gl.uniform1i(uniform, bool);
  12642. };
  12643. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12644. if (!uniform)
  12645. return;
  12646. this._gl.uniform4f(uniform, x, y, z, w);
  12647. };
  12648. Engine.prototype.setColor3 = function (uniform, color3) {
  12649. if (!uniform)
  12650. return;
  12651. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12652. };
  12653. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12654. if (!uniform)
  12655. return;
  12656. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12657. };
  12658. /**
  12659. * Sets a Color4 on a uniform variable
  12660. * @param uniform defines the uniform location
  12661. * @param color4 defines the value to be set
  12662. */
  12663. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12664. if (!uniform)
  12665. return;
  12666. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12667. };
  12668. // States
  12669. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12670. if (zOffset === void 0) { zOffset = 0; }
  12671. if (reverseSide === void 0) { reverseSide = false; }
  12672. // Culling
  12673. if (this._depthCullingState.cull !== culling || force) {
  12674. this._depthCullingState.cull = culling;
  12675. }
  12676. // Cull face
  12677. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12678. if (this._depthCullingState.cullFace !== cullFace || force) {
  12679. this._depthCullingState.cullFace = cullFace;
  12680. }
  12681. // Z offset
  12682. this.setZOffset(zOffset);
  12683. // Front face
  12684. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12685. if (this._depthCullingState.frontFace !== frontFace || force) {
  12686. this._depthCullingState.frontFace = frontFace;
  12687. }
  12688. };
  12689. Engine.prototype.setZOffset = function (value) {
  12690. this._depthCullingState.zOffset = value;
  12691. };
  12692. Engine.prototype.getZOffset = function () {
  12693. return this._depthCullingState.zOffset;
  12694. };
  12695. Engine.prototype.setDepthBuffer = function (enable) {
  12696. this._depthCullingState.depthTest = enable;
  12697. };
  12698. Engine.prototype.getDepthWrite = function () {
  12699. return this._depthCullingState.depthMask;
  12700. };
  12701. Engine.prototype.setDepthWrite = function (enable) {
  12702. this._depthCullingState.depthMask = enable;
  12703. };
  12704. Engine.prototype.setColorWrite = function (enable) {
  12705. this._gl.colorMask(enable, enable, enable, enable);
  12706. this._colorWrite = enable;
  12707. };
  12708. Engine.prototype.getColorWrite = function () {
  12709. return this._colorWrite;
  12710. };
  12711. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12712. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12713. };
  12714. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12715. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12716. if (this._alphaMode === mode) {
  12717. return;
  12718. }
  12719. switch (mode) {
  12720. case Engine.ALPHA_DISABLE:
  12721. this._alphaState.alphaBlend = false;
  12722. break;
  12723. case Engine.ALPHA_PREMULTIPLIED:
  12724. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12725. this._alphaState.alphaBlend = true;
  12726. break;
  12727. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12728. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12729. this._alphaState.alphaBlend = true;
  12730. break;
  12731. case Engine.ALPHA_COMBINE:
  12732. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12733. this._alphaState.alphaBlend = true;
  12734. break;
  12735. case Engine.ALPHA_ONEONE:
  12736. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12737. this._alphaState.alphaBlend = true;
  12738. break;
  12739. case Engine.ALPHA_ADD:
  12740. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12741. this._alphaState.alphaBlend = true;
  12742. break;
  12743. case Engine.ALPHA_SUBTRACT:
  12744. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12745. this._alphaState.alphaBlend = true;
  12746. break;
  12747. case Engine.ALPHA_MULTIPLY:
  12748. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12749. this._alphaState.alphaBlend = true;
  12750. break;
  12751. case Engine.ALPHA_MAXIMIZED:
  12752. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12753. this._alphaState.alphaBlend = true;
  12754. break;
  12755. case Engine.ALPHA_INTERPOLATE:
  12756. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12757. this._alphaState.alphaBlend = true;
  12758. break;
  12759. case Engine.ALPHA_SCREENMODE:
  12760. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12761. this._alphaState.alphaBlend = true;
  12762. break;
  12763. }
  12764. if (!noDepthWriteChange) {
  12765. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12766. }
  12767. this._alphaMode = mode;
  12768. };
  12769. Engine.prototype.getAlphaMode = function () {
  12770. return this._alphaMode;
  12771. };
  12772. // Textures
  12773. Engine.prototype.wipeCaches = function (bruteForce) {
  12774. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12775. return;
  12776. }
  12777. this._currentEffect = null;
  12778. // 6/8/2017: deltakosh: Should not be required anymore.
  12779. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12780. if (bruteForce) {
  12781. this.resetTextureCache();
  12782. this._currentProgram = null;
  12783. this._stencilState.reset();
  12784. this._depthCullingState.reset();
  12785. this.setDepthFunctionToLessOrEqual();
  12786. this._alphaState.reset();
  12787. }
  12788. this._resetVertexBufferBinding();
  12789. this._cachedIndexBuffer = null;
  12790. this._cachedEffectForVertexBuffers = null;
  12791. this._unbindVertexArrayObject();
  12792. this.bindIndexBuffer(null);
  12793. };
  12794. /**
  12795. * Set the compressed texture format to use, based on the formats you have, and the formats
  12796. * supported by the hardware / browser.
  12797. *
  12798. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12799. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12800. * to API arguments needed to compressed textures. This puts the burden on the container
  12801. * generator to house the arcane code for determining these for current & future formats.
  12802. *
  12803. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12804. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12805. *
  12806. * Note: The result of this call is not taken into account when a texture is base64.
  12807. *
  12808. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12809. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12810. *
  12811. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12812. * @returns The extension selected.
  12813. */
  12814. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12815. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12816. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12817. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12818. return this._textureFormatInUse = this._texturesSupported[i];
  12819. }
  12820. }
  12821. }
  12822. // actively set format to nothing, to allow this to be called more than once
  12823. // and possibly fail the 2nd time
  12824. this._textureFormatInUse = null;
  12825. return null;
  12826. };
  12827. Engine.prototype._createTexture = function () {
  12828. var texture = this._gl.createTexture();
  12829. if (!texture) {
  12830. throw new Error("Unable to create texture");
  12831. }
  12832. return texture;
  12833. };
  12834. /**
  12835. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12836. * @param {string} urlArg- This contains one of the following:
  12837. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12838. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12839. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12840. *
  12841. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12842. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12843. * @param {Scene} scene- Needed for loading to the correct scene.
  12844. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12845. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12846. * @param {callback} onError- Optional callback to be called upon failure.
  12847. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12848. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12849. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12850. *
  12851. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12852. */
  12853. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12854. var _this = this;
  12855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12856. if (onLoad === void 0) { onLoad = null; }
  12857. if (onError === void 0) { onError = null; }
  12858. if (buffer === void 0) { buffer = null; }
  12859. if (fallBack === void 0) { fallBack = null; }
  12860. if (format === void 0) { format = null; }
  12861. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12862. var fromData = url.substr(0, 5) === "data:";
  12863. var fromBlob = url.substr(0, 5) === "blob:";
  12864. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12865. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12866. // establish the file extension, if possible
  12867. var lastDot = url.lastIndexOf('.');
  12868. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12869. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12870. var isTGA = (extension.indexOf(".tga") === 0);
  12871. // determine if a ktx file should be substituted
  12872. var isKTX = false;
  12873. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12874. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12875. isKTX = true;
  12876. }
  12877. if (scene) {
  12878. scene._addPendingData(texture);
  12879. }
  12880. texture.url = url;
  12881. texture.generateMipMaps = !noMipmap;
  12882. texture.samplingMode = samplingMode;
  12883. texture.invertY = invertY;
  12884. if (!this._doNotHandleContextLost) {
  12885. // Keep a link to the buffer only if we plan to handle context lost
  12886. texture._buffer = buffer;
  12887. }
  12888. var onLoadObserver = null;
  12889. if (onLoad && !fallBack) {
  12890. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12891. }
  12892. if (!fallBack)
  12893. this._internalTexturesCache.push(texture);
  12894. var onerror = function (message, exception) {
  12895. if (scene) {
  12896. scene._removePendingData(texture);
  12897. }
  12898. if (onLoadObserver) {
  12899. texture.onLoadedObservable.remove(onLoadObserver);
  12900. }
  12901. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12902. if (isKTX) {
  12903. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12904. }
  12905. else if (BABYLON.Tools.UseFallbackTexture) {
  12906. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12907. }
  12908. if (onError) {
  12909. onError(message || "Unknown error", exception);
  12910. }
  12911. };
  12912. var callback = null;
  12913. // processing for non-image formats
  12914. if (isKTX || isTGA || isDDS) {
  12915. if (isKTX) {
  12916. callback = function (data) {
  12917. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12918. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12919. ktx.uploadLevels(_this._gl, !noMipmap);
  12920. return false;
  12921. }, samplingMode);
  12922. };
  12923. }
  12924. else if (isTGA) {
  12925. callback = function (arrayBuffer) {
  12926. var data = new Uint8Array(arrayBuffer);
  12927. var header = BABYLON.TGATools.GetTGAHeader(data);
  12928. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12929. BABYLON.TGATools.UploadContent(_this._gl, data);
  12930. return false;
  12931. }, samplingMode);
  12932. };
  12933. }
  12934. else if (isDDS) {
  12935. callback = function (data) {
  12936. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12937. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12938. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12939. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12940. return false;
  12941. }, samplingMode);
  12942. };
  12943. }
  12944. if (!buffer) {
  12945. this._loadFile(url, function (data) {
  12946. if (callback) {
  12947. callback(data);
  12948. }
  12949. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12950. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12951. });
  12952. }
  12953. else {
  12954. if (callback) {
  12955. callback(buffer);
  12956. }
  12957. }
  12958. // image format processing
  12959. }
  12960. else {
  12961. var onload = function (img) {
  12962. if (fromBlob && !_this._doNotHandleContextLost) {
  12963. // We need to store the image if we need to rebuild the texture
  12964. // in case of a webgl context lost
  12965. texture._buffer = img;
  12966. }
  12967. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12968. var gl = _this._gl;
  12969. var isPot = (img.width === potWidth && img.height === potHeight);
  12970. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12971. if (isPot) {
  12972. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12973. return false;
  12974. }
  12975. // Using shaders to rescale because canvas.drawImage is lossy
  12976. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12977. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12978. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12983. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12984. _this._releaseTexture(source);
  12985. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12986. continuationCallback();
  12987. });
  12988. return true;
  12989. }, samplingMode);
  12990. };
  12991. if (!fromData || isBase64)
  12992. if (buffer instanceof HTMLImageElement) {
  12993. onload(buffer);
  12994. }
  12995. else {
  12996. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12997. }
  12998. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12999. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13000. else
  13001. onload(buffer);
  13002. }
  13003. return texture;
  13004. };
  13005. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13006. var _this = this;
  13007. var rtt = this.createRenderTargetTexture({
  13008. width: destination.width,
  13009. height: destination.height,
  13010. }, {
  13011. generateMipMaps: false,
  13012. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13013. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13014. generateDepthBuffer: false,
  13015. generateStencilBuffer: false
  13016. });
  13017. if (!this._rescalePostProcess) {
  13018. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13019. }
  13020. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13021. _this._rescalePostProcess.onApply = function (effect) {
  13022. effect._bindTexture("textureSampler", source);
  13023. };
  13024. var hostingScene = scene;
  13025. if (!hostingScene) {
  13026. hostingScene = _this.scenes[_this.scenes.length - 1];
  13027. }
  13028. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13029. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13030. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13031. _this.unBindFramebuffer(rtt);
  13032. _this._releaseTexture(rtt);
  13033. if (onComplete) {
  13034. onComplete();
  13035. }
  13036. });
  13037. };
  13038. Engine.prototype._getInternalFormat = function (format) {
  13039. var internalFormat = this._gl.RGBA;
  13040. switch (format) {
  13041. case Engine.TEXTUREFORMAT_ALPHA:
  13042. internalFormat = this._gl.ALPHA;
  13043. break;
  13044. case Engine.TEXTUREFORMAT_LUMINANCE:
  13045. internalFormat = this._gl.LUMINANCE;
  13046. break;
  13047. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13048. internalFormat = this._gl.LUMINANCE_ALPHA;
  13049. break;
  13050. case Engine.TEXTUREFORMAT_RGB:
  13051. case Engine.TEXTUREFORMAT_RGB32F:
  13052. internalFormat = this._gl.RGB;
  13053. break;
  13054. case Engine.TEXTUREFORMAT_RGBA:
  13055. case Engine.TEXTUREFORMAT_RGBA32F:
  13056. internalFormat = this._gl.RGBA;
  13057. break;
  13058. case Engine.TEXTUREFORMAT_R32F:
  13059. internalFormat = this._gl.RED;
  13060. break;
  13061. case Engine.TEXTUREFORMAT_RG32F:
  13062. internalFormat = this._gl.RG;
  13063. break;
  13064. }
  13065. return internalFormat;
  13066. };
  13067. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13068. if (compression === void 0) { compression = null; }
  13069. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13070. if (!texture) {
  13071. return;
  13072. }
  13073. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13074. var internalFormat = this._getInternalFormat(format);
  13075. var textureType = this._getWebGLTextureType(type);
  13076. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13077. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13078. if (!this._doNotHandleContextLost) {
  13079. texture._bufferView = data;
  13080. texture.format = format;
  13081. texture.type = type;
  13082. texture.invertY = invertY;
  13083. texture._compression = compression;
  13084. }
  13085. if (texture.width % 4 !== 0) {
  13086. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13087. }
  13088. if (compression && data) {
  13089. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13090. }
  13091. else {
  13092. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13093. }
  13094. if (texture.generateMipMaps) {
  13095. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13096. }
  13097. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13098. // this.resetTextureCache();
  13099. texture.isReady = true;
  13100. };
  13101. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13102. if (compression === void 0) { compression = null; }
  13103. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13104. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13105. texture.baseWidth = width;
  13106. texture.baseHeight = height;
  13107. texture.width = width;
  13108. texture.height = height;
  13109. texture.format = format;
  13110. texture.generateMipMaps = generateMipMaps;
  13111. texture.samplingMode = samplingMode;
  13112. texture.invertY = invertY;
  13113. texture._compression = compression;
  13114. texture.type = type;
  13115. if (!this._doNotHandleContextLost) {
  13116. texture._bufferView = data;
  13117. }
  13118. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13119. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13120. // Filters
  13121. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13122. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13124. if (generateMipMaps) {
  13125. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13126. }
  13127. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13128. this._internalTexturesCache.push(texture);
  13129. return texture;
  13130. };
  13131. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13133. texture.baseWidth = width;
  13134. texture.baseHeight = height;
  13135. if (generateMipMaps) {
  13136. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13137. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13138. }
  13139. // this.resetTextureCache();
  13140. texture.width = width;
  13141. texture.height = height;
  13142. texture.isReady = false;
  13143. texture.generateMipMaps = generateMipMaps;
  13144. texture.samplingMode = samplingMode;
  13145. this.updateTextureSamplingMode(samplingMode, texture);
  13146. this._internalTexturesCache.push(texture);
  13147. return texture;
  13148. };
  13149. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13150. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13151. if (texture.isCube) {
  13152. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13153. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13154. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13155. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13156. }
  13157. else if (texture.is3D) {
  13158. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13159. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13160. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13161. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13162. }
  13163. else {
  13164. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13165. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13166. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13167. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13168. }
  13169. texture.samplingMode = samplingMode;
  13170. };
  13171. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13172. if (premulAlpha === void 0) { premulAlpha = false; }
  13173. if (!texture) {
  13174. return;
  13175. }
  13176. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13177. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13178. if (premulAlpha) {
  13179. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13180. }
  13181. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13182. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13183. if (texture.generateMipMaps) {
  13184. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13185. }
  13186. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13187. if (premulAlpha) {
  13188. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13189. }
  13190. texture.isReady = true;
  13191. };
  13192. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13193. if (!texture || texture._isDisabled) {
  13194. return;
  13195. }
  13196. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13197. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13198. try {
  13199. // Testing video texture support
  13200. if (this._videoTextureSupported === undefined) {
  13201. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13202. if (this._gl.getError() !== 0) {
  13203. this._videoTextureSupported = false;
  13204. }
  13205. else {
  13206. this._videoTextureSupported = true;
  13207. }
  13208. }
  13209. // Copy video through the current working canvas if video texture is not supported
  13210. if (!this._videoTextureSupported) {
  13211. if (!texture._workingCanvas) {
  13212. texture._workingCanvas = document.createElement("canvas");
  13213. var context = texture._workingCanvas.getContext("2d");
  13214. if (!context) {
  13215. throw new Error("Unable to get 2d context");
  13216. }
  13217. texture._workingContext = context;
  13218. texture._workingCanvas.width = texture.width;
  13219. texture._workingCanvas.height = texture.height;
  13220. }
  13221. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13222. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13223. }
  13224. else {
  13225. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13226. }
  13227. if (texture.generateMipMaps) {
  13228. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13229. }
  13230. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13231. // this.resetTextureCache();
  13232. texture.isReady = true;
  13233. }
  13234. catch (ex) {
  13235. // Something unexpected
  13236. // Let's disable the texture
  13237. texture._isDisabled = true;
  13238. }
  13239. };
  13240. /**
  13241. * Updates a depth texture Comparison Mode and Function.
  13242. * If the comparison Function is equal to 0, the mode will be set to none.
  13243. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13244. * @param texture The texture to set the comparison function for
  13245. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13246. */
  13247. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13248. if (this.webGLVersion === 1) {
  13249. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13250. return;
  13251. }
  13252. var gl = this._gl;
  13253. if (texture.isCube) {
  13254. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13255. if (comparisonFunction === 0) {
  13256. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13258. }
  13259. else {
  13260. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13262. }
  13263. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13264. }
  13265. else {
  13266. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13267. if (comparisonFunction === 0) {
  13268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13270. }
  13271. else {
  13272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13274. }
  13275. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13276. }
  13277. texture._comparisonFunction = comparisonFunction;
  13278. };
  13279. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13280. var width = size.width || size;
  13281. var height = size.height || size;
  13282. internalTexture.baseWidth = width;
  13283. internalTexture.baseHeight = height;
  13284. internalTexture.width = width;
  13285. internalTexture.height = height;
  13286. internalTexture.isReady = true;
  13287. internalTexture.samples = 1;
  13288. internalTexture.generateMipMaps = false;
  13289. internalTexture._generateDepthBuffer = true;
  13290. internalTexture._generateStencilBuffer = generateStencil;
  13291. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13292. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13293. internalTexture._comparisonFunction = comparisonFunction;
  13294. var gl = this._gl;
  13295. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13296. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13297. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13298. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13299. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13300. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13301. if (comparisonFunction === 0) {
  13302. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13303. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13304. }
  13305. else {
  13306. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13307. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13308. }
  13309. };
  13310. /**
  13311. * Creates a depth stencil texture.
  13312. * This is only available in WebGL 2 or with the depth texture extension available.
  13313. * @param size The size of face edge in the texture.
  13314. * @param options The options defining the texture.
  13315. * @returns The texture
  13316. */
  13317. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13318. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13319. if (!this._caps.depthTextureExtension) {
  13320. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13321. return internalTexture;
  13322. }
  13323. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13324. var gl = this._gl;
  13325. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13326. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13327. if (this.webGLVersion > 1) {
  13328. if (internalOptions.generateStencil) {
  13329. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13330. }
  13331. else {
  13332. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13333. }
  13334. }
  13335. else {
  13336. if (internalOptions.generateStencil) {
  13337. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13338. }
  13339. else {
  13340. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13341. }
  13342. }
  13343. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13344. return internalTexture;
  13345. };
  13346. /**
  13347. * Creates a depth stencil cube texture.
  13348. * This is only available in WebGL 2.
  13349. * @param size The size of face edge in the cube texture.
  13350. * @param options The options defining the cube texture.
  13351. * @returns The cube texture
  13352. */
  13353. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13354. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13355. internalTexture.isCube = true;
  13356. if (this.webGLVersion === 1) {
  13357. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13358. return internalTexture;
  13359. }
  13360. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13361. var gl = this._gl;
  13362. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13363. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13364. // Create the depth/stencil buffer
  13365. for (var face = 0; face < 6; face++) {
  13366. if (internalOptions.generateStencil) {
  13367. 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);
  13368. }
  13369. else {
  13370. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13371. }
  13372. }
  13373. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13374. return internalTexture;
  13375. };
  13376. /**
  13377. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13378. * @param renderTarget The render target to set the frame buffer for
  13379. */
  13380. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13381. // Create the framebuffer
  13382. var internalTexture = renderTarget.getInternalTexture();
  13383. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13384. return;
  13385. }
  13386. var gl = this._gl;
  13387. var depthStencilTexture = renderTarget.depthStencilTexture;
  13388. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13389. if (depthStencilTexture.isCube) {
  13390. if (depthStencilTexture._generateStencilBuffer) {
  13391. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13392. }
  13393. else {
  13394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13395. }
  13396. }
  13397. else {
  13398. if (depthStencilTexture._generateStencilBuffer) {
  13399. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13400. }
  13401. else {
  13402. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13403. }
  13404. }
  13405. this.bindUnboundFramebuffer(null);
  13406. };
  13407. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13408. var fullOptions = new RenderTargetCreationOptions();
  13409. if (options !== undefined && typeof options === "object") {
  13410. fullOptions.generateMipMaps = options.generateMipMaps;
  13411. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13412. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13413. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13414. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13415. }
  13416. else {
  13417. fullOptions.generateMipMaps = options;
  13418. fullOptions.generateDepthBuffer = true;
  13419. fullOptions.generateStencilBuffer = false;
  13420. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13421. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13422. }
  13423. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13424. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13425. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13426. }
  13427. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13428. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13429. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13430. }
  13431. var gl = this._gl;
  13432. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13433. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13434. var width = size.width || size;
  13435. var height = size.height || size;
  13436. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13437. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13438. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13439. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13440. }
  13441. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13445. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13446. // Create the framebuffer
  13447. var framebuffer = gl.createFramebuffer();
  13448. this.bindUnboundFramebuffer(framebuffer);
  13449. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13450. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13451. if (fullOptions.generateMipMaps) {
  13452. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13453. }
  13454. // Unbind
  13455. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13456. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13457. this.bindUnboundFramebuffer(null);
  13458. texture._framebuffer = framebuffer;
  13459. texture.baseWidth = width;
  13460. texture.baseHeight = height;
  13461. texture.width = width;
  13462. texture.height = height;
  13463. texture.isReady = true;
  13464. texture.samples = 1;
  13465. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13466. texture.samplingMode = fullOptions.samplingMode;
  13467. texture.type = fullOptions.type;
  13468. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13469. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13470. // this.resetTextureCache();
  13471. this._internalTexturesCache.push(texture);
  13472. return texture;
  13473. };
  13474. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13475. var generateMipMaps = false;
  13476. var generateDepthBuffer = true;
  13477. var generateStencilBuffer = false;
  13478. var generateDepthTexture = false;
  13479. var textureCount = 1;
  13480. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13481. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13482. var types = [], samplingModes = [];
  13483. if (options !== undefined) {
  13484. generateMipMaps = options.generateMipMaps;
  13485. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13486. generateStencilBuffer = options.generateStencilBuffer;
  13487. generateDepthTexture = options.generateDepthTexture;
  13488. textureCount = options.textureCount || 1;
  13489. if (options.types) {
  13490. types = options.types;
  13491. }
  13492. if (options.samplingModes) {
  13493. samplingModes = options.samplingModes;
  13494. }
  13495. }
  13496. var gl = this._gl;
  13497. // Create the framebuffer
  13498. var framebuffer = gl.createFramebuffer();
  13499. this.bindUnboundFramebuffer(framebuffer);
  13500. var width = size.width || size;
  13501. var height = size.height || size;
  13502. var textures = [];
  13503. var attachments = [];
  13504. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13505. for (var i = 0; i < textureCount; i++) {
  13506. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13507. var type = types[i] || defaultType;
  13508. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13509. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13510. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13511. }
  13512. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13513. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13514. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13515. }
  13516. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13517. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13518. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13519. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13520. }
  13521. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13522. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13523. textures.push(texture);
  13524. attachments.push(attachment);
  13525. gl.activeTexture(gl["TEXTURE" + i]);
  13526. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13527. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13528. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13531. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13532. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13533. if (generateMipMaps) {
  13534. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13535. }
  13536. // Unbind
  13537. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13538. texture._framebuffer = framebuffer;
  13539. texture._depthStencilBuffer = depthStencilBuffer;
  13540. texture.baseWidth = width;
  13541. texture.baseHeight = height;
  13542. texture.width = width;
  13543. texture.height = height;
  13544. texture.isReady = true;
  13545. texture.samples = 1;
  13546. texture.generateMipMaps = generateMipMaps;
  13547. texture.samplingMode = samplingMode;
  13548. texture.type = type;
  13549. texture._generateDepthBuffer = generateDepthBuffer;
  13550. texture._generateStencilBuffer = generateStencilBuffer;
  13551. texture._attachments = attachments;
  13552. this._internalTexturesCache.push(texture);
  13553. }
  13554. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13555. // Depth texture
  13556. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13557. gl.activeTexture(gl.TEXTURE0);
  13558. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13563. 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);
  13564. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13565. depthTexture._framebuffer = framebuffer;
  13566. depthTexture.baseWidth = width;
  13567. depthTexture.baseHeight = height;
  13568. depthTexture.width = width;
  13569. depthTexture.height = height;
  13570. depthTexture.isReady = true;
  13571. depthTexture.samples = 1;
  13572. depthTexture.generateMipMaps = generateMipMaps;
  13573. depthTexture.samplingMode = gl.NEAREST;
  13574. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13575. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13576. textures.push(depthTexture);
  13577. this._internalTexturesCache.push(depthTexture);
  13578. }
  13579. gl.drawBuffers(attachments);
  13580. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13581. this.bindUnboundFramebuffer(null);
  13582. this.resetTextureCache();
  13583. return textures;
  13584. };
  13585. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13586. if (samples === void 0) { samples = 1; }
  13587. var depthStencilBuffer = null;
  13588. var gl = this._gl;
  13589. // Create the depth/stencil buffer
  13590. if (generateStencilBuffer) {
  13591. depthStencilBuffer = gl.createRenderbuffer();
  13592. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13593. if (samples > 1) {
  13594. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13595. }
  13596. else {
  13597. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13598. }
  13599. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13600. }
  13601. else if (generateDepthBuffer) {
  13602. depthStencilBuffer = gl.createRenderbuffer();
  13603. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13604. if (samples > 1) {
  13605. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13606. }
  13607. else {
  13608. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13609. }
  13610. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13611. }
  13612. return depthStencilBuffer;
  13613. };
  13614. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13615. if (this.webGLVersion < 2 || !texture) {
  13616. return 1;
  13617. }
  13618. if (texture.samples === samples) {
  13619. return samples;
  13620. }
  13621. var gl = this._gl;
  13622. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13623. // Dispose previous render buffers
  13624. if (texture._depthStencilBuffer) {
  13625. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13626. texture._depthStencilBuffer = null;
  13627. }
  13628. if (texture._MSAAFramebuffer) {
  13629. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13630. texture._MSAAFramebuffer = null;
  13631. }
  13632. if (texture._MSAARenderBuffer) {
  13633. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13634. texture._MSAARenderBuffer = null;
  13635. }
  13636. if (samples > 1) {
  13637. var framebuffer = gl.createFramebuffer();
  13638. if (!framebuffer) {
  13639. throw new Error("Unable to create multi sampled framebuffer");
  13640. }
  13641. texture._MSAAFramebuffer = framebuffer;
  13642. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13643. var colorRenderbuffer = gl.createRenderbuffer();
  13644. if (!colorRenderbuffer) {
  13645. throw new Error("Unable to create multi sampled framebuffer");
  13646. }
  13647. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13648. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13649. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13650. texture._MSAARenderBuffer = colorRenderbuffer;
  13651. }
  13652. else {
  13653. this.bindUnboundFramebuffer(texture._framebuffer);
  13654. }
  13655. texture.samples = samples;
  13656. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13657. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13658. this.bindUnboundFramebuffer(null);
  13659. return samples;
  13660. };
  13661. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13662. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13663. return 1;
  13664. }
  13665. if (textures[0].samples === samples) {
  13666. return samples;
  13667. }
  13668. var gl = this._gl;
  13669. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13670. // Dispose previous render buffers
  13671. if (textures[0]._depthStencilBuffer) {
  13672. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13673. textures[0]._depthStencilBuffer = null;
  13674. }
  13675. if (textures[0]._MSAAFramebuffer) {
  13676. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13677. textures[0]._MSAAFramebuffer = null;
  13678. }
  13679. for (var i = 0; i < textures.length; i++) {
  13680. if (textures[i]._MSAARenderBuffer) {
  13681. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13682. textures[i]._MSAARenderBuffer = null;
  13683. }
  13684. }
  13685. if (samples > 1) {
  13686. var framebuffer = gl.createFramebuffer();
  13687. if (!framebuffer) {
  13688. throw new Error("Unable to create multi sampled framebuffer");
  13689. }
  13690. this.bindUnboundFramebuffer(framebuffer);
  13691. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13692. var attachments = [];
  13693. for (var i = 0; i < textures.length; i++) {
  13694. var texture = textures[i];
  13695. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13696. var colorRenderbuffer = gl.createRenderbuffer();
  13697. if (!colorRenderbuffer) {
  13698. throw new Error("Unable to create multi sampled framebuffer");
  13699. }
  13700. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13701. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13702. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13703. texture._MSAAFramebuffer = framebuffer;
  13704. texture._MSAARenderBuffer = colorRenderbuffer;
  13705. texture.samples = samples;
  13706. texture._depthStencilBuffer = depthStencilBuffer;
  13707. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13708. attachments.push(attachment);
  13709. }
  13710. gl.drawBuffers(attachments);
  13711. }
  13712. else {
  13713. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13714. }
  13715. this.bindUnboundFramebuffer(null);
  13716. return samples;
  13717. };
  13718. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13719. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13720. };
  13721. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13722. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13723. };
  13724. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13725. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13726. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13727. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13728. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13729. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13730. }
  13731. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13732. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13733. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13734. }
  13735. var gl = this._gl;
  13736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13737. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13738. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13739. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13740. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13741. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13742. }
  13743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13746. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13747. for (var face = 0; face < 6; face++) {
  13748. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13749. }
  13750. // Create the framebuffer
  13751. var framebuffer = gl.createFramebuffer();
  13752. this.bindUnboundFramebuffer(framebuffer);
  13753. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13754. // MipMaps
  13755. if (fullOptions.generateMipMaps) {
  13756. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13757. }
  13758. // Unbind
  13759. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13760. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13761. this.bindUnboundFramebuffer(null);
  13762. texture._framebuffer = framebuffer;
  13763. texture.width = size;
  13764. texture.height = size;
  13765. texture.isReady = true;
  13766. texture.isCube = true;
  13767. texture.samples = 1;
  13768. texture.generateMipMaps = fullOptions.generateMipMaps;
  13769. texture.samplingMode = fullOptions.samplingMode;
  13770. texture.type = fullOptions.type;
  13771. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13772. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13773. this._internalTexturesCache.push(texture);
  13774. return texture;
  13775. };
  13776. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13777. var _this = this;
  13778. if (onLoad === void 0) { onLoad = null; }
  13779. if (onError === void 0) { onError = null; }
  13780. if (forcedExtension === void 0) { forcedExtension = null; }
  13781. var callback = function (loadData) {
  13782. if (!loadData) {
  13783. if (onLoad) {
  13784. onLoad(null);
  13785. }
  13786. return;
  13787. }
  13788. var texture = loadData.texture;
  13789. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13790. texture._lodGenerationScale = scale;
  13791. texture._lodGenerationOffset = offset;
  13792. if (_this._caps.textureLOD) {
  13793. // Do not add extra process if texture lod is supported.
  13794. if (onLoad) {
  13795. onLoad(texture);
  13796. }
  13797. return;
  13798. }
  13799. var mipSlices = 3;
  13800. var gl = _this._gl;
  13801. var width = loadData.width;
  13802. if (!width) {
  13803. return;
  13804. }
  13805. var textures = [];
  13806. for (var i = 0; i < mipSlices; i++) {
  13807. //compute LOD from even spacing in smoothness (matching shader calculation)
  13808. var smoothness = i / (mipSlices - 1);
  13809. var roughness = 1 - smoothness;
  13810. var minLODIndex = offset; // roughness = 0
  13811. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13812. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13813. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13814. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13815. glTextureFromLod.isCube = true;
  13816. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13821. if (loadData.isDDS) {
  13822. var info = loadData.info;
  13823. var data = loadData.data;
  13824. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13825. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13826. }
  13827. else {
  13828. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13829. }
  13830. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13831. // Wrap in a base texture for easy binding.
  13832. var lodTexture = new BABYLON.BaseTexture(scene);
  13833. lodTexture.isCube = true;
  13834. lodTexture._texture = glTextureFromLod;
  13835. glTextureFromLod.isReady = true;
  13836. textures.push(lodTexture);
  13837. }
  13838. texture._lodTextureHigh = textures[2];
  13839. texture._lodTextureMid = textures[1];
  13840. texture._lodTextureLow = textures[0];
  13841. if (onLoad) {
  13842. onLoad(texture);
  13843. }
  13844. };
  13845. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13846. };
  13847. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13848. var _this = this;
  13849. if (onLoad === void 0) { onLoad = null; }
  13850. if (onError === void 0) { onError = null; }
  13851. if (forcedExtension === void 0) { forcedExtension = null; }
  13852. var gl = this._gl;
  13853. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13854. texture.isCube = true;
  13855. texture.url = rootUrl;
  13856. texture.generateMipMaps = !noMipmap;
  13857. if (!this._doNotHandleContextLost) {
  13858. texture._extension = forcedExtension;
  13859. texture._files = files;
  13860. }
  13861. var isKTX = false;
  13862. var isDDS = false;
  13863. var lastDot = rootUrl.lastIndexOf('.');
  13864. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13865. if (this._textureFormatInUse) {
  13866. extension = this._textureFormatInUse;
  13867. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13868. isKTX = true;
  13869. }
  13870. else {
  13871. isDDS = (extension === ".dds");
  13872. }
  13873. var onerror = function (request, exception) {
  13874. if (onError && request) {
  13875. onError(request.status + " " + request.statusText, exception);
  13876. }
  13877. };
  13878. if (isKTX) {
  13879. this._loadFile(rootUrl, function (data) {
  13880. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13881. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13882. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13883. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13884. ktx.uploadLevels(_this._gl, !noMipmap);
  13885. _this.setCubeMapTextureParams(gl, loadMipmap);
  13886. texture.width = ktx.pixelWidth;
  13887. texture.height = ktx.pixelHeight;
  13888. texture.isReady = true;
  13889. }, undefined, undefined, true, onerror);
  13890. }
  13891. else if (isDDS) {
  13892. if (files && files.length === 6) {
  13893. this._cascadeLoadFiles(scene, function (imgs) {
  13894. var info;
  13895. var loadMipmap = false;
  13896. var width = 0;
  13897. for (var index = 0; index < imgs.length; index++) {
  13898. var data = imgs[index];
  13899. info = BABYLON.DDSTools.GetDDSInfo(data);
  13900. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13901. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13902. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13903. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13904. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13905. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13906. }
  13907. texture.width = info.width;
  13908. texture.height = info.height;
  13909. texture.type = info.textureType;
  13910. width = info.width;
  13911. }
  13912. _this.setCubeMapTextureParams(gl, loadMipmap);
  13913. texture.isReady = true;
  13914. if (onLoad) {
  13915. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13916. }
  13917. }, files, onError);
  13918. }
  13919. else {
  13920. this._loadFile(rootUrl, function (data) {
  13921. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13922. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13923. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13924. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13925. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13926. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13927. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13928. }
  13929. _this.setCubeMapTextureParams(gl, loadMipmap);
  13930. texture.width = info.width;
  13931. texture.height = info.height;
  13932. texture.isReady = true;
  13933. texture.type = info.textureType;
  13934. if (onLoad) {
  13935. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13936. }
  13937. }, undefined, undefined, true, onerror);
  13938. }
  13939. }
  13940. else {
  13941. if (!files) {
  13942. throw new Error("Cannot load cubemap because files were not defined");
  13943. }
  13944. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13945. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13946. var height = width;
  13947. _this._prepareWorkingCanvas();
  13948. if (!_this._workingCanvas || !_this._workingContext) {
  13949. return;
  13950. }
  13951. _this._workingCanvas.width = width;
  13952. _this._workingCanvas.height = height;
  13953. var faces = [
  13954. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13955. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13956. ];
  13957. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13958. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13959. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13960. for (var index = 0; index < faces.length; index++) {
  13961. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13962. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13963. }
  13964. if (!noMipmap) {
  13965. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13966. }
  13967. _this.setCubeMapTextureParams(gl, !noMipmap);
  13968. texture.width = width;
  13969. texture.height = height;
  13970. texture.isReady = true;
  13971. if (format) {
  13972. texture.format = format;
  13973. }
  13974. texture.onLoadedObservable.notifyObservers(texture);
  13975. texture.onLoadedObservable.clear();
  13976. if (onLoad) {
  13977. onLoad();
  13978. }
  13979. }, files, onError);
  13980. }
  13981. this._internalTexturesCache.push(texture);
  13982. return texture;
  13983. };
  13984. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13989. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13990. // this.resetTextureCache();
  13991. };
  13992. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13993. if (compression === void 0) { compression = null; }
  13994. if (level === void 0) { level = 0; }
  13995. texture._bufferViewArray = data;
  13996. texture.format = format;
  13997. texture.type = type;
  13998. texture.invertY = invertY;
  13999. texture._compression = compression;
  14000. var gl = this._gl;
  14001. var textureType = this._getWebGLTextureType(type);
  14002. var internalFormat = this._getInternalFormat(format);
  14003. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14004. var needConversion = false;
  14005. if (internalFormat === gl.RGB) {
  14006. internalFormat = gl.RGBA;
  14007. needConversion = true;
  14008. }
  14009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14010. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14011. if (texture.width % 4 !== 0) {
  14012. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14013. }
  14014. // Data are known to be in +X +Y +Z -X -Y -Z
  14015. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14016. var faceData = data[faceIndex];
  14017. if (compression) {
  14018. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14019. }
  14020. else {
  14021. if (needConversion) {
  14022. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14023. }
  14024. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14025. }
  14026. }
  14027. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14028. if (isPot && texture.generateMipMaps && level === 0) {
  14029. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14030. }
  14031. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14032. // this.resetTextureCache();
  14033. texture.isReady = true;
  14034. };
  14035. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14036. if (compression === void 0) { compression = null; }
  14037. var gl = this._gl;
  14038. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14039. texture.isCube = true;
  14040. texture.generateMipMaps = generateMipMaps;
  14041. texture.format = format;
  14042. texture.type = type;
  14043. if (!this._doNotHandleContextLost) {
  14044. texture._bufferViewArray = data;
  14045. }
  14046. var textureType = this._getWebGLTextureType(type);
  14047. var internalFormat = this._getInternalFormat(format);
  14048. if (internalFormat === gl.RGB) {
  14049. internalFormat = gl.RGBA;
  14050. }
  14051. var width = size;
  14052. var height = width;
  14053. texture.width = width;
  14054. texture.height = height;
  14055. // Double check on POT to generate Mips.
  14056. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14057. if (!isPot) {
  14058. generateMipMaps = false;
  14059. }
  14060. // Upload data if needed. The texture won't be ready until then.
  14061. if (data) {
  14062. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14063. }
  14064. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14065. // Filters
  14066. if (data && generateMipMaps) {
  14067. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14068. }
  14069. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14072. }
  14073. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14076. }
  14077. else {
  14078. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14081. }
  14082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14085. return texture;
  14086. };
  14087. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14088. var _this = this;
  14089. if (onLoad === void 0) { onLoad = null; }
  14090. if (onError === void 0) { onError = null; }
  14091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14092. if (invertY === void 0) { invertY = false; }
  14093. var gl = this._gl;
  14094. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14095. scene._addPendingData(texture);
  14096. texture.url = url;
  14097. this._internalTexturesCache.push(texture);
  14098. var onerror = function (request, exception) {
  14099. scene._removePendingData(texture);
  14100. if (onError && request) {
  14101. onError(request.status + " " + request.statusText, exception);
  14102. }
  14103. };
  14104. var internalCallback = function (data) {
  14105. var width = texture.width;
  14106. var faceDataArrays = callback(data);
  14107. if (!faceDataArrays) {
  14108. return;
  14109. }
  14110. if (mipmmapGenerator) {
  14111. var textureType = _this._getWebGLTextureType(type);
  14112. var internalFormat = _this._getInternalFormat(format);
  14113. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14114. var needConversion = false;
  14115. if (internalFormat === gl.RGB) {
  14116. internalFormat = gl.RGBA;
  14117. needConversion = true;
  14118. }
  14119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14120. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14121. var mipData = mipmmapGenerator(faceDataArrays);
  14122. for (var level = 0; level < mipData.length; level++) {
  14123. var mipSize = width >> level;
  14124. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14125. var mipFaceData = mipData[level][faceIndex];
  14126. if (needConversion) {
  14127. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14128. }
  14129. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14130. }
  14131. }
  14132. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14133. }
  14134. else {
  14135. texture.generateMipMaps = !noMipmap;
  14136. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14137. }
  14138. texture.isReady = true;
  14139. // this.resetTextureCache();
  14140. scene._removePendingData(texture);
  14141. if (onLoad) {
  14142. onLoad();
  14143. }
  14144. };
  14145. this._loadFile(url, function (data) {
  14146. internalCallback(data);
  14147. }, undefined, scene.database, true, onerror);
  14148. return texture;
  14149. };
  14150. ;
  14151. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14152. if (compression === void 0) { compression = null; }
  14153. var internalFormat = this._getInternalFormat(format);
  14154. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14155. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14156. if (!this._doNotHandleContextLost) {
  14157. texture._bufferView = data;
  14158. texture.format = format;
  14159. texture.invertY = invertY;
  14160. texture._compression = compression;
  14161. }
  14162. if (texture.width % 4 !== 0) {
  14163. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14164. }
  14165. if (compression && data) {
  14166. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14167. }
  14168. else {
  14169. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14170. }
  14171. if (texture.generateMipMaps) {
  14172. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14173. }
  14174. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14175. // this.resetTextureCache();
  14176. texture.isReady = true;
  14177. };
  14178. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14179. if (compression === void 0) { compression = null; }
  14180. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14181. texture.baseWidth = width;
  14182. texture.baseHeight = height;
  14183. texture.baseDepth = depth;
  14184. texture.width = width;
  14185. texture.height = height;
  14186. texture.depth = depth;
  14187. texture.format = format;
  14188. texture.generateMipMaps = generateMipMaps;
  14189. texture.samplingMode = samplingMode;
  14190. texture.is3D = true;
  14191. if (!this._doNotHandleContextLost) {
  14192. texture._bufferView = data;
  14193. }
  14194. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14195. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14196. // Filters
  14197. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14198. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14199. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14200. if (generateMipMaps) {
  14201. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14202. }
  14203. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14204. this._internalTexturesCache.push(texture);
  14205. return texture;
  14206. };
  14207. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14208. var gl = this._gl;
  14209. if (!gl) {
  14210. return;
  14211. }
  14212. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14215. if (!noMipmap && !isCompressed) {
  14216. gl.generateMipmap(gl.TEXTURE_2D);
  14217. }
  14218. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14219. // this.resetTextureCache();
  14220. if (scene) {
  14221. scene._removePendingData(texture);
  14222. }
  14223. texture.onLoadedObservable.notifyObservers(texture);
  14224. texture.onLoadedObservable.clear();
  14225. };
  14226. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14227. var _this = this;
  14228. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14229. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14230. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14231. var gl = this._gl;
  14232. if (!gl) {
  14233. return;
  14234. }
  14235. if (!texture._webGLTexture) {
  14236. // this.resetTextureCache();
  14237. if (scene) {
  14238. scene._removePendingData(texture);
  14239. }
  14240. return;
  14241. }
  14242. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14243. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14244. texture.baseWidth = width;
  14245. texture.baseHeight = height;
  14246. texture.width = potWidth;
  14247. texture.height = potHeight;
  14248. texture.isReady = true;
  14249. if (processFunction(potWidth, potHeight, function () {
  14250. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14251. })) {
  14252. // Returning as texture needs extra async steps
  14253. return;
  14254. }
  14255. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14256. };
  14257. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14258. // Create new RGBA data container.
  14259. var rgbaData;
  14260. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14261. rgbaData = new Float32Array(width * height * 4);
  14262. }
  14263. else {
  14264. rgbaData = new Uint32Array(width * height * 4);
  14265. }
  14266. // Convert each pixel.
  14267. for (var x = 0; x < width; x++) {
  14268. for (var y = 0; y < height; y++) {
  14269. var index = (y * width + x) * 3;
  14270. var newIndex = (y * width + x) * 4;
  14271. // Map Old Value to new value.
  14272. rgbaData[newIndex + 0] = rgbData[index + 0];
  14273. rgbaData[newIndex + 1] = rgbData[index + 1];
  14274. rgbaData[newIndex + 2] = rgbData[index + 2];
  14275. // Add fully opaque alpha channel.
  14276. rgbaData[newIndex + 3] = 1;
  14277. }
  14278. }
  14279. return rgbaData;
  14280. };
  14281. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14282. var gl = this._gl;
  14283. if (texture._framebuffer) {
  14284. gl.deleteFramebuffer(texture._framebuffer);
  14285. texture._framebuffer = null;
  14286. }
  14287. if (texture._depthStencilBuffer) {
  14288. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14289. texture._depthStencilBuffer = null;
  14290. }
  14291. if (texture._MSAAFramebuffer) {
  14292. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14293. texture._MSAAFramebuffer = null;
  14294. }
  14295. if (texture._MSAARenderBuffer) {
  14296. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14297. texture._MSAARenderBuffer = null;
  14298. }
  14299. };
  14300. Engine.prototype._releaseTexture = function (texture) {
  14301. var gl = this._gl;
  14302. this._releaseFramebufferObjects(texture);
  14303. gl.deleteTexture(texture._webGLTexture);
  14304. // Unbind channels
  14305. this.unbindAllTextures();
  14306. var index = this._internalTexturesCache.indexOf(texture);
  14307. if (index !== -1) {
  14308. this._internalTexturesCache.splice(index, 1);
  14309. }
  14310. // Integrated fixed lod samplers.
  14311. if (texture._lodTextureHigh) {
  14312. texture._lodTextureHigh.dispose();
  14313. }
  14314. if (texture._lodTextureMid) {
  14315. texture._lodTextureMid.dispose();
  14316. }
  14317. if (texture._lodTextureLow) {
  14318. texture._lodTextureLow.dispose();
  14319. }
  14320. };
  14321. Engine.prototype.setProgram = function (program) {
  14322. if (this._currentProgram !== program) {
  14323. this._gl.useProgram(program);
  14324. this._currentProgram = program;
  14325. }
  14326. };
  14327. Engine.prototype.bindSamplers = function (effect) {
  14328. this.setProgram(effect.getProgram());
  14329. var samplers = effect.getSamplers();
  14330. for (var index = 0; index < samplers.length; index++) {
  14331. var uniform = effect.getUniform(samplers[index]);
  14332. if (uniform) {
  14333. this._boundUniforms[index] = uniform;
  14334. }
  14335. }
  14336. this._currentEffect = null;
  14337. };
  14338. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14339. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14340. return;
  14341. }
  14342. // Remove
  14343. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14344. // Bind last to it
  14345. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14346. // Bind to dummy
  14347. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14348. };
  14349. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14350. if (!internalTexture) {
  14351. return -1;
  14352. }
  14353. internalTexture._initialSlot = channel;
  14354. if (this.disableTextureBindingOptimization) {
  14355. if (channel !== internalTexture._designatedSlot) {
  14356. this._textureCollisions.addCount(1, false);
  14357. }
  14358. }
  14359. else {
  14360. if (channel !== internalTexture._designatedSlot) {
  14361. if (internalTexture._designatedSlot > -1) {
  14362. return internalTexture._designatedSlot;
  14363. }
  14364. else {
  14365. // No slot for this texture, let's pick a new one (if we find a free slot)
  14366. if (this._nextFreeTextureSlots.length) {
  14367. return this._nextFreeTextureSlots[0];
  14368. }
  14369. // We need to recycle the oldest bound texture, sorry.
  14370. this._textureCollisions.addCount(1, false);
  14371. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14372. }
  14373. }
  14374. }
  14375. return channel;
  14376. };
  14377. Engine.prototype._linkTrackers = function (previous, next) {
  14378. previous.next = next;
  14379. next.previous = previous;
  14380. };
  14381. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14382. var currentSlot = internalTexture._designatedSlot;
  14383. if (currentSlot === -1) {
  14384. return -1;
  14385. }
  14386. internalTexture._designatedSlot = -1;
  14387. if (this.disableTextureBindingOptimization) {
  14388. return -1;
  14389. }
  14390. // Remove from bound list
  14391. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14392. // Free the slot
  14393. this._boundTexturesCache[currentSlot] = null;
  14394. this._nextFreeTextureSlots.push(currentSlot);
  14395. return currentSlot;
  14396. };
  14397. Engine.prototype._activateCurrentTexture = function () {
  14398. if (this._currentTextureChannel !== this._activeChannel) {
  14399. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14400. this._currentTextureChannel = this._activeChannel;
  14401. }
  14402. };
  14403. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14404. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14405. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14406. this._activeChannel = texture._designatedSlot;
  14407. }
  14408. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14409. var isTextureForRendering = texture && texture._initialSlot > -1;
  14410. if (currentTextureBound !== texture) {
  14411. if (currentTextureBound) {
  14412. this._removeDesignatedSlot(currentTextureBound);
  14413. }
  14414. this._activateCurrentTexture();
  14415. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14416. this._boundTexturesCache[this._activeChannel] = texture;
  14417. if (texture) {
  14418. if (!this.disableTextureBindingOptimization) {
  14419. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14420. if (slotIndex > -1) {
  14421. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14422. }
  14423. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14424. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14425. }
  14426. texture._designatedSlot = this._activeChannel;
  14427. }
  14428. }
  14429. else if (forTextureDataUpdate) {
  14430. this._activateCurrentTexture();
  14431. }
  14432. if (isTextureForRendering && !forTextureDataUpdate) {
  14433. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14434. }
  14435. };
  14436. Engine.prototype._bindTexture = function (channel, texture) {
  14437. if (channel < 0) {
  14438. return;
  14439. }
  14440. if (texture) {
  14441. channel = this._getCorrectTextureChannel(channel, texture);
  14442. }
  14443. this._activeChannel = channel;
  14444. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14445. };
  14446. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14447. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14448. };
  14449. Engine.prototype.unbindAllTextures = function () {
  14450. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14451. this._activeChannel = channel;
  14452. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14453. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14454. if (this.webGLVersion > 1) {
  14455. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14456. }
  14457. }
  14458. };
  14459. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14460. if (channel < 0) {
  14461. return;
  14462. }
  14463. if (uniform) {
  14464. this._boundUniforms[channel] = uniform;
  14465. }
  14466. this._setTexture(channel, texture);
  14467. };
  14468. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14469. var uniform = this._boundUniforms[sourceSlot];
  14470. if (uniform._currentState === destination) {
  14471. return;
  14472. }
  14473. this._gl.uniform1i(uniform, destination);
  14474. uniform._currentState = destination;
  14475. };
  14476. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14477. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14478. // Not ready?
  14479. if (!texture) {
  14480. if (this._boundTexturesCache[channel] != null) {
  14481. this._activeChannel = channel;
  14482. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14483. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14484. if (this.webGLVersion > 1) {
  14485. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14486. }
  14487. }
  14488. return false;
  14489. }
  14490. // Video
  14491. if (texture.video) {
  14492. this._activeChannel = channel;
  14493. texture.update();
  14494. }
  14495. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14496. texture.delayLoad();
  14497. return false;
  14498. }
  14499. var internalTexture;
  14500. if (texture.isReady()) {
  14501. internalTexture = texture.getInternalTexture();
  14502. }
  14503. else if (texture.isCube) {
  14504. internalTexture = this.emptyCubeTexture;
  14505. }
  14506. else if (texture.is3D) {
  14507. internalTexture = this.emptyTexture3D;
  14508. }
  14509. else {
  14510. internalTexture = this.emptyTexture;
  14511. }
  14512. if (!isPartOfTextureArray) {
  14513. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14514. }
  14515. if (this._boundTexturesCache[channel] === internalTexture) {
  14516. this._moveBoundTextureOnTop(internalTexture);
  14517. if (!isPartOfTextureArray) {
  14518. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14519. }
  14520. return false;
  14521. }
  14522. this._activeChannel = channel;
  14523. if (internalTexture && internalTexture.is3D) {
  14524. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14525. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14526. internalTexture._cachedWrapU = texture.wrapU;
  14527. switch (texture.wrapU) {
  14528. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14529. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14530. break;
  14531. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14532. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14533. break;
  14534. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14535. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14536. break;
  14537. }
  14538. }
  14539. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14540. internalTexture._cachedWrapV = texture.wrapV;
  14541. switch (texture.wrapV) {
  14542. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14543. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14544. break;
  14545. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14546. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14547. break;
  14548. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14549. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14550. break;
  14551. }
  14552. }
  14553. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14554. internalTexture._cachedWrapR = texture.wrapR;
  14555. switch (texture.wrapR) {
  14556. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14557. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14558. break;
  14559. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14560. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14561. break;
  14562. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14563. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14564. break;
  14565. }
  14566. }
  14567. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14568. }
  14569. else if (internalTexture && internalTexture.isCube) {
  14570. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14571. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14572. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14573. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14574. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14575. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14576. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14577. }
  14578. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14579. }
  14580. else {
  14581. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14582. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14583. internalTexture._cachedWrapU = texture.wrapU;
  14584. switch (texture.wrapU) {
  14585. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14586. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14587. break;
  14588. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14589. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14590. break;
  14591. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14592. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14593. break;
  14594. }
  14595. }
  14596. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14597. internalTexture._cachedWrapV = texture.wrapV;
  14598. switch (texture.wrapV) {
  14599. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14601. break;
  14602. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14604. break;
  14605. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14606. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14607. break;
  14608. }
  14609. }
  14610. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14611. }
  14612. return true;
  14613. };
  14614. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14615. if (channel < 0 || !uniform) {
  14616. return;
  14617. }
  14618. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14619. this._textureUnits = new Int32Array(textures.length);
  14620. }
  14621. for (var i = 0; i < textures.length; i++) {
  14622. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14623. }
  14624. this._gl.uniform1iv(uniform, this._textureUnits);
  14625. for (var index = 0; index < textures.length; index++) {
  14626. this._setTexture(this._textureUnits[index], textures[index], true);
  14627. }
  14628. };
  14629. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14630. var internalTexture = texture.getInternalTexture();
  14631. if (!internalTexture) {
  14632. return;
  14633. }
  14634. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14635. var value = texture.anisotropicFilteringLevel;
  14636. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14637. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14638. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14639. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14640. }
  14641. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14642. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14643. internalTexture._cachedAnisotropicFilteringLevel = value;
  14644. }
  14645. };
  14646. Engine.prototype.readPixels = function (x, y, width, height) {
  14647. var data = new Uint8Array(height * width * 4);
  14648. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14649. return data;
  14650. };
  14651. /**
  14652. * Add an externaly attached data from its key.
  14653. * This method call will fail and return false, if such key already exists.
  14654. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14655. * @param key the unique key that identifies the data
  14656. * @param data the data object to associate to the key for this Engine instance
  14657. * @return true if no such key were already present and the data was added successfully, false otherwise
  14658. */
  14659. Engine.prototype.addExternalData = function (key, data) {
  14660. if (!this._externalData) {
  14661. this._externalData = new BABYLON.StringDictionary();
  14662. }
  14663. return this._externalData.add(key, data);
  14664. };
  14665. /**
  14666. * Get an externaly attached data from its key
  14667. * @param key the unique key that identifies the data
  14668. * @return the associated data, if present (can be null), or undefined if not present
  14669. */
  14670. Engine.prototype.getExternalData = function (key) {
  14671. if (!this._externalData) {
  14672. this._externalData = new BABYLON.StringDictionary();
  14673. }
  14674. return this._externalData.get(key);
  14675. };
  14676. /**
  14677. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14678. * @param key the unique key that identifies the data
  14679. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14680. * @return the associated data, can be null if the factory returned null.
  14681. */
  14682. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14683. if (!this._externalData) {
  14684. this._externalData = new BABYLON.StringDictionary();
  14685. }
  14686. return this._externalData.getOrAddWithFactory(key, factory);
  14687. };
  14688. /**
  14689. * Remove an externaly attached data from the Engine instance
  14690. * @param key the unique key that identifies the data
  14691. * @return true if the data was successfully removed, false if it doesn't exist
  14692. */
  14693. Engine.prototype.removeExternalData = function (key) {
  14694. if (!this._externalData) {
  14695. this._externalData = new BABYLON.StringDictionary();
  14696. }
  14697. return this._externalData.remove(key);
  14698. };
  14699. Engine.prototype.unbindAllAttributes = function () {
  14700. if (this._mustWipeVertexAttributes) {
  14701. this._mustWipeVertexAttributes = false;
  14702. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14703. this._gl.disableVertexAttribArray(i);
  14704. this._vertexAttribArraysEnabled[i] = false;
  14705. this._currentBufferPointers[i].active = false;
  14706. }
  14707. return;
  14708. }
  14709. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14710. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14711. continue;
  14712. }
  14713. this._gl.disableVertexAttribArray(i);
  14714. this._vertexAttribArraysEnabled[i] = false;
  14715. this._currentBufferPointers[i].active = false;
  14716. }
  14717. };
  14718. Engine.prototype.releaseEffects = function () {
  14719. for (var name in this._compiledEffects) {
  14720. this._deleteProgram(this._compiledEffects[name]._program);
  14721. }
  14722. this._compiledEffects = {};
  14723. };
  14724. // Dispose
  14725. Engine.prototype.dispose = function () {
  14726. this.hideLoadingUI();
  14727. this.stopRenderLoop();
  14728. // Release postProcesses
  14729. while (this.postProcesses.length) {
  14730. this.postProcesses[0].dispose();
  14731. }
  14732. // Empty texture
  14733. if (this._emptyTexture) {
  14734. this._releaseTexture(this._emptyTexture);
  14735. this._emptyTexture = null;
  14736. }
  14737. if (this._emptyCubeTexture) {
  14738. this._releaseTexture(this._emptyCubeTexture);
  14739. this._emptyCubeTexture = null;
  14740. }
  14741. // Rescale PP
  14742. if (this._rescalePostProcess) {
  14743. this._rescalePostProcess.dispose();
  14744. }
  14745. // Release scenes
  14746. while (this.scenes.length) {
  14747. this.scenes[0].dispose();
  14748. }
  14749. // Release audio engine
  14750. if (Engine.audioEngine) {
  14751. Engine.audioEngine.dispose();
  14752. }
  14753. // Release effects
  14754. this.releaseEffects();
  14755. // Unbind
  14756. this.unbindAllAttributes();
  14757. if (this._dummyFramebuffer) {
  14758. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14759. }
  14760. //WebVR
  14761. this.disableVR();
  14762. // Events
  14763. if (BABYLON.Tools.IsWindowObjectExist()) {
  14764. window.removeEventListener("blur", this._onBlur);
  14765. window.removeEventListener("focus", this._onFocus);
  14766. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14767. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14768. if (this._renderingCanvas) {
  14769. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14770. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14771. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14772. if (!this._doNotHandleContextLost) {
  14773. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14774. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14775. }
  14776. }
  14777. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14778. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14779. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14780. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14781. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14782. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14783. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14784. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14785. if (this._onVrDisplayConnect) {
  14786. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14787. if (this._onVrDisplayDisconnect) {
  14788. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14789. }
  14790. if (this._onVrDisplayPresentChange) {
  14791. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14792. }
  14793. this._onVrDisplayConnect = null;
  14794. this._onVrDisplayDisconnect = null;
  14795. }
  14796. }
  14797. // Remove from Instances
  14798. var index = Engine.Instances.indexOf(this);
  14799. if (index >= 0) {
  14800. Engine.Instances.splice(index, 1);
  14801. }
  14802. this._workingCanvas = null;
  14803. this._workingContext = null;
  14804. this._currentBufferPointers = [];
  14805. this._renderingCanvas = null;
  14806. this._currentProgram = null;
  14807. this.onResizeObservable.clear();
  14808. this.onCanvasBlurObservable.clear();
  14809. this.onCanvasFocusObservable.clear();
  14810. this.onCanvasPointerOutObservable.clear();
  14811. this.onBeginFrameObservable.clear();
  14812. this.onEndFrameObservable.clear();
  14813. BABYLON.Effect.ResetCache();
  14814. // Abort active requests
  14815. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14816. var request = _a[_i];
  14817. request.abort();
  14818. }
  14819. };
  14820. // Loading screen
  14821. Engine.prototype.displayLoadingUI = function () {
  14822. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14823. return;
  14824. }
  14825. var loadingScreen = this.loadingScreen;
  14826. if (loadingScreen) {
  14827. loadingScreen.displayLoadingUI();
  14828. }
  14829. };
  14830. Engine.prototype.hideLoadingUI = function () {
  14831. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14832. return;
  14833. }
  14834. var loadingScreen = this.loadingScreen;
  14835. if (loadingScreen) {
  14836. loadingScreen.hideLoadingUI();
  14837. }
  14838. };
  14839. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14840. get: function () {
  14841. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14842. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14843. return this._loadingScreen;
  14844. },
  14845. set: function (loadingScreen) {
  14846. this._loadingScreen = loadingScreen;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14852. set: function (text) {
  14853. this.loadingScreen.loadingUIText = text;
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14859. set: function (color) {
  14860. this.loadingScreen.loadingUIBackgroundColor = color;
  14861. },
  14862. enumerable: true,
  14863. configurable: true
  14864. });
  14865. Engine.prototype.attachContextLostEvent = function (callback) {
  14866. if (this._renderingCanvas) {
  14867. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14868. }
  14869. };
  14870. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14871. if (this._renderingCanvas) {
  14872. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14873. }
  14874. };
  14875. Engine.prototype.getVertexShaderSource = function (program) {
  14876. var shaders = this._gl.getAttachedShaders(program);
  14877. if (!shaders) {
  14878. return null;
  14879. }
  14880. return this._gl.getShaderSource(shaders[0]);
  14881. };
  14882. Engine.prototype.getFragmentShaderSource = function (program) {
  14883. var shaders = this._gl.getAttachedShaders(program);
  14884. if (!shaders) {
  14885. return null;
  14886. }
  14887. return this._gl.getShaderSource(shaders[1]);
  14888. };
  14889. Engine.prototype.getError = function () {
  14890. return this._gl.getError();
  14891. };
  14892. // FPS
  14893. Engine.prototype.getFps = function () {
  14894. return this._fps;
  14895. };
  14896. Engine.prototype.getDeltaTime = function () {
  14897. return this._deltaTime;
  14898. };
  14899. Engine.prototype._measureFps = function () {
  14900. this._performanceMonitor.sampleFrame();
  14901. this._fps = this._performanceMonitor.averageFPS;
  14902. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14903. };
  14904. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14905. if (faceIndex === void 0) { faceIndex = -1; }
  14906. var gl = this._gl;
  14907. if (!this._dummyFramebuffer) {
  14908. var dummy = gl.createFramebuffer();
  14909. if (!dummy) {
  14910. throw new Error("Unable to create dummy framebuffer");
  14911. }
  14912. this._dummyFramebuffer = dummy;
  14913. }
  14914. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14915. if (faceIndex > -1) {
  14916. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14917. }
  14918. else {
  14919. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14920. }
  14921. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14922. var buffer;
  14923. switch (readType) {
  14924. case gl.UNSIGNED_BYTE:
  14925. buffer = new Uint8Array(4 * width * height);
  14926. readType = gl.UNSIGNED_BYTE;
  14927. break;
  14928. default:
  14929. buffer = new Float32Array(4 * width * height);
  14930. readType = gl.FLOAT;
  14931. break;
  14932. }
  14933. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14934. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14935. return buffer;
  14936. };
  14937. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14938. if (this._webGLVersion > 1) {
  14939. return this._caps.colorBufferFloat;
  14940. }
  14941. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14942. };
  14943. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14944. if (this._webGLVersion > 1) {
  14945. return this._caps.colorBufferFloat;
  14946. }
  14947. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14948. };
  14949. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14950. Engine.prototype._canRenderToFramebuffer = function (type) {
  14951. var gl = this._gl;
  14952. //clear existing errors
  14953. while (gl.getError() !== gl.NO_ERROR) { }
  14954. var successful = true;
  14955. var texture = gl.createTexture();
  14956. gl.bindTexture(gl.TEXTURE_2D, texture);
  14957. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14958. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14959. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14960. var fb = gl.createFramebuffer();
  14961. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14962. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14963. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14964. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14965. successful = successful && (gl.getError() === gl.NO_ERROR);
  14966. //try render by clearing frame buffer's color buffer
  14967. if (successful) {
  14968. gl.clear(gl.COLOR_BUFFER_BIT);
  14969. successful = successful && (gl.getError() === gl.NO_ERROR);
  14970. }
  14971. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14972. if (successful) {
  14973. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14974. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14975. var readFormat = gl.RGBA;
  14976. var readType = gl.UNSIGNED_BYTE;
  14977. var buffer = new Uint8Array(4);
  14978. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14979. successful = successful && (gl.getError() === gl.NO_ERROR);
  14980. }
  14981. //clean up
  14982. gl.deleteTexture(texture);
  14983. gl.deleteFramebuffer(fb);
  14984. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14985. //clear accumulated errors
  14986. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14987. return successful;
  14988. };
  14989. Engine.prototype._getWebGLTextureType = function (type) {
  14990. if (type === Engine.TEXTURETYPE_FLOAT) {
  14991. return this._gl.FLOAT;
  14992. }
  14993. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14994. // Add Half Float Constant.
  14995. return this._gl.HALF_FLOAT_OES;
  14996. }
  14997. return this._gl.UNSIGNED_BYTE;
  14998. };
  14999. ;
  15000. /** @ignore */
  15001. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15002. if (this._webGLVersion === 1) {
  15003. return this._gl.RGBA;
  15004. }
  15005. if (type === Engine.TEXTURETYPE_FLOAT) {
  15006. if (format) {
  15007. switch (format) {
  15008. case Engine.TEXTUREFORMAT_R32F:
  15009. return this._gl.R32F;
  15010. case Engine.TEXTUREFORMAT_RG32F:
  15011. return this._gl.RG32F;
  15012. case Engine.TEXTUREFORMAT_RGB32F:
  15013. return this._gl.RGB32F;
  15014. }
  15015. }
  15016. return this._gl.RGBA32F;
  15017. }
  15018. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15019. return this._gl.RGBA16F;
  15020. }
  15021. return this._gl.RGBA;
  15022. };
  15023. ;
  15024. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15025. if (type === Engine.TEXTURETYPE_FLOAT) {
  15026. return this._gl.RGBA32F;
  15027. }
  15028. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15029. return this._gl.RGBA16F;
  15030. }
  15031. return this._gl.RGBA8;
  15032. };
  15033. ;
  15034. Engine.prototype.createQuery = function () {
  15035. return this._gl.createQuery();
  15036. };
  15037. Engine.prototype.deleteQuery = function (query) {
  15038. this._gl.deleteQuery(query);
  15039. return this;
  15040. };
  15041. Engine.prototype.isQueryResultAvailable = function (query) {
  15042. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15043. };
  15044. Engine.prototype.getQueryResult = function (query) {
  15045. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15046. };
  15047. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15048. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15049. this._gl.beginQuery(glAlgorithm, query);
  15050. return this;
  15051. };
  15052. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15053. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15054. this._gl.endQuery(glAlgorithm);
  15055. return this;
  15056. };
  15057. /* Time queries */
  15058. Engine.prototype._createTimeQuery = function () {
  15059. var timerQuery = this._caps.timerQuery;
  15060. if (timerQuery.createQueryEXT) {
  15061. return timerQuery.createQueryEXT();
  15062. }
  15063. return this.createQuery();
  15064. };
  15065. Engine.prototype._deleteTimeQuery = function (query) {
  15066. var timerQuery = this._caps.timerQuery;
  15067. if (timerQuery.deleteQueryEXT) {
  15068. timerQuery.deleteQueryEXT(query);
  15069. return;
  15070. }
  15071. this.deleteQuery(query);
  15072. };
  15073. Engine.prototype._getTimeQueryResult = function (query) {
  15074. var timerQuery = this._caps.timerQuery;
  15075. if (timerQuery.getQueryObjectEXT) {
  15076. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15077. }
  15078. return this.getQueryResult(query);
  15079. };
  15080. Engine.prototype._getTimeQueryAvailability = function (query) {
  15081. var timerQuery = this._caps.timerQuery;
  15082. if (timerQuery.getQueryObjectEXT) {
  15083. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15084. }
  15085. return this.isQueryResultAvailable(query);
  15086. };
  15087. Engine.prototype.startTimeQuery = function () {
  15088. var timerQuery = this._caps.timerQuery;
  15089. if (!timerQuery) {
  15090. return null;
  15091. }
  15092. var token = new BABYLON._TimeToken();
  15093. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15094. if (this._caps.canUseTimestampForTimerQuery) {
  15095. token._startTimeQuery = this._createTimeQuery();
  15096. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15097. }
  15098. else {
  15099. if (this._currentNonTimestampToken) {
  15100. return this._currentNonTimestampToken;
  15101. }
  15102. token._timeElapsedQuery = this._createTimeQuery();
  15103. if (timerQuery.beginQueryEXT) {
  15104. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15105. }
  15106. else {
  15107. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15108. }
  15109. this._currentNonTimestampToken = token;
  15110. }
  15111. return token;
  15112. };
  15113. Engine.prototype.endTimeQuery = function (token) {
  15114. var timerQuery = this._caps.timerQuery;
  15115. if (!timerQuery || !token) {
  15116. return -1;
  15117. }
  15118. if (this._caps.canUseTimestampForTimerQuery) {
  15119. if (!token._startTimeQuery) {
  15120. return -1;
  15121. }
  15122. if (!token._endTimeQuery) {
  15123. token._endTimeQuery = this._createTimeQuery();
  15124. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15125. }
  15126. }
  15127. else if (!token._timeElapsedQueryEnded) {
  15128. if (!token._timeElapsedQuery) {
  15129. return -1;
  15130. }
  15131. if (timerQuery.endQueryEXT) {
  15132. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15133. }
  15134. else {
  15135. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15136. }
  15137. token._timeElapsedQueryEnded = true;
  15138. }
  15139. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15140. var available = false;
  15141. if (token._endTimeQuery) {
  15142. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15143. }
  15144. else if (token._timeElapsedQuery) {
  15145. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15146. }
  15147. if (available && !disjoint) {
  15148. var result = 0;
  15149. if (this._caps.canUseTimestampForTimerQuery) {
  15150. if (!token._startTimeQuery || !token._endTimeQuery) {
  15151. return -1;
  15152. }
  15153. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15154. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15155. result = timeEnd - timeStart;
  15156. this._deleteTimeQuery(token._startTimeQuery);
  15157. this._deleteTimeQuery(token._endTimeQuery);
  15158. token._startTimeQuery = null;
  15159. token._endTimeQuery = null;
  15160. }
  15161. else {
  15162. if (!token._timeElapsedQuery) {
  15163. return -1;
  15164. }
  15165. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15166. this._deleteTimeQuery(token._timeElapsedQuery);
  15167. token._timeElapsedQuery = null;
  15168. token._timeElapsedQueryEnded = false;
  15169. this._currentNonTimestampToken = null;
  15170. }
  15171. return result;
  15172. }
  15173. return -1;
  15174. };
  15175. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15176. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15177. };
  15178. // Transform feedback
  15179. Engine.prototype.createTransformFeedback = function () {
  15180. return this._gl.createTransformFeedback();
  15181. };
  15182. Engine.prototype.deleteTransformFeedback = function (value) {
  15183. this._gl.deleteTransformFeedback(value);
  15184. };
  15185. Engine.prototype.bindTransformFeedback = function (value) {
  15186. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15187. };
  15188. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15189. if (usePoints === void 0) { usePoints = true; }
  15190. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15191. };
  15192. Engine.prototype.endTransformFeedback = function () {
  15193. this._gl.endTransformFeedback();
  15194. };
  15195. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15196. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15197. };
  15198. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15199. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15200. };
  15201. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15202. var _this = this;
  15203. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15204. this._activeRequests.push(request);
  15205. request.onCompleteObservable.add(function (request) {
  15206. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15207. });
  15208. return request;
  15209. };
  15210. /** @ignore */
  15211. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15212. var _this = this;
  15213. return new Promise(function (resolve, reject) {
  15214. _this._loadFile(url, function (data) {
  15215. resolve(data);
  15216. }, undefined, database, useArrayBuffer, function (request, exception) {
  15217. reject(exception);
  15218. });
  15219. });
  15220. };
  15221. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15222. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15223. var onload = function (data) {
  15224. loadedFiles[index] = data;
  15225. loadedFiles._internalCount++;
  15226. if (loadedFiles._internalCount === 6) {
  15227. onfinish(loadedFiles);
  15228. }
  15229. };
  15230. var onerror = function (request, exception) {
  15231. if (onErrorCallBack && request) {
  15232. onErrorCallBack(request.status + " " + request.statusText, exception);
  15233. }
  15234. };
  15235. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15236. };
  15237. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15238. if (onError === void 0) { onError = null; }
  15239. var loadedFiles = [];
  15240. loadedFiles._internalCount = 0;
  15241. for (var index = 0; index < 6; index++) {
  15242. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15243. }
  15244. };
  15245. // Statics
  15246. Engine.isSupported = function () {
  15247. try {
  15248. var tempcanvas = document.createElement("canvas");
  15249. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15250. return gl != null && !!window.WebGLRenderingContext;
  15251. }
  15252. catch (e) {
  15253. return false;
  15254. }
  15255. };
  15256. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15257. Engine.ExceptionList = [
  15258. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15259. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15260. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15261. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15262. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15263. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15264. ];
  15265. Engine.Instances = new Array();
  15266. // Const statics
  15267. Engine._ALPHA_DISABLE = 0;
  15268. Engine._ALPHA_ADD = 1;
  15269. Engine._ALPHA_COMBINE = 2;
  15270. Engine._ALPHA_SUBTRACT = 3;
  15271. Engine._ALPHA_MULTIPLY = 4;
  15272. Engine._ALPHA_MAXIMIZED = 5;
  15273. Engine._ALPHA_ONEONE = 6;
  15274. Engine._ALPHA_PREMULTIPLIED = 7;
  15275. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15276. Engine._ALPHA_INTERPOLATE = 9;
  15277. Engine._ALPHA_SCREENMODE = 10;
  15278. Engine._DELAYLOADSTATE_NONE = 0;
  15279. Engine._DELAYLOADSTATE_LOADED = 1;
  15280. Engine._DELAYLOADSTATE_LOADING = 2;
  15281. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15282. Engine._TEXTUREFORMAT_ALPHA = 0;
  15283. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15284. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15285. Engine._TEXTUREFORMAT_RGB = 4;
  15286. Engine._TEXTUREFORMAT_RGBA = 5;
  15287. Engine._TEXTUREFORMAT_R32F = 6;
  15288. Engine._TEXTUREFORMAT_RG32F = 7;
  15289. Engine._TEXTUREFORMAT_RGB32F = 8;
  15290. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15291. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15292. Engine._TEXTURETYPE_FLOAT = 1;
  15293. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15294. // Depht or Stencil test Constants.
  15295. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15296. 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.
  15297. 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.
  15298. 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.
  15299. 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.
  15300. 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.
  15301. 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.
  15302. 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.
  15303. // Stencil Actions Constants.
  15304. Engine._KEEP = 0x1E00;
  15305. Engine._REPLACE = 0x1E01;
  15306. Engine._INCR = 0x1E02;
  15307. Engine._DECR = 0x1E03;
  15308. Engine._INVERT = 0x150A;
  15309. Engine._INCR_WRAP = 0x8507;
  15310. Engine._DECR_WRAP = 0x8508;
  15311. // Texture rescaling mode
  15312. Engine._SCALEMODE_FLOOR = 1;
  15313. Engine._SCALEMODE_NEAREST = 2;
  15314. Engine._SCALEMODE_CEILING = 3;
  15315. // Updatable statics so stick with vars here
  15316. Engine.CollisionsEpsilon = 0.001;
  15317. Engine.CodeRepository = "src/";
  15318. Engine.ShadersRepository = "src/Shaders/";
  15319. return Engine;
  15320. }());
  15321. BABYLON.Engine = Engine;
  15322. })(BABYLON || (BABYLON = {}));
  15323. //# sourceMappingURL=babylon.engine.js.map
  15324. var BABYLON;
  15325. (function (BABYLON) {
  15326. /**
  15327. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15328. */
  15329. var Node = /** @class */ (function () {
  15330. /**
  15331. * Creates a new Node
  15332. * @param {string} name - the name and id to be given to this node
  15333. * @param {BABYLON.Scene} the scene this node will be added to
  15334. */
  15335. function Node(name, scene) {
  15336. if (scene === void 0) { scene = null; }
  15337. /**
  15338. * Gets or sets a string used to store user defined state for the node
  15339. */
  15340. this.state = "";
  15341. /**
  15342. * Gets or sets an object used to store user defined information for the node
  15343. */
  15344. this.metadata = null;
  15345. /**
  15346. * Gets or sets a boolean used to define if the node must be serialized
  15347. */
  15348. this.doNotSerialize = false;
  15349. /** @ignore */
  15350. this._isDisposed = false;
  15351. /**
  15352. * Gets a list of {BABYLON.Animation} associated with the node
  15353. */
  15354. this.animations = new Array();
  15355. this._ranges = {};
  15356. this._isEnabled = true;
  15357. this._isReady = true;
  15358. /** @ignore */
  15359. this._currentRenderId = -1;
  15360. this._parentRenderId = -1;
  15361. this._animationPropertiesOverride = null;
  15362. /**
  15363. * An event triggered when the mesh is disposed
  15364. * @type {BABYLON.Observable}
  15365. */
  15366. this.onDisposeObservable = new BABYLON.Observable();
  15367. // Behaviors
  15368. this._behaviors = new Array();
  15369. this.name = name;
  15370. this.id = name;
  15371. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15372. this.uniqueId = this._scene.getUniqueId();
  15373. this._initCache();
  15374. }
  15375. /**
  15376. * Gets a boolean indicating if the node has been disposed
  15377. * @returns true if the node was disposed
  15378. */
  15379. Node.prototype.isDisposed = function () {
  15380. return this._isDisposed;
  15381. };
  15382. Object.defineProperty(Node.prototype, "parent", {
  15383. get: function () {
  15384. return this._parentNode;
  15385. },
  15386. /**
  15387. * Gets or sets the parent of the node
  15388. */
  15389. set: function (parent) {
  15390. if (this._parentNode === parent) {
  15391. return;
  15392. }
  15393. // Remove self from list of children of parent
  15394. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15395. var index = this._parentNode._children.indexOf(this);
  15396. if (index !== -1) {
  15397. this._parentNode._children.splice(index, 1);
  15398. }
  15399. }
  15400. // Store new parent
  15401. this._parentNode = parent;
  15402. // Add as child to new parent
  15403. if (this._parentNode) {
  15404. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15405. this._parentNode._children = new Array();
  15406. }
  15407. this._parentNode._children.push(this);
  15408. }
  15409. },
  15410. enumerable: true,
  15411. configurable: true
  15412. });
  15413. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15414. /**
  15415. * Gets or sets the animation properties override
  15416. */
  15417. get: function () {
  15418. return this._animationPropertiesOverride;
  15419. },
  15420. set: function (value) {
  15421. this._animationPropertiesOverride = value;
  15422. },
  15423. enumerable: true,
  15424. configurable: true
  15425. });
  15426. /**
  15427. * Gets a string idenfifying the name of the class
  15428. * @returns "Node" string
  15429. */
  15430. Node.prototype.getClassName = function () {
  15431. return "Node";
  15432. };
  15433. Object.defineProperty(Node.prototype, "onDispose", {
  15434. /**
  15435. * Sets a callback that will be raised when the node will be disposed
  15436. */
  15437. set: function (callback) {
  15438. if (this._onDisposeObserver) {
  15439. this.onDisposeObservable.remove(this._onDisposeObserver);
  15440. }
  15441. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15442. },
  15443. enumerable: true,
  15444. configurable: true
  15445. });
  15446. /**
  15447. * Gets the scene of the node
  15448. * @returns a {BABYLON.Scene}
  15449. */
  15450. Node.prototype.getScene = function () {
  15451. return this._scene;
  15452. };
  15453. /**
  15454. * Gets the engine of the node
  15455. * @returns a {BABYLON.Engine}
  15456. */
  15457. Node.prototype.getEngine = function () {
  15458. return this._scene.getEngine();
  15459. };
  15460. /**
  15461. * Attach a behavior to the node
  15462. * @see http://doc.babylonjs.com/features/behaviour
  15463. * @param behavior defines the behavior to attach
  15464. * @returns the current Node
  15465. */
  15466. Node.prototype.addBehavior = function (behavior) {
  15467. var _this = this;
  15468. var index = this._behaviors.indexOf(behavior);
  15469. if (index !== -1) {
  15470. return this;
  15471. }
  15472. behavior.init();
  15473. if (this._scene.isLoading) {
  15474. // We defer the attach when the scene will be loaded
  15475. var observer = this._scene.onDataLoadedObservable.add(function () {
  15476. behavior.attach(_this);
  15477. setTimeout(function () {
  15478. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15479. _this._scene.onDataLoadedObservable.remove(observer);
  15480. }, 0);
  15481. });
  15482. }
  15483. else {
  15484. behavior.attach(this);
  15485. }
  15486. this._behaviors.push(behavior);
  15487. return this;
  15488. };
  15489. /**
  15490. * Remove an attached behavior
  15491. * @see http://doc.babylonjs.com/features/behaviour
  15492. * @param behavior defines the behavior to attach
  15493. * @returns the current Node
  15494. */
  15495. Node.prototype.removeBehavior = function (behavior) {
  15496. var index = this._behaviors.indexOf(behavior);
  15497. if (index === -1) {
  15498. return this;
  15499. }
  15500. this._behaviors[index].detach();
  15501. this._behaviors.splice(index, 1);
  15502. return this;
  15503. };
  15504. Object.defineProperty(Node.prototype, "behaviors", {
  15505. /**
  15506. * Gets the list of attached behaviors
  15507. * @see http://doc.babylonjs.com/features/behaviour
  15508. */
  15509. get: function () {
  15510. return this._behaviors;
  15511. },
  15512. enumerable: true,
  15513. configurable: true
  15514. });
  15515. /**
  15516. * Gets an attached behavior by name
  15517. * @param name defines the name of the behavior to look for
  15518. * @see http://doc.babylonjs.com/features/behaviour
  15519. * @returns null if behavior was not found else the requested behavior
  15520. */
  15521. Node.prototype.getBehaviorByName = function (name) {
  15522. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15523. var behavior = _a[_i];
  15524. if (behavior.name === name) {
  15525. return behavior;
  15526. }
  15527. }
  15528. return null;
  15529. };
  15530. /**
  15531. * Returns the world matrix of the node
  15532. * @returns a matrix containing the node's world matrix
  15533. */
  15534. Node.prototype.getWorldMatrix = function () {
  15535. return BABYLON.Matrix.Identity();
  15536. };
  15537. // override it in derived class if you add new variables to the cache
  15538. // and call the parent class method
  15539. /** @ignore */
  15540. Node.prototype._initCache = function () {
  15541. this._cache = {};
  15542. this._cache.parent = undefined;
  15543. };
  15544. /** @ignore */
  15545. Node.prototype.updateCache = function (force) {
  15546. if (!force && this.isSynchronized())
  15547. return;
  15548. this._cache.parent = this.parent;
  15549. this._updateCache();
  15550. };
  15551. // override it in derived class if you add new variables to the cache
  15552. // and call the parent class method if !ignoreParentClass
  15553. /** @ignore */
  15554. Node.prototype._updateCache = function (ignoreParentClass) {
  15555. };
  15556. // override it in derived class if you add new variables to the cache
  15557. /** @ignore */
  15558. Node.prototype._isSynchronized = function () {
  15559. return true;
  15560. };
  15561. /** @ignore */
  15562. Node.prototype._markSyncedWithParent = function () {
  15563. if (this.parent) {
  15564. this._parentRenderId = this.parent._currentRenderId;
  15565. }
  15566. };
  15567. /** @ignore */
  15568. Node.prototype.isSynchronizedWithParent = function () {
  15569. if (!this.parent) {
  15570. return true;
  15571. }
  15572. if (this._parentRenderId !== this.parent._currentRenderId) {
  15573. return false;
  15574. }
  15575. return this.parent.isSynchronized();
  15576. };
  15577. /** @ignore */
  15578. Node.prototype.isSynchronized = function (updateCache) {
  15579. var check = this.hasNewParent();
  15580. check = check || !this.isSynchronizedWithParent();
  15581. check = check || !this._isSynchronized();
  15582. if (updateCache)
  15583. this.updateCache(true);
  15584. return !check;
  15585. };
  15586. /** @ignore */
  15587. Node.prototype.hasNewParent = function (update) {
  15588. if (this._cache.parent === this.parent)
  15589. return false;
  15590. if (update)
  15591. this._cache.parent = this.parent;
  15592. return true;
  15593. };
  15594. /**
  15595. * Is this node ready to be used/rendered
  15596. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15597. * @return true if the node is ready
  15598. */
  15599. Node.prototype.isReady = function (completeCheck) {
  15600. if (completeCheck === void 0) { completeCheck = false; }
  15601. return this._isReady;
  15602. };
  15603. /**
  15604. * Is this node enabled?
  15605. * 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
  15606. * @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
  15607. * @return whether this node (and its parent) is enabled
  15608. * @see setEnabled
  15609. */
  15610. Node.prototype.isEnabled = function (checkAncestors) {
  15611. if (checkAncestors === void 0) { checkAncestors = true; }
  15612. if (checkAncestors === false) {
  15613. return this._isEnabled;
  15614. }
  15615. if (this._isEnabled === false) {
  15616. return false;
  15617. }
  15618. if (this.parent !== undefined && this.parent !== null) {
  15619. return this.parent.isEnabled(checkAncestors);
  15620. }
  15621. return true;
  15622. };
  15623. /**
  15624. * Set the enabled state of this node
  15625. * @param value defines the new enabled state
  15626. * @see isEnabled
  15627. */
  15628. Node.prototype.setEnabled = function (value) {
  15629. this._isEnabled = value;
  15630. };
  15631. /**
  15632. * Is this node a descendant of the given node?
  15633. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15634. * @param ancestor defines the parent node to inspect
  15635. * @see parent
  15636. * @returns a boolean indicating if this node is a descendant of the given node
  15637. */
  15638. Node.prototype.isDescendantOf = function (ancestor) {
  15639. if (this.parent) {
  15640. if (this.parent === ancestor) {
  15641. return true;
  15642. }
  15643. return this.parent.isDescendantOf(ancestor);
  15644. }
  15645. return false;
  15646. };
  15647. /** @ignore */
  15648. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15649. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15650. if (!this._children) {
  15651. return;
  15652. }
  15653. for (var index = 0; index < this._children.length; index++) {
  15654. var item = this._children[index];
  15655. if (!predicate || predicate(item)) {
  15656. results.push(item);
  15657. }
  15658. if (!directDescendantsOnly) {
  15659. item._getDescendants(results, false, predicate);
  15660. }
  15661. }
  15662. };
  15663. /**
  15664. * Will return all nodes that have this node as ascendant
  15665. * @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
  15666. * @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
  15667. * @return all children nodes of all types
  15668. */
  15669. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15670. var results = new Array();
  15671. this._getDescendants(results, directDescendantsOnly, predicate);
  15672. return results;
  15673. };
  15674. /**
  15675. * Get all child-meshes of this node
  15676. * @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
  15677. * @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
  15678. * @returns an array of {BABYLON.AbstractMesh}
  15679. */
  15680. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15681. var results = [];
  15682. this._getDescendants(results, directDescendantsOnly, function (node) {
  15683. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15684. });
  15685. return results;
  15686. };
  15687. /**
  15688. * Get all child-transformNodes of this node
  15689. * @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
  15690. * @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
  15691. * @returns an array of {BABYLON.TransformNode}
  15692. */
  15693. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15694. var results = [];
  15695. this._getDescendants(results, directDescendantsOnly, function (node) {
  15696. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15697. });
  15698. return results;
  15699. };
  15700. /**
  15701. * Get all direct children of this node
  15702. * @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
  15703. * @returns an array of {BABYLON.Node}
  15704. */
  15705. Node.prototype.getChildren = function (predicate) {
  15706. return this.getDescendants(true, predicate);
  15707. };
  15708. /** @ignore */
  15709. Node.prototype._setReady = function (state) {
  15710. if (state === this._isReady) {
  15711. return;
  15712. }
  15713. if (!state) {
  15714. this._isReady = false;
  15715. return;
  15716. }
  15717. this._isReady = true;
  15718. if (this.onReady) {
  15719. this.onReady(this);
  15720. }
  15721. };
  15722. /**
  15723. * Get an animation by name
  15724. * @param name defines the name of the animation to look for
  15725. * @returns null if not found else the requested animation
  15726. */
  15727. Node.prototype.getAnimationByName = function (name) {
  15728. for (var i = 0; i < this.animations.length; i++) {
  15729. var animation = this.animations[i];
  15730. if (animation.name === name) {
  15731. return animation;
  15732. }
  15733. }
  15734. return null;
  15735. };
  15736. /**
  15737. * Creates an animation range for this node
  15738. * @param name defines the name of the range
  15739. * @param from defines the starting key
  15740. * @param to defines the end key
  15741. */
  15742. Node.prototype.createAnimationRange = function (name, from, to) {
  15743. // check name not already in use
  15744. if (!this._ranges[name]) {
  15745. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15746. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15747. if (this.animations[i]) {
  15748. this.animations[i].createRange(name, from, to);
  15749. }
  15750. }
  15751. }
  15752. };
  15753. /**
  15754. * Delete a specific animation range
  15755. * @param name defines the name of the range to delete
  15756. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15757. */
  15758. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15759. if (deleteFrames === void 0) { deleteFrames = true; }
  15760. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15761. if (this.animations[i]) {
  15762. this.animations[i].deleteRange(name, deleteFrames);
  15763. }
  15764. }
  15765. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15766. };
  15767. /**
  15768. * Get an animation range by name
  15769. * @param name defines the name of the animation range to look for
  15770. * @returns null if not found else the requested animation range
  15771. */
  15772. Node.prototype.getAnimationRange = function (name) {
  15773. return this._ranges[name];
  15774. };
  15775. /**
  15776. * Will start the animation sequence
  15777. * @param name defines the range frames for animation sequence
  15778. * @param loop defines if the animation should loop (false by default)
  15779. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15780. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15781. * @returns the object created for this animation. If range does not exist, it will return null
  15782. */
  15783. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15784. var range = this.getAnimationRange(name);
  15785. if (!range) {
  15786. return null;
  15787. }
  15788. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15789. };
  15790. /**
  15791. * Serialize animation ranges into a JSON compatible object
  15792. * @returns serialization object
  15793. */
  15794. Node.prototype.serializeAnimationRanges = function () {
  15795. var serializationRanges = [];
  15796. for (var name in this._ranges) {
  15797. var localRange = this._ranges[name];
  15798. if (!localRange) {
  15799. continue;
  15800. }
  15801. var range = {};
  15802. range.name = name;
  15803. range.from = localRange.from;
  15804. range.to = localRange.to;
  15805. serializationRanges.push(range);
  15806. }
  15807. return serializationRanges;
  15808. };
  15809. /**
  15810. * Computes the world matrix of the node
  15811. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15812. * @returns the world matrix
  15813. */
  15814. Node.prototype.computeWorldMatrix = function (force) {
  15815. return BABYLON.Matrix.Identity();
  15816. };
  15817. /**
  15818. * Releases all associated resources
  15819. */
  15820. Node.prototype.dispose = function () {
  15821. this.parent = null;
  15822. // Callback
  15823. this.onDisposeObservable.notifyObservers(this);
  15824. this.onDisposeObservable.clear();
  15825. // Behaviors
  15826. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15827. var behavior = _a[_i];
  15828. behavior.detach();
  15829. }
  15830. this._behaviors = [];
  15831. this._isDisposed = true;
  15832. };
  15833. /**
  15834. * Parse animation range data from a serialization object and store them into a given node
  15835. * @param node defines where to store the animation ranges
  15836. * @param parsedNode defines the serialization object to read data from
  15837. * @param scene defines the hosting scene
  15838. */
  15839. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15840. if (parsedNode.ranges) {
  15841. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15842. var data = parsedNode.ranges[index];
  15843. node.createAnimationRange(data.name, data.from, data.to);
  15844. }
  15845. }
  15846. };
  15847. __decorate([
  15848. BABYLON.serialize()
  15849. ], Node.prototype, "name", void 0);
  15850. __decorate([
  15851. BABYLON.serialize()
  15852. ], Node.prototype, "id", void 0);
  15853. __decorate([
  15854. BABYLON.serialize()
  15855. ], Node.prototype, "uniqueId", void 0);
  15856. __decorate([
  15857. BABYLON.serialize()
  15858. ], Node.prototype, "state", void 0);
  15859. __decorate([
  15860. BABYLON.serialize()
  15861. ], Node.prototype, "metadata", void 0);
  15862. return Node;
  15863. }());
  15864. BABYLON.Node = Node;
  15865. })(BABYLON || (BABYLON = {}));
  15866. //# sourceMappingURL=babylon.node.js.map
  15867. var BABYLON;
  15868. (function (BABYLON) {
  15869. var BoundingSphere = /** @class */ (function () {
  15870. function BoundingSphere(minimum, maximum) {
  15871. this.minimum = minimum;
  15872. this.maximum = maximum;
  15873. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15874. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15875. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15876. this.radius = distance * 0.5;
  15877. this.centerWorld = BABYLON.Vector3.Zero();
  15878. this._update(BABYLON.Matrix.Identity());
  15879. }
  15880. // Methods
  15881. BoundingSphere.prototype._update = function (world) {
  15882. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15883. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15884. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15885. };
  15886. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15887. for (var i = 0; i < 6; i++) {
  15888. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15889. return false;
  15890. }
  15891. return true;
  15892. };
  15893. BoundingSphere.prototype.intersectsPoint = function (point) {
  15894. var x = this.centerWorld.x - point.x;
  15895. var y = this.centerWorld.y - point.y;
  15896. var z = this.centerWorld.z - point.z;
  15897. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15898. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15899. return false;
  15900. return true;
  15901. };
  15902. // Statics
  15903. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15904. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15905. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15906. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15907. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15908. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15909. return false;
  15910. return true;
  15911. };
  15912. return BoundingSphere;
  15913. }());
  15914. BABYLON.BoundingSphere = BoundingSphere;
  15915. })(BABYLON || (BABYLON = {}));
  15916. //# sourceMappingURL=babylon.boundingSphere.js.map
  15917. var BABYLON;
  15918. (function (BABYLON) {
  15919. var BoundingBox = /** @class */ (function () {
  15920. function BoundingBox(minimum, maximum) {
  15921. this.minimum = minimum;
  15922. this.maximum = maximum;
  15923. this.vectors = new Array();
  15924. this.vectorsWorld = new Array();
  15925. // Bounding vectors
  15926. this.vectors.push(this.minimum.clone());
  15927. this.vectors.push(this.maximum.clone());
  15928. this.vectors.push(this.minimum.clone());
  15929. this.vectors[2].x = this.maximum.x;
  15930. this.vectors.push(this.minimum.clone());
  15931. this.vectors[3].y = this.maximum.y;
  15932. this.vectors.push(this.minimum.clone());
  15933. this.vectors[4].z = this.maximum.z;
  15934. this.vectors.push(this.maximum.clone());
  15935. this.vectors[5].z = this.minimum.z;
  15936. this.vectors.push(this.maximum.clone());
  15937. this.vectors[6].x = this.minimum.x;
  15938. this.vectors.push(this.maximum.clone());
  15939. this.vectors[7].y = this.minimum.y;
  15940. // OBB
  15941. this.center = this.maximum.add(this.minimum).scale(0.5);
  15942. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15943. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15944. // World
  15945. for (var index = 0; index < this.vectors.length; index++) {
  15946. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15947. }
  15948. this.minimumWorld = BABYLON.Vector3.Zero();
  15949. this.maximumWorld = BABYLON.Vector3.Zero();
  15950. this.centerWorld = BABYLON.Vector3.Zero();
  15951. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15952. this._update(BABYLON.Matrix.Identity());
  15953. }
  15954. // Methods
  15955. BoundingBox.prototype.getWorldMatrix = function () {
  15956. return this._worldMatrix;
  15957. };
  15958. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15959. this._worldMatrix.copyFrom(matrix);
  15960. return this;
  15961. };
  15962. BoundingBox.prototype._update = function (world) {
  15963. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15964. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15965. for (var index = 0; index < this.vectors.length; index++) {
  15966. var v = this.vectorsWorld[index];
  15967. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15968. if (v.x < this.minimumWorld.x)
  15969. this.minimumWorld.x = v.x;
  15970. if (v.y < this.minimumWorld.y)
  15971. this.minimumWorld.y = v.y;
  15972. if (v.z < this.minimumWorld.z)
  15973. this.minimumWorld.z = v.z;
  15974. if (v.x > this.maximumWorld.x)
  15975. this.maximumWorld.x = v.x;
  15976. if (v.y > this.maximumWorld.y)
  15977. this.maximumWorld.y = v.y;
  15978. if (v.z > this.maximumWorld.z)
  15979. this.maximumWorld.z = v.z;
  15980. }
  15981. // Extend
  15982. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15983. this.extendSizeWorld.scaleInPlace(0.5);
  15984. // OBB
  15985. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15986. this.centerWorld.scaleInPlace(0.5);
  15987. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15988. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15989. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15990. this._worldMatrix = world;
  15991. };
  15992. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15993. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15994. };
  15995. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15996. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15997. };
  15998. BoundingBox.prototype.intersectsPoint = function (point) {
  15999. var delta = -BABYLON.Epsilon;
  16000. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16001. return false;
  16002. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16003. return false;
  16004. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16005. return false;
  16006. return true;
  16007. };
  16008. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16009. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16010. };
  16011. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16012. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16013. return false;
  16014. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16015. return false;
  16016. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16017. return false;
  16018. return true;
  16019. };
  16020. // Statics
  16021. BoundingBox.Intersects = function (box0, box1) {
  16022. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16023. return false;
  16024. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16025. return false;
  16026. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16027. return false;
  16028. return true;
  16029. };
  16030. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16031. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16032. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16033. return (num <= (sphereRadius * sphereRadius));
  16034. };
  16035. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16036. for (var p = 0; p < 6; p++) {
  16037. for (var i = 0; i < 8; i++) {
  16038. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16039. return false;
  16040. }
  16041. }
  16042. }
  16043. return true;
  16044. };
  16045. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16046. for (var p = 0; p < 6; p++) {
  16047. var inCount = 8;
  16048. for (var i = 0; i < 8; i++) {
  16049. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16050. --inCount;
  16051. }
  16052. else {
  16053. break;
  16054. }
  16055. }
  16056. if (inCount === 0)
  16057. return false;
  16058. }
  16059. return true;
  16060. };
  16061. return BoundingBox;
  16062. }());
  16063. BABYLON.BoundingBox = BoundingBox;
  16064. })(BABYLON || (BABYLON = {}));
  16065. //# sourceMappingURL=babylon.boundingBox.js.map
  16066. var BABYLON;
  16067. (function (BABYLON) {
  16068. var computeBoxExtents = function (axis, box) {
  16069. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16070. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16071. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16072. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16073. var r = r0 + r1 + r2;
  16074. return {
  16075. min: p - r,
  16076. max: p + r
  16077. };
  16078. };
  16079. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16080. var axisOverlap = function (axis, box0, box1) {
  16081. var result0 = computeBoxExtents(axis, box0);
  16082. var result1 = computeBoxExtents(axis, box1);
  16083. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16084. };
  16085. var BoundingInfo = /** @class */ (function () {
  16086. function BoundingInfo(minimum, maximum) {
  16087. this.minimum = minimum;
  16088. this.maximum = maximum;
  16089. this._isLocked = false;
  16090. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16091. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16092. }
  16093. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16094. get: function () {
  16095. return this._isLocked;
  16096. },
  16097. set: function (value) {
  16098. this._isLocked = value;
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. // Methods
  16104. BoundingInfo.prototype.update = function (world) {
  16105. if (this._isLocked) {
  16106. return;
  16107. }
  16108. this.boundingBox._update(world);
  16109. this.boundingSphere._update(world);
  16110. };
  16111. /**
  16112. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16113. * @param center New center of the bounding info
  16114. * @param extend New extend of the bounding info
  16115. */
  16116. BoundingInfo.prototype.centerOn = function (center, extend) {
  16117. this.minimum = center.subtract(extend);
  16118. this.maximum = center.add(extend);
  16119. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16120. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16121. return this;
  16122. };
  16123. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16124. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16125. return false;
  16126. return this.boundingBox.isInFrustum(frustumPlanes);
  16127. };
  16128. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16129. /**
  16130. * Gets the world distance between the min and max points of the bounding box
  16131. */
  16132. get: function () {
  16133. var boundingBox = this.boundingBox;
  16134. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16135. return size.length();
  16136. },
  16137. enumerable: true,
  16138. configurable: true
  16139. });
  16140. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16141. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16142. };
  16143. BoundingInfo.prototype._checkCollision = function (collider) {
  16144. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16145. };
  16146. BoundingInfo.prototype.intersectsPoint = function (point) {
  16147. if (!this.boundingSphere.centerWorld) {
  16148. return false;
  16149. }
  16150. if (!this.boundingSphere.intersectsPoint(point)) {
  16151. return false;
  16152. }
  16153. if (!this.boundingBox.intersectsPoint(point)) {
  16154. return false;
  16155. }
  16156. return true;
  16157. };
  16158. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16159. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16160. return false;
  16161. }
  16162. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16163. return false;
  16164. }
  16165. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16166. return false;
  16167. }
  16168. if (!precise) {
  16169. return true;
  16170. }
  16171. var box0 = this.boundingBox;
  16172. var box1 = boundingInfo.boundingBox;
  16173. if (!axisOverlap(box0.directions[0], box0, box1))
  16174. return false;
  16175. if (!axisOverlap(box0.directions[1], box0, box1))
  16176. return false;
  16177. if (!axisOverlap(box0.directions[2], box0, box1))
  16178. return false;
  16179. if (!axisOverlap(box1.directions[0], box0, box1))
  16180. return false;
  16181. if (!axisOverlap(box1.directions[1], box0, box1))
  16182. return false;
  16183. if (!axisOverlap(box1.directions[2], box0, box1))
  16184. return false;
  16185. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16186. return false;
  16187. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16188. return false;
  16189. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16190. return false;
  16191. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16192. return false;
  16193. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16194. return false;
  16195. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16196. return false;
  16197. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16198. return false;
  16199. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16200. return false;
  16201. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16202. return false;
  16203. return true;
  16204. };
  16205. return BoundingInfo;
  16206. }());
  16207. BABYLON.BoundingInfo = BoundingInfo;
  16208. })(BABYLON || (BABYLON = {}));
  16209. //# sourceMappingURL=babylon.boundingInfo.js.map
  16210. var BABYLON;
  16211. (function (BABYLON) {
  16212. var TransformNode = /** @class */ (function (_super) {
  16213. __extends(TransformNode, _super);
  16214. function TransformNode(name, scene, isPure) {
  16215. if (scene === void 0) { scene = null; }
  16216. if (isPure === void 0) { isPure = true; }
  16217. var _this = _super.call(this, name, scene) || this;
  16218. // Properties
  16219. _this._rotation = BABYLON.Vector3.Zero();
  16220. _this._scaling = BABYLON.Vector3.One();
  16221. _this._isDirty = false;
  16222. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16223. _this.scalingDeterminant = 1;
  16224. _this.infiniteDistance = false;
  16225. _this.position = BABYLON.Vector3.Zero();
  16226. _this._localWorld = BABYLON.Matrix.Zero();
  16227. _this._worldMatrix = BABYLON.Matrix.Zero();
  16228. _this._worldMatrixDeterminant = 0;
  16229. _this._absolutePosition = BABYLON.Vector3.Zero();
  16230. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16231. _this._postMultiplyPivotMatrix = false;
  16232. _this._isWorldMatrixFrozen = false;
  16233. /**
  16234. * An event triggered after the world matrix is updated
  16235. * @type {BABYLON.Observable}
  16236. */
  16237. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16238. _this._nonUniformScaling = false;
  16239. if (isPure) {
  16240. _this.getScene().addTransformNode(_this);
  16241. }
  16242. return _this;
  16243. }
  16244. Object.defineProperty(TransformNode.prototype, "rotation", {
  16245. /**
  16246. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16247. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16248. * Default : (0.0, 0.0, 0.0)
  16249. */
  16250. get: function () {
  16251. return this._rotation;
  16252. },
  16253. set: function (newRotation) {
  16254. this._rotation = newRotation;
  16255. },
  16256. enumerable: true,
  16257. configurable: true
  16258. });
  16259. Object.defineProperty(TransformNode.prototype, "scaling", {
  16260. /**
  16261. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16262. * Default : (1.0, 1.0, 1.0)
  16263. */
  16264. get: function () {
  16265. return this._scaling;
  16266. },
  16267. /**
  16268. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16269. * Default : (1.0, 1.0, 1.0)
  16270. */
  16271. set: function (newScaling) {
  16272. this._scaling = newScaling;
  16273. },
  16274. enumerable: true,
  16275. configurable: true
  16276. });
  16277. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16278. /**
  16279. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16280. * It's null by default.
  16281. * 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)
  16282. */
  16283. get: function () {
  16284. return this._rotationQuaternion;
  16285. },
  16286. set: function (quaternion) {
  16287. this._rotationQuaternion = quaternion;
  16288. //reset the rotation vector.
  16289. if (quaternion && this.rotation.length()) {
  16290. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16291. }
  16292. },
  16293. enumerable: true,
  16294. configurable: true
  16295. });
  16296. /**
  16297. * Returns the latest update of the World matrix
  16298. * Returns a Matrix.
  16299. */
  16300. TransformNode.prototype.getWorldMatrix = function () {
  16301. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16302. this.computeWorldMatrix();
  16303. }
  16304. return this._worldMatrix;
  16305. };
  16306. /**
  16307. * Returns the latest update of the World matrix determinant.
  16308. */
  16309. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16310. return this._worldMatrixDeterminant;
  16311. };
  16312. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16313. /**
  16314. * Returns directly the latest state of the mesh World matrix.
  16315. * A Matrix is returned.
  16316. */
  16317. get: function () {
  16318. return this._worldMatrix;
  16319. },
  16320. enumerable: true,
  16321. configurable: true
  16322. });
  16323. /**
  16324. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16325. * Returns the AbstractMesh.
  16326. */
  16327. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16328. this._poseMatrix.copyFrom(matrix);
  16329. return this;
  16330. };
  16331. /**
  16332. * Returns the mesh Pose matrix.
  16333. * Returned object : Matrix
  16334. */
  16335. TransformNode.prototype.getPoseMatrix = function () {
  16336. return this._poseMatrix;
  16337. };
  16338. TransformNode.prototype._isSynchronized = function () {
  16339. if (this._isDirty) {
  16340. return false;
  16341. }
  16342. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16343. return false;
  16344. if (this._cache.pivotMatrixUpdated) {
  16345. return false;
  16346. }
  16347. if (this.infiniteDistance) {
  16348. return false;
  16349. }
  16350. if (!this._cache.position.equals(this.position))
  16351. return false;
  16352. if (this.rotationQuaternion) {
  16353. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16354. return false;
  16355. }
  16356. if (!this._cache.rotation.equals(this.rotation))
  16357. return false;
  16358. if (!this._cache.scaling.equals(this.scaling))
  16359. return false;
  16360. return true;
  16361. };
  16362. TransformNode.prototype._initCache = function () {
  16363. _super.prototype._initCache.call(this);
  16364. this._cache.localMatrixUpdated = false;
  16365. this._cache.position = BABYLON.Vector3.Zero();
  16366. this._cache.scaling = BABYLON.Vector3.Zero();
  16367. this._cache.rotation = BABYLON.Vector3.Zero();
  16368. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16369. this._cache.billboardMode = -1;
  16370. };
  16371. TransformNode.prototype.markAsDirty = function (property) {
  16372. if (property === "rotation") {
  16373. this.rotationQuaternion = null;
  16374. }
  16375. this._currentRenderId = Number.MAX_VALUE;
  16376. this._isDirty = true;
  16377. return this;
  16378. };
  16379. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16380. /**
  16381. * Returns the current mesh absolute position.
  16382. * Retuns a Vector3.
  16383. */
  16384. get: function () {
  16385. return this._absolutePosition;
  16386. },
  16387. enumerable: true,
  16388. configurable: true
  16389. });
  16390. /**
  16391. * Sets a new matrix to apply before all other transformation
  16392. * @param matrix defines the transform matrix
  16393. * @returns the current TransformNode
  16394. */
  16395. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16396. return this.setPivotMatrix(matrix, false);
  16397. };
  16398. /**
  16399. * Sets a new pivot matrix to the current node
  16400. * @param matrix defines the new pivot matrix to use
  16401. * @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
  16402. * @returns the current TransformNode
  16403. */
  16404. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16405. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16406. this._pivotMatrix = matrix.clone();
  16407. this._cache.pivotMatrixUpdated = true;
  16408. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16409. if (this._postMultiplyPivotMatrix) {
  16410. if (!this._pivotMatrixInverse) {
  16411. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16412. }
  16413. else {
  16414. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16415. }
  16416. }
  16417. return this;
  16418. };
  16419. /**
  16420. * Returns the mesh pivot matrix.
  16421. * Default : Identity.
  16422. * A Matrix is returned.
  16423. */
  16424. TransformNode.prototype.getPivotMatrix = function () {
  16425. return this._pivotMatrix;
  16426. };
  16427. /**
  16428. * Prevents the World matrix to be computed any longer.
  16429. * Returns the AbstractMesh.
  16430. */
  16431. TransformNode.prototype.freezeWorldMatrix = function () {
  16432. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16433. this.computeWorldMatrix(true);
  16434. this._isWorldMatrixFrozen = true;
  16435. return this;
  16436. };
  16437. /**
  16438. * Allows back the World matrix computation.
  16439. * Returns the AbstractMesh.
  16440. */
  16441. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16442. this._isWorldMatrixFrozen = false;
  16443. this.computeWorldMatrix(true);
  16444. return this;
  16445. };
  16446. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16447. /**
  16448. * True if the World matrix has been frozen.
  16449. * Returns a boolean.
  16450. */
  16451. get: function () {
  16452. return this._isWorldMatrixFrozen;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. /**
  16458. * Retuns the mesh absolute position in the World.
  16459. * Returns a Vector3.
  16460. */
  16461. TransformNode.prototype.getAbsolutePosition = function () {
  16462. this.computeWorldMatrix();
  16463. return this._absolutePosition;
  16464. };
  16465. /**
  16466. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16467. * Returns the AbstractMesh.
  16468. */
  16469. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16470. if (!absolutePosition) {
  16471. return this;
  16472. }
  16473. var absolutePositionX;
  16474. var absolutePositionY;
  16475. var absolutePositionZ;
  16476. if (absolutePosition.x === undefined) {
  16477. if (arguments.length < 3) {
  16478. return this;
  16479. }
  16480. absolutePositionX = arguments[0];
  16481. absolutePositionY = arguments[1];
  16482. absolutePositionZ = arguments[2];
  16483. }
  16484. else {
  16485. absolutePositionX = absolutePosition.x;
  16486. absolutePositionY = absolutePosition.y;
  16487. absolutePositionZ = absolutePosition.z;
  16488. }
  16489. if (this.parent) {
  16490. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16491. invertParentWorldMatrix.invert();
  16492. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16493. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16494. }
  16495. else {
  16496. this.position.x = absolutePositionX;
  16497. this.position.y = absolutePositionY;
  16498. this.position.z = absolutePositionZ;
  16499. }
  16500. return this;
  16501. };
  16502. /**
  16503. * Sets the mesh position in its local space.
  16504. * Returns the AbstractMesh.
  16505. */
  16506. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16507. this.computeWorldMatrix();
  16508. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16509. return this;
  16510. };
  16511. /**
  16512. * Returns the mesh position in the local space from the current World matrix values.
  16513. * Returns a new Vector3.
  16514. */
  16515. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16516. this.computeWorldMatrix();
  16517. var invLocalWorldMatrix = this._localWorld.clone();
  16518. invLocalWorldMatrix.invert();
  16519. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16520. };
  16521. /**
  16522. * Translates the mesh along the passed Vector3 in its local space.
  16523. * Returns the AbstractMesh.
  16524. */
  16525. TransformNode.prototype.locallyTranslate = function (vector3) {
  16526. this.computeWorldMatrix(true);
  16527. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16528. return this;
  16529. };
  16530. /**
  16531. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16532. * @param targetPoint the position (must be in same space as current mesh) to look at
  16533. * @param yawCor optional yaw (y-axis) correction in radians
  16534. * @param pitchCor optional pitch (x-axis) correction in radians
  16535. * @param rollCor optional roll (z-axis) correction in radians
  16536. * @param space the choosen space of the target
  16537. * @returns the TransformNode.
  16538. */
  16539. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16540. if (yawCor === void 0) { yawCor = 0; }
  16541. if (pitchCor === void 0) { pitchCor = 0; }
  16542. if (rollCor === void 0) { rollCor = 0; }
  16543. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16544. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16545. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16546. targetPoint.subtractToRef(pos, dv);
  16547. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16548. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16549. var pitch = Math.atan2(dv.y, len);
  16550. if (this.rotationQuaternion) {
  16551. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16552. }
  16553. else {
  16554. this.rotation.x = pitch + pitchCor;
  16555. this.rotation.y = yaw + yawCor;
  16556. this.rotation.z = rollCor;
  16557. }
  16558. return this;
  16559. };
  16560. /**
  16561. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16562. * This Vector3 is expressed in the World space.
  16563. */
  16564. TransformNode.prototype.getDirection = function (localAxis) {
  16565. var result = BABYLON.Vector3.Zero();
  16566. this.getDirectionToRef(localAxis, result);
  16567. return result;
  16568. };
  16569. /**
  16570. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16571. * localAxis is expressed in the mesh local space.
  16572. * result is computed in the Wordl space from the mesh World matrix.
  16573. * Returns the AbstractMesh.
  16574. */
  16575. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16576. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16577. return this;
  16578. };
  16579. /**
  16580. * Sets a new pivot point to the current node
  16581. * @param point defines the new pivot point to use
  16582. * @param space defines if the point is in world or local space (local by default)
  16583. * @returns the current TransformNode
  16584. */
  16585. TransformNode.prototype.setPivotPoint = function (point, space) {
  16586. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16587. if (this.getScene().getRenderId() == 0) {
  16588. this.computeWorldMatrix(true);
  16589. }
  16590. var wm = this.getWorldMatrix();
  16591. if (space == BABYLON.Space.WORLD) {
  16592. var tmat = BABYLON.Tmp.Matrix[0];
  16593. wm.invertToRef(tmat);
  16594. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16595. }
  16596. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16597. };
  16598. /**
  16599. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16600. */
  16601. TransformNode.prototype.getPivotPoint = function () {
  16602. var point = BABYLON.Vector3.Zero();
  16603. this.getPivotPointToRef(point);
  16604. return point;
  16605. };
  16606. /**
  16607. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16608. * Returns the AbstractMesh.
  16609. */
  16610. TransformNode.prototype.getPivotPointToRef = function (result) {
  16611. result.x = -this._pivotMatrix.m[12];
  16612. result.y = -this._pivotMatrix.m[13];
  16613. result.z = -this._pivotMatrix.m[14];
  16614. return this;
  16615. };
  16616. /**
  16617. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16618. */
  16619. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16620. var point = BABYLON.Vector3.Zero();
  16621. this.getAbsolutePivotPointToRef(point);
  16622. return point;
  16623. };
  16624. /**
  16625. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16626. * Returns the AbstractMesh.
  16627. */
  16628. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16629. result.x = this._pivotMatrix.m[12];
  16630. result.y = this._pivotMatrix.m[13];
  16631. result.z = this._pivotMatrix.m[14];
  16632. this.getPivotPointToRef(result);
  16633. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16634. return this;
  16635. };
  16636. /**
  16637. * Defines the passed node as the parent of the current node.
  16638. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16639. * Returns the TransformNode.
  16640. */
  16641. TransformNode.prototype.setParent = function (node) {
  16642. if (node === null) {
  16643. var rotation = BABYLON.Tmp.Quaternion[0];
  16644. var position = BABYLON.Tmp.Vector3[0];
  16645. var scale = BABYLON.Tmp.Vector3[1];
  16646. if (this.parent && this.parent.computeWorldMatrix) {
  16647. this.parent.computeWorldMatrix(true);
  16648. }
  16649. this.computeWorldMatrix(true);
  16650. this.getWorldMatrix().decompose(scale, rotation, position);
  16651. if (this.rotationQuaternion) {
  16652. this.rotationQuaternion.copyFrom(rotation);
  16653. }
  16654. else {
  16655. rotation.toEulerAnglesToRef(this.rotation);
  16656. }
  16657. this.scaling.x = scale.x;
  16658. this.scaling.y = scale.y;
  16659. this.scaling.z = scale.z;
  16660. this.position.x = position.x;
  16661. this.position.y = position.y;
  16662. this.position.z = position.z;
  16663. }
  16664. else {
  16665. var rotation = BABYLON.Tmp.Quaternion[0];
  16666. var position = BABYLON.Tmp.Vector3[0];
  16667. var scale = BABYLON.Tmp.Vector3[1];
  16668. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16669. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16670. this.computeWorldMatrix(true);
  16671. node.computeWorldMatrix(true);
  16672. node.getWorldMatrix().invertToRef(invParentMatrix);
  16673. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16674. diffMatrix.decompose(scale, rotation, position);
  16675. if (this.rotationQuaternion) {
  16676. this.rotationQuaternion.copyFrom(rotation);
  16677. }
  16678. else {
  16679. rotation.toEulerAnglesToRef(this.rotation);
  16680. }
  16681. this.position.x = position.x;
  16682. this.position.y = position.y;
  16683. this.position.z = position.z;
  16684. this.scaling.x = scale.x;
  16685. this.scaling.y = scale.y;
  16686. this.scaling.z = scale.z;
  16687. }
  16688. this.parent = node;
  16689. return this;
  16690. };
  16691. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16692. get: function () {
  16693. return this._nonUniformScaling;
  16694. },
  16695. enumerable: true,
  16696. configurable: true
  16697. });
  16698. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16699. if (this._nonUniformScaling === value) {
  16700. return false;
  16701. }
  16702. this._nonUniformScaling = true;
  16703. return true;
  16704. };
  16705. /**
  16706. * Attach the current TransformNode to another TransformNode associated with a bone
  16707. * @param bone Bone affecting the TransformNode
  16708. * @param affectedTransformNode TransformNode associated with the bone
  16709. */
  16710. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16711. this._transformToBoneReferal = affectedTransformNode;
  16712. this.parent = bone;
  16713. if (bone.getWorldMatrix().determinant() < 0) {
  16714. this.scalingDeterminant *= -1;
  16715. }
  16716. return this;
  16717. };
  16718. TransformNode.prototype.detachFromBone = function () {
  16719. if (!this.parent) {
  16720. return this;
  16721. }
  16722. if (this.parent.getWorldMatrix().determinant() < 0) {
  16723. this.scalingDeterminant *= -1;
  16724. }
  16725. this._transformToBoneReferal = null;
  16726. this.parent = null;
  16727. return this;
  16728. };
  16729. /**
  16730. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16731. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16732. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16733. * The passed axis is also normalized.
  16734. * Returns the AbstractMesh.
  16735. */
  16736. TransformNode.prototype.rotate = function (axis, amount, space) {
  16737. axis.normalize();
  16738. if (!this.rotationQuaternion) {
  16739. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16740. this.rotation = BABYLON.Vector3.Zero();
  16741. }
  16742. var rotationQuaternion;
  16743. if (!space || space === BABYLON.Space.LOCAL) {
  16744. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16745. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16746. }
  16747. else {
  16748. if (this.parent) {
  16749. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16750. invertParentWorldMatrix.invert();
  16751. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16752. }
  16753. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16754. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16755. }
  16756. return this;
  16757. };
  16758. /**
  16759. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16760. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16761. * The passed axis is also normalized.
  16762. * Returns the AbstractMesh.
  16763. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16764. */
  16765. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16766. axis.normalize();
  16767. if (!this.rotationQuaternion) {
  16768. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16769. this.rotation.copyFromFloats(0, 0, 0);
  16770. }
  16771. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16772. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16773. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16774. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16775. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16776. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16777. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16778. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16779. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16780. return this;
  16781. };
  16782. /**
  16783. * Translates the mesh along the axis vector for the passed distance in the given space.
  16784. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16785. * Returns the AbstractMesh.
  16786. */
  16787. TransformNode.prototype.translate = function (axis, distance, space) {
  16788. var displacementVector = axis.scale(distance);
  16789. if (!space || space === BABYLON.Space.LOCAL) {
  16790. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16791. this.setPositionWithLocalVector(tempV3);
  16792. }
  16793. else {
  16794. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16795. }
  16796. return this;
  16797. };
  16798. /**
  16799. * Adds a rotation step to the mesh current rotation.
  16800. * x, y, z are Euler angles expressed in radians.
  16801. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16802. * This means this rotation is made in the mesh local space only.
  16803. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16804. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16805. * ```javascript
  16806. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16807. * ```
  16808. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16809. * 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.
  16810. * Returns the AbstractMesh.
  16811. */
  16812. TransformNode.prototype.addRotation = function (x, y, z) {
  16813. var rotationQuaternion;
  16814. if (this.rotationQuaternion) {
  16815. rotationQuaternion = this.rotationQuaternion;
  16816. }
  16817. else {
  16818. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16819. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16820. }
  16821. var accumulation = BABYLON.Tmp.Quaternion[0];
  16822. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16823. rotationQuaternion.multiplyInPlace(accumulation);
  16824. if (!this.rotationQuaternion) {
  16825. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16826. }
  16827. return this;
  16828. };
  16829. /**
  16830. * Computes the mesh World matrix and returns it.
  16831. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16832. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16833. * If the parameter `force`is set to `true`, the actual computation is done.
  16834. * Returns the mesh World Matrix.
  16835. */
  16836. TransformNode.prototype.computeWorldMatrix = function (force) {
  16837. if (this._isWorldMatrixFrozen) {
  16838. return this._worldMatrix;
  16839. }
  16840. if (!force && this.isSynchronized(true)) {
  16841. return this._worldMatrix;
  16842. }
  16843. this._cache.position.copyFrom(this.position);
  16844. this._cache.scaling.copyFrom(this.scaling);
  16845. this._cache.pivotMatrixUpdated = false;
  16846. this._cache.billboardMode = this.billboardMode;
  16847. this._currentRenderId = this.getScene().getRenderId();
  16848. this._isDirty = false;
  16849. // Scaling
  16850. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16851. // Rotation
  16852. //rotate, if quaternion is set and rotation was used
  16853. if (this.rotationQuaternion) {
  16854. var len = this.rotation.length();
  16855. if (len) {
  16856. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16857. this.rotation.copyFromFloats(0, 0, 0);
  16858. }
  16859. }
  16860. if (this.rotationQuaternion) {
  16861. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16862. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16863. }
  16864. else {
  16865. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16866. this._cache.rotation.copyFrom(this.rotation);
  16867. }
  16868. // Translation
  16869. var camera = this.getScene().activeCamera;
  16870. if (this.infiniteDistance && !this.parent && camera) {
  16871. var cameraWorldMatrix = camera.getWorldMatrix();
  16872. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16873. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16874. }
  16875. else {
  16876. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16877. }
  16878. // Composing transformations
  16879. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16880. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16881. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16882. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16883. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16884. // Need to decompose each rotation here
  16885. var currentPosition = BABYLON.Tmp.Vector3[3];
  16886. if (this.parent && this.parent.getWorldMatrix) {
  16887. if (this._transformToBoneReferal) {
  16888. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16889. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16890. }
  16891. else {
  16892. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16893. }
  16894. }
  16895. else {
  16896. currentPosition.copyFrom(this.position);
  16897. }
  16898. currentPosition.subtractInPlace(camera.globalPosition);
  16899. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16900. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16901. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16902. }
  16903. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16904. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16905. }
  16906. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16907. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16908. }
  16909. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16910. }
  16911. else {
  16912. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16913. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16914. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16915. }
  16916. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16917. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16918. }
  16919. // Local world
  16920. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16921. // Parent
  16922. if (this.parent && this.parent.getWorldMatrix) {
  16923. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16924. if (this._transformToBoneReferal) {
  16925. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16926. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16927. }
  16928. else {
  16929. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16930. }
  16931. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16932. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16933. this._worldMatrix.copyFrom(this._localWorld);
  16934. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16935. }
  16936. else {
  16937. if (this._transformToBoneReferal) {
  16938. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16939. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16940. }
  16941. else {
  16942. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16943. }
  16944. }
  16945. this._markSyncedWithParent();
  16946. }
  16947. else {
  16948. this._worldMatrix.copyFrom(this._localWorld);
  16949. }
  16950. // Post multiply inverse of pivotMatrix
  16951. if (this._postMultiplyPivotMatrix) {
  16952. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16953. }
  16954. // Normal matrix
  16955. if (this.scaling.isNonUniform) {
  16956. this._updateNonUniformScalingState(true);
  16957. }
  16958. else if (this.parent && this.parent._nonUniformScaling) {
  16959. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16960. }
  16961. else {
  16962. this._updateNonUniformScalingState(false);
  16963. }
  16964. this._afterComputeWorldMatrix();
  16965. // Absolute position
  16966. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16967. // Callbacks
  16968. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16969. if (!this._poseMatrix) {
  16970. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16971. }
  16972. // Cache the determinant
  16973. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16974. return this._worldMatrix;
  16975. };
  16976. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16977. };
  16978. /**
  16979. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16980. * @param func: callback function to add
  16981. *
  16982. * Returns the TransformNode.
  16983. */
  16984. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16985. this.onAfterWorldMatrixUpdateObservable.add(func);
  16986. return this;
  16987. };
  16988. /**
  16989. * Removes a registered callback function.
  16990. * Returns the TransformNode.
  16991. */
  16992. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16993. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16994. return this;
  16995. };
  16996. /**
  16997. * Clone the current transform node
  16998. * Returns the new transform node
  16999. * @param name Name of the new clone
  17000. * @param newParent New parent for the clone
  17001. * @param doNotCloneChildren Do not clone children hierarchy
  17002. */
  17003. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17004. var _this = this;
  17005. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17006. result.name = name;
  17007. result.id = name;
  17008. if (newParent) {
  17009. result.parent = newParent;
  17010. }
  17011. if (!doNotCloneChildren) {
  17012. // Children
  17013. var directDescendants = this.getDescendants(true);
  17014. for (var index = 0; index < directDescendants.length; index++) {
  17015. var child = directDescendants[index];
  17016. if (child.clone) {
  17017. child.clone(name + "." + child.name, result);
  17018. }
  17019. }
  17020. }
  17021. return result;
  17022. };
  17023. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17024. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17025. serializationObject.type = this.getClassName();
  17026. // Parent
  17027. if (this.parent) {
  17028. serializationObject.parentId = this.parent.id;
  17029. }
  17030. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17031. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17032. }
  17033. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17034. serializationObject.isEnabled = this.isEnabled();
  17035. // Parent
  17036. if (this.parent) {
  17037. serializationObject.parentId = this.parent.id;
  17038. }
  17039. return serializationObject;
  17040. };
  17041. // Statics
  17042. /**
  17043. * Returns a new TransformNode object parsed from the source provided.
  17044. * The parameter `parsedMesh` is the source.
  17045. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17046. */
  17047. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17048. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17049. if (BABYLON.Tags) {
  17050. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17051. }
  17052. if (parsedTransformNode.localMatrix) {
  17053. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17054. }
  17055. else if (parsedTransformNode.pivotMatrix) {
  17056. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17057. }
  17058. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17059. // Parent
  17060. if (parsedTransformNode.parentId) {
  17061. transformNode._waitingParentId = parsedTransformNode.parentId;
  17062. }
  17063. return transformNode;
  17064. };
  17065. /**
  17066. * Disposes the TransformNode.
  17067. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17068. * Returns nothing.
  17069. */
  17070. TransformNode.prototype.dispose = function (doNotRecurse) {
  17071. // Animations
  17072. this.getScene().stopAnimation(this);
  17073. // Remove from scene
  17074. this.getScene().removeTransformNode(this);
  17075. if (!doNotRecurse) {
  17076. // Children
  17077. var objects = this.getDescendants(true);
  17078. for (var index = 0; index < objects.length; index++) {
  17079. objects[index].dispose();
  17080. }
  17081. }
  17082. else {
  17083. var childMeshes = this.getChildMeshes(true);
  17084. for (index = 0; index < childMeshes.length; index++) {
  17085. var child = childMeshes[index];
  17086. child.parent = null;
  17087. child.computeWorldMatrix(true);
  17088. }
  17089. }
  17090. this.onAfterWorldMatrixUpdateObservable.clear();
  17091. _super.prototype.dispose.call(this);
  17092. };
  17093. // Statics
  17094. TransformNode.BILLBOARDMODE_NONE = 0;
  17095. TransformNode.BILLBOARDMODE_X = 1;
  17096. TransformNode.BILLBOARDMODE_Y = 2;
  17097. TransformNode.BILLBOARDMODE_Z = 4;
  17098. TransformNode.BILLBOARDMODE_ALL = 7;
  17099. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17100. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17101. __decorate([
  17102. BABYLON.serializeAsVector3()
  17103. ], TransformNode.prototype, "_rotation", void 0);
  17104. __decorate([
  17105. BABYLON.serializeAsQuaternion()
  17106. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17107. __decorate([
  17108. BABYLON.serializeAsVector3()
  17109. ], TransformNode.prototype, "_scaling", void 0);
  17110. __decorate([
  17111. BABYLON.serialize()
  17112. ], TransformNode.prototype, "billboardMode", void 0);
  17113. __decorate([
  17114. BABYLON.serialize()
  17115. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17116. __decorate([
  17117. BABYLON.serialize()
  17118. ], TransformNode.prototype, "infiniteDistance", void 0);
  17119. __decorate([
  17120. BABYLON.serializeAsVector3()
  17121. ], TransformNode.prototype, "position", void 0);
  17122. return TransformNode;
  17123. }(BABYLON.Node));
  17124. BABYLON.TransformNode = TransformNode;
  17125. })(BABYLON || (BABYLON = {}));
  17126. //# sourceMappingURL=babylon.transformNode.js.map
  17127. var BABYLON;
  17128. (function (BABYLON) {
  17129. var AbstractMesh = /** @class */ (function (_super) {
  17130. __extends(AbstractMesh, _super);
  17131. // Constructor
  17132. function AbstractMesh(name, scene) {
  17133. if (scene === void 0) { scene = null; }
  17134. var _this = _super.call(this, name, scene, false) || this;
  17135. _this._facetNb = 0; // facet number
  17136. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17137. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17138. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17139. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17140. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17141. _this._subDiv = {
  17142. max: 1,
  17143. X: 1,
  17144. Y: 1,
  17145. Z: 1
  17146. };
  17147. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17148. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17149. // Events
  17150. /**
  17151. * An event triggered when this mesh collides with another one
  17152. * @type {BABYLON.Observable}
  17153. */
  17154. _this.onCollideObservable = new BABYLON.Observable();
  17155. /**
  17156. * An event triggered when the collision's position changes
  17157. * @type {BABYLON.Observable}
  17158. */
  17159. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17160. /**
  17161. * An event triggered when material is changed
  17162. * @type {BABYLON.Observable}
  17163. */
  17164. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17165. // Properties
  17166. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17167. /**
  17168. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17169. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17170. * or
  17171. * 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.
  17172. * for more info check WebGl documentations
  17173. */
  17174. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17175. /**
  17176. * 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:
  17177. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17178. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17179. * 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.
  17180. */
  17181. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17182. /**
  17183. * 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.
  17184. * The default value is -1 which means don't break the query and wait till the result.
  17185. */
  17186. _this.occlusionRetryCount = -1;
  17187. _this._occlusionInternalRetryCounter = 0;
  17188. _this._isOccluded = false;
  17189. _this._isOcclusionQueryInProgress = false;
  17190. _this._visibility = 1.0;
  17191. _this.alphaIndex = Number.MAX_VALUE;
  17192. _this.isVisible = true;
  17193. _this.isPickable = true;
  17194. _this.showBoundingBox = false;
  17195. _this.showSubMeshesBoundingBox = false;
  17196. _this.isBlocker = false;
  17197. _this.enablePointerMoveEvents = false;
  17198. _this.renderingGroupId = 0;
  17199. _this._receiveShadows = false;
  17200. _this.renderOutline = false;
  17201. _this.outlineColor = BABYLON.Color3.Red();
  17202. _this.outlineWidth = 0.02;
  17203. _this.renderOverlay = false;
  17204. _this.overlayColor = BABYLON.Color3.Red();
  17205. _this.overlayAlpha = 0.5;
  17206. _this._hasVertexAlpha = false;
  17207. _this._useVertexColors = true;
  17208. _this._computeBonesUsingShaders = true;
  17209. _this._numBoneInfluencers = 4;
  17210. _this._applyFog = true;
  17211. _this.useOctreeForRenderingSelection = true;
  17212. _this.useOctreeForPicking = true;
  17213. _this.useOctreeForCollisions = true;
  17214. _this._layerMask = 0x0FFFFFFF;
  17215. /**
  17216. * True if the mesh must be rendered in any case.
  17217. */
  17218. _this.alwaysSelectAsActiveMesh = false;
  17219. /**
  17220. * This scene's action manager
  17221. * @type {BABYLON.ActionManager}
  17222. */
  17223. _this.actionManager = null;
  17224. // Physics
  17225. _this.physicsImpostor = null;
  17226. // Collisions
  17227. _this._checkCollisions = false;
  17228. _this._collisionMask = -1;
  17229. _this._collisionGroup = -1;
  17230. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17231. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17232. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17233. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17234. // Edges
  17235. _this.edgesWidth = 1;
  17236. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17237. // Cache
  17238. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17239. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17240. _this._renderId = 0;
  17241. _this._intersectionsInProgress = new Array();
  17242. _this._unIndexed = false;
  17243. _this._lightSources = new Array();
  17244. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17245. if (collidedMesh === void 0) { collidedMesh = null; }
  17246. //TODO move this to the collision coordinator!
  17247. if (_this.getScene().workerCollisions)
  17248. newPosition.multiplyInPlace(_this._collider._radius);
  17249. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17250. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17251. _this.position.addInPlace(_this._diffPositionForCollisions);
  17252. }
  17253. if (collidedMesh) {
  17254. _this.onCollideObservable.notifyObservers(collidedMesh);
  17255. }
  17256. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17257. };
  17258. _this.getScene().addMesh(_this);
  17259. _this._resyncLightSources();
  17260. return _this;
  17261. }
  17262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17263. get: function () {
  17264. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17270. get: function () {
  17271. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17277. get: function () {
  17278. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17279. },
  17280. enumerable: true,
  17281. configurable: true
  17282. });
  17283. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17284. get: function () {
  17285. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17291. get: function () {
  17292. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17293. },
  17294. enumerable: true,
  17295. configurable: true
  17296. });
  17297. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17298. /**
  17299. * Read-only : the number of facets in the mesh
  17300. */
  17301. get: function () {
  17302. return this._facetNb;
  17303. },
  17304. enumerable: true,
  17305. configurable: true
  17306. });
  17307. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17308. /**
  17309. * The number (integer) of subdivisions per axis in the partioning space
  17310. */
  17311. get: function () {
  17312. return this._partitioningSubdivisions;
  17313. },
  17314. set: function (nb) {
  17315. this._partitioningSubdivisions = nb;
  17316. },
  17317. enumerable: true,
  17318. configurable: true
  17319. });
  17320. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17321. /**
  17322. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17323. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17324. */
  17325. get: function () {
  17326. return this._partitioningBBoxRatio;
  17327. },
  17328. set: function (ratio) {
  17329. this._partitioningBBoxRatio = ratio;
  17330. },
  17331. enumerable: true,
  17332. configurable: true
  17333. });
  17334. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17335. /**
  17336. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17337. * Works only for updatable meshes.
  17338. * Doesn't work with multi-materials.
  17339. */
  17340. get: function () {
  17341. return this._facetDepthSort;
  17342. },
  17343. set: function (sort) {
  17344. this._facetDepthSort = sort;
  17345. },
  17346. enumerable: true,
  17347. configurable: true
  17348. });
  17349. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17350. /**
  17351. * The location (Vector3) where the facet depth sort must be computed from.
  17352. * By default, the active camera position.
  17353. * Used only when facet depth sort is enabled.
  17354. */
  17355. get: function () {
  17356. return this._facetDepthSortFrom;
  17357. },
  17358. set: function (location) {
  17359. this._facetDepthSortFrom = location;
  17360. },
  17361. enumerable: true,
  17362. configurable: true
  17363. });
  17364. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17365. /**
  17366. * Read-only boolean : is the feature facetData enabled ?
  17367. */
  17368. get: function () {
  17369. return this._facetDataEnabled;
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17375. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17376. return false;
  17377. }
  17378. this._markSubMeshesAsMiscDirty();
  17379. return true;
  17380. };
  17381. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17382. set: function (callback) {
  17383. if (this._onCollideObserver) {
  17384. this.onCollideObservable.remove(this._onCollideObserver);
  17385. }
  17386. this._onCollideObserver = this.onCollideObservable.add(callback);
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17392. set: function (callback) {
  17393. if (this._onCollisionPositionChangeObserver) {
  17394. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17395. }
  17396. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17397. },
  17398. enumerable: true,
  17399. configurable: true
  17400. });
  17401. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17402. /**
  17403. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17404. */
  17405. get: function () {
  17406. return this._isOccluded;
  17407. },
  17408. set: function (value) {
  17409. this._isOccluded = value;
  17410. },
  17411. enumerable: true,
  17412. configurable: true
  17413. });
  17414. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17415. /**
  17416. * Flag to check the progress status of the query
  17417. */
  17418. get: function () {
  17419. return this._isOcclusionQueryInProgress;
  17420. },
  17421. enumerable: true,
  17422. configurable: true
  17423. });
  17424. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17425. /**
  17426. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17427. */
  17428. get: function () {
  17429. return this._visibility;
  17430. },
  17431. /**
  17432. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17433. */
  17434. set: function (value) {
  17435. if (this._visibility === value) {
  17436. return;
  17437. }
  17438. this._visibility = value;
  17439. this._markSubMeshesAsMiscDirty();
  17440. },
  17441. enumerable: true,
  17442. configurable: true
  17443. });
  17444. Object.defineProperty(AbstractMesh.prototype, "material", {
  17445. get: function () {
  17446. return this._material;
  17447. },
  17448. set: function (value) {
  17449. if (this._material === value) {
  17450. return;
  17451. }
  17452. this._material = value;
  17453. if (this.onMaterialChangedObservable.hasObservers) {
  17454. this.onMaterialChangedObservable.notifyObservers(this);
  17455. }
  17456. if (!this.subMeshes) {
  17457. return;
  17458. }
  17459. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17460. var subMesh = _a[_i];
  17461. subMesh.setEffect(null);
  17462. }
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17468. get: function () {
  17469. return this._receiveShadows;
  17470. },
  17471. set: function (value) {
  17472. if (this._receiveShadows === value) {
  17473. return;
  17474. }
  17475. this._receiveShadows = value;
  17476. this._markSubMeshesAsLightDirty();
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17482. get: function () {
  17483. return this._hasVertexAlpha;
  17484. },
  17485. set: function (value) {
  17486. if (this._hasVertexAlpha === value) {
  17487. return;
  17488. }
  17489. this._hasVertexAlpha = value;
  17490. this._markSubMeshesAsAttributesDirty();
  17491. this._markSubMeshesAsMiscDirty();
  17492. },
  17493. enumerable: true,
  17494. configurable: true
  17495. });
  17496. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17497. get: function () {
  17498. return this._useVertexColors;
  17499. },
  17500. set: function (value) {
  17501. if (this._useVertexColors === value) {
  17502. return;
  17503. }
  17504. this._useVertexColors = value;
  17505. this._markSubMeshesAsAttributesDirty();
  17506. },
  17507. enumerable: true,
  17508. configurable: true
  17509. });
  17510. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17511. get: function () {
  17512. return this._computeBonesUsingShaders;
  17513. },
  17514. set: function (value) {
  17515. if (this._computeBonesUsingShaders === value) {
  17516. return;
  17517. }
  17518. this._computeBonesUsingShaders = value;
  17519. this._markSubMeshesAsAttributesDirty();
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17525. get: function () {
  17526. return this._numBoneInfluencers;
  17527. },
  17528. set: function (value) {
  17529. if (this._numBoneInfluencers === value) {
  17530. return;
  17531. }
  17532. this._numBoneInfluencers = value;
  17533. this._markSubMeshesAsAttributesDirty();
  17534. },
  17535. enumerable: true,
  17536. configurable: true
  17537. });
  17538. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17539. get: function () {
  17540. return this._applyFog;
  17541. },
  17542. set: function (value) {
  17543. if (this._applyFog === value) {
  17544. return;
  17545. }
  17546. this._applyFog = value;
  17547. this._markSubMeshesAsMiscDirty();
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17553. get: function () {
  17554. return this._layerMask;
  17555. },
  17556. set: function (value) {
  17557. if (value === this._layerMask) {
  17558. return;
  17559. }
  17560. this._layerMask = value;
  17561. this._resyncLightSources();
  17562. },
  17563. enumerable: true,
  17564. configurable: true
  17565. });
  17566. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17567. get: function () {
  17568. return this._collisionMask;
  17569. },
  17570. set: function (mask) {
  17571. this._collisionMask = !isNaN(mask) ? mask : -1;
  17572. },
  17573. enumerable: true,
  17574. configurable: true
  17575. });
  17576. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17577. get: function () {
  17578. return this._collisionGroup;
  17579. },
  17580. set: function (mask) {
  17581. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17587. get: function () {
  17588. return null;
  17589. },
  17590. enumerable: true,
  17591. configurable: true
  17592. });
  17593. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17594. get: function () {
  17595. return this._skeleton;
  17596. },
  17597. set: function (value) {
  17598. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17599. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17600. }
  17601. if (value && value.needInitialSkinMatrix) {
  17602. value._registerMeshWithPoseMatrix(this);
  17603. }
  17604. this._skeleton = value;
  17605. if (!this._skeleton) {
  17606. this._bonesTransformMatrices = null;
  17607. }
  17608. this._markSubMeshesAsAttributesDirty();
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. /**
  17614. * Returns the string "AbstractMesh"
  17615. */
  17616. AbstractMesh.prototype.getClassName = function () {
  17617. return "AbstractMesh";
  17618. };
  17619. /**
  17620. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17621. */
  17622. AbstractMesh.prototype.toString = function (fullDetails) {
  17623. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17624. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17625. if (this._skeleton) {
  17626. ret += ", skeleton: " + this._skeleton.name;
  17627. }
  17628. if (fullDetails) {
  17629. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17630. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17631. }
  17632. return ret;
  17633. };
  17634. AbstractMesh.prototype._rebuild = function () {
  17635. if (this._occlusionQuery) {
  17636. this._occlusionQuery = null;
  17637. }
  17638. if (this._edgesRenderer) {
  17639. this._edgesRenderer._rebuild();
  17640. }
  17641. if (!this.subMeshes) {
  17642. return;
  17643. }
  17644. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17645. var subMesh = _a[_i];
  17646. subMesh._rebuild();
  17647. }
  17648. };
  17649. AbstractMesh.prototype._resyncLightSources = function () {
  17650. this._lightSources.length = 0;
  17651. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17652. var light = _a[_i];
  17653. if (!light.isEnabled()) {
  17654. continue;
  17655. }
  17656. if (light.canAffectMesh(this)) {
  17657. this._lightSources.push(light);
  17658. }
  17659. }
  17660. this._markSubMeshesAsLightDirty();
  17661. };
  17662. AbstractMesh.prototype._resyncLighSource = function (light) {
  17663. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17664. var index = this._lightSources.indexOf(light);
  17665. if (index === -1) {
  17666. if (!isIn) {
  17667. return;
  17668. }
  17669. this._lightSources.push(light);
  17670. }
  17671. else {
  17672. if (isIn) {
  17673. return;
  17674. }
  17675. this._lightSources.splice(index, 1);
  17676. }
  17677. this._markSubMeshesAsLightDirty();
  17678. };
  17679. AbstractMesh.prototype._removeLightSource = function (light) {
  17680. var index = this._lightSources.indexOf(light);
  17681. if (index === -1) {
  17682. return;
  17683. }
  17684. this._lightSources.splice(index, 1);
  17685. this._markSubMeshesAsLightDirty();
  17686. };
  17687. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17688. if (!this.subMeshes) {
  17689. return;
  17690. }
  17691. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17692. var subMesh = _a[_i];
  17693. if (subMesh._materialDefines) {
  17694. func(subMesh._materialDefines);
  17695. }
  17696. }
  17697. };
  17698. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17699. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17700. };
  17701. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17702. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17703. };
  17704. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17705. if (!this.subMeshes) {
  17706. return;
  17707. }
  17708. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17709. var subMesh = _a[_i];
  17710. var material = subMesh.getMaterial();
  17711. if (material) {
  17712. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17713. }
  17714. }
  17715. };
  17716. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17717. /**
  17718. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17719. * Default : (1.0, 1.0, 1.0)
  17720. */
  17721. get: function () {
  17722. return this._scaling;
  17723. },
  17724. /**
  17725. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17726. * Default : (1.0, 1.0, 1.0)
  17727. */
  17728. set: function (newScaling) {
  17729. this._scaling = newScaling;
  17730. if (this.physicsImpostor) {
  17731. this.physicsImpostor.forceUpdate();
  17732. }
  17733. },
  17734. enumerable: true,
  17735. configurable: true
  17736. });
  17737. // Methods
  17738. /**
  17739. * Disables the mesh edger rendering mode.
  17740. * Returns the AbstractMesh.
  17741. */
  17742. AbstractMesh.prototype.disableEdgesRendering = function () {
  17743. if (this._edgesRenderer) {
  17744. this._edgesRenderer.dispose();
  17745. this._edgesRenderer = null;
  17746. }
  17747. return this;
  17748. };
  17749. /**
  17750. * Enables the edge rendering mode on the mesh.
  17751. * This mode makes the mesh edges visible.
  17752. * Returns the AbstractMesh.
  17753. */
  17754. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17755. if (epsilon === void 0) { epsilon = 0.95; }
  17756. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17757. this.disableEdgesRendering();
  17758. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17759. return this;
  17760. };
  17761. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17762. /**
  17763. * Returns true if the mesh is blocked. Used by the class Mesh.
  17764. * Returns the boolean `false` by default.
  17765. */
  17766. get: function () {
  17767. return false;
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. /**
  17773. * Returns the mesh itself by default, used by the class Mesh.
  17774. * Returned type : AbstractMesh
  17775. */
  17776. AbstractMesh.prototype.getLOD = function (camera) {
  17777. return this;
  17778. };
  17779. /**
  17780. * Returns 0 by default, used by the class Mesh.
  17781. * Returns an integer.
  17782. */
  17783. AbstractMesh.prototype.getTotalVertices = function () {
  17784. return 0;
  17785. };
  17786. /**
  17787. * Returns null by default, used by the class Mesh.
  17788. * Returned type : integer array
  17789. */
  17790. AbstractMesh.prototype.getIndices = function () {
  17791. return null;
  17792. };
  17793. /**
  17794. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17795. * Returned type : float array or Float32Array
  17796. */
  17797. AbstractMesh.prototype.getVerticesData = function (kind) {
  17798. return null;
  17799. };
  17800. /**
  17801. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17802. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17803. * The `data` are either a numeric array either a Float32Array.
  17804. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17805. * 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).
  17806. * Note that a new underlying VertexBuffer object is created each call.
  17807. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17808. *
  17809. * Possible `kind` values :
  17810. * - BABYLON.VertexBuffer.PositionKind
  17811. * - BABYLON.VertexBuffer.UVKind
  17812. * - BABYLON.VertexBuffer.UV2Kind
  17813. * - BABYLON.VertexBuffer.UV3Kind
  17814. * - BABYLON.VertexBuffer.UV4Kind
  17815. * - BABYLON.VertexBuffer.UV5Kind
  17816. * - BABYLON.VertexBuffer.UV6Kind
  17817. * - BABYLON.VertexBuffer.ColorKind
  17818. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17819. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17820. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17821. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17822. *
  17823. * Returns the Mesh.
  17824. */
  17825. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17826. return this;
  17827. };
  17828. /**
  17829. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17830. * If the mesh has no geometry, it is simply returned as it is.
  17831. * The `data` are either a numeric array either a Float32Array.
  17832. * No new underlying VertexBuffer object is created.
  17833. * 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.
  17834. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17835. *
  17836. * Possible `kind` values :
  17837. * - BABYLON.VertexBuffer.PositionKind
  17838. * - BABYLON.VertexBuffer.UVKind
  17839. * - BABYLON.VertexBuffer.UV2Kind
  17840. * - BABYLON.VertexBuffer.UV3Kind
  17841. * - BABYLON.VertexBuffer.UV4Kind
  17842. * - BABYLON.VertexBuffer.UV5Kind
  17843. * - BABYLON.VertexBuffer.UV6Kind
  17844. * - BABYLON.VertexBuffer.ColorKind
  17845. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17846. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17847. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17848. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17849. *
  17850. * Returns the Mesh.
  17851. */
  17852. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17853. return this;
  17854. };
  17855. /**
  17856. * Sets the mesh indices.
  17857. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17858. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17859. * This method creates a new index buffer each call.
  17860. * Returns the Mesh.
  17861. */
  17862. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17863. return this;
  17864. };
  17865. /** Returns false by default, used by the class Mesh.
  17866. * Returns a boolean
  17867. */
  17868. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17869. return false;
  17870. };
  17871. /**
  17872. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17873. * Returns a BoundingInfo
  17874. */
  17875. AbstractMesh.prototype.getBoundingInfo = function () {
  17876. if (this._masterMesh) {
  17877. return this._masterMesh.getBoundingInfo();
  17878. }
  17879. if (!this._boundingInfo) {
  17880. // this._boundingInfo is being created here
  17881. this._updateBoundingInfo();
  17882. }
  17883. // cannot be null.
  17884. return this._boundingInfo;
  17885. };
  17886. /**
  17887. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17888. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17889. */
  17890. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17891. if (includeDescendants === void 0) { includeDescendants = true; }
  17892. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17893. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17894. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17895. if (maxDimension === 0) {
  17896. return this;
  17897. }
  17898. var scale = 1 / maxDimension;
  17899. this.scaling.scaleInPlace(scale);
  17900. return this;
  17901. };
  17902. /**
  17903. * Sets a mesh new object BoundingInfo.
  17904. * Returns the AbstractMesh.
  17905. */
  17906. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17907. this._boundingInfo = boundingInfo;
  17908. return this;
  17909. };
  17910. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17911. get: function () {
  17912. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. AbstractMesh.prototype._preActivate = function () {
  17918. };
  17919. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17920. };
  17921. AbstractMesh.prototype._activate = function (renderId) {
  17922. this._renderId = renderId;
  17923. };
  17924. /**
  17925. * Returns the latest update of the World matrix
  17926. * Returns a Matrix.
  17927. */
  17928. AbstractMesh.prototype.getWorldMatrix = function () {
  17929. if (this._masterMesh) {
  17930. return this._masterMesh.getWorldMatrix();
  17931. }
  17932. return _super.prototype.getWorldMatrix.call(this);
  17933. };
  17934. /**
  17935. * Returns the latest update of the World matrix determinant.
  17936. */
  17937. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17938. if (this._masterMesh) {
  17939. return this._masterMesh._getWorldMatrixDeterminant();
  17940. }
  17941. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17942. };
  17943. // ================================== Point of View Movement =================================
  17944. /**
  17945. * Perform relative position change from the point of view of behind the front of the mesh.
  17946. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17947. * Supports definition of mesh facing forward or backward.
  17948. * @param {number} amountRight
  17949. * @param {number} amountUp
  17950. * @param {number} amountForward
  17951. *
  17952. * Returns the AbstractMesh.
  17953. */
  17954. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17955. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17956. return this;
  17957. };
  17958. /**
  17959. * Calculate relative position change from the point of view of behind the front of the mesh.
  17960. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17961. * Supports definition of mesh facing forward or backward.
  17962. * @param {number} amountRight
  17963. * @param {number} amountUp
  17964. * @param {number} amountForward
  17965. *
  17966. * Returns a new Vector3.
  17967. */
  17968. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17969. var rotMatrix = new BABYLON.Matrix();
  17970. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17971. rotQuaternion.toRotationMatrix(rotMatrix);
  17972. var translationDelta = BABYLON.Vector3.Zero();
  17973. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17974. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17975. return translationDelta;
  17976. };
  17977. // ================================== Point of View Rotation =================================
  17978. /**
  17979. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17980. * Supports definition of mesh facing forward or backward.
  17981. * @param {number} flipBack
  17982. * @param {number} twirlClockwise
  17983. * @param {number} tiltRight
  17984. *
  17985. * Returns the AbstractMesh.
  17986. */
  17987. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17988. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17989. return this;
  17990. };
  17991. /**
  17992. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17993. * Supports definition of mesh facing forward or backward.
  17994. * @param {number} flipBack
  17995. * @param {number} twirlClockwise
  17996. * @param {number} tiltRight
  17997. *
  17998. * Returns a new Vector3.
  17999. */
  18000. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18001. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18002. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18003. };
  18004. /**
  18005. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18006. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18007. */
  18008. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18009. if (includeDescendants === void 0) { includeDescendants = true; }
  18010. this.computeWorldMatrix(true);
  18011. var min;
  18012. var max;
  18013. var boundingInfo = this.getBoundingInfo();
  18014. if (!this.subMeshes) {
  18015. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18016. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18017. }
  18018. else {
  18019. min = boundingInfo.boundingBox.minimumWorld;
  18020. max = boundingInfo.boundingBox.maximumWorld;
  18021. }
  18022. if (includeDescendants) {
  18023. var descendants = this.getDescendants(false);
  18024. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18025. var descendant = descendants_1[_i];
  18026. var childMesh = descendant;
  18027. childMesh.computeWorldMatrix(true);
  18028. //make sure we have the needed params to get mix and max
  18029. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18030. continue;
  18031. }
  18032. var childBoundingInfo = childMesh.getBoundingInfo();
  18033. var boundingBox = childBoundingInfo.boundingBox;
  18034. var minBox = boundingBox.minimumWorld;
  18035. var maxBox = boundingBox.maximumWorld;
  18036. BABYLON.Tools.CheckExtends(minBox, min, max);
  18037. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18038. }
  18039. }
  18040. return {
  18041. min: min,
  18042. max: max
  18043. };
  18044. };
  18045. /**
  18046. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18047. * Returns the AbstractMesh.
  18048. */
  18049. AbstractMesh.prototype._updateBoundingInfo = function () {
  18050. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18051. this._boundingInfo.update(this.worldMatrixFromCache);
  18052. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18053. return this;
  18054. };
  18055. /**
  18056. * Update a mesh's children BoundingInfo objects only.
  18057. * Returns the AbstractMesh.
  18058. */
  18059. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18060. if (!this.subMeshes) {
  18061. return this;
  18062. }
  18063. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18064. var subMesh = this.subMeshes[subIndex];
  18065. if (!subMesh.IsGlobal) {
  18066. subMesh.updateBoundingInfo(matrix);
  18067. }
  18068. }
  18069. return this;
  18070. };
  18071. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18072. // Bounding info
  18073. this._updateBoundingInfo();
  18074. };
  18075. /**
  18076. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18077. * A mesh is in the frustum if its bounding box intersects the frustum.
  18078. * Boolean returned.
  18079. */
  18080. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18081. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18082. };
  18083. /**
  18084. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18085. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18086. * Boolean returned.
  18087. */
  18088. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18089. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18090. ;
  18091. };
  18092. /**
  18093. * True if the mesh intersects another mesh or a SolidParticle object.
  18094. * 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)
  18095. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18096. * Returns a boolean.
  18097. */
  18098. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18099. if (precise === void 0) { precise = false; }
  18100. if (!this._boundingInfo || !mesh._boundingInfo) {
  18101. return false;
  18102. }
  18103. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18104. return true;
  18105. }
  18106. if (includeDescendants) {
  18107. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18108. var child = _a[_i];
  18109. if (child.intersectsMesh(mesh, precise, true)) {
  18110. return true;
  18111. }
  18112. }
  18113. }
  18114. return false;
  18115. };
  18116. /**
  18117. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18118. * Returns a boolean.
  18119. */
  18120. AbstractMesh.prototype.intersectsPoint = function (point) {
  18121. if (!this._boundingInfo) {
  18122. return false;
  18123. }
  18124. return this._boundingInfo.intersectsPoint(point);
  18125. };
  18126. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18127. return this.physicsImpostor;
  18128. };
  18129. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18130. if (camera === void 0) { camera = null; }
  18131. if (!camera) {
  18132. camera = this.getScene().activeCamera;
  18133. }
  18134. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18135. };
  18136. /**
  18137. * Returns the distance from the mesh to the active camera.
  18138. * Returns a float.
  18139. */
  18140. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18141. if (camera === void 0) { camera = null; }
  18142. if (!camera) {
  18143. camera = this.getScene().activeCamera;
  18144. }
  18145. return this.absolutePosition.subtract(camera.position).length();
  18146. };
  18147. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18148. if (!this.physicsImpostor) {
  18149. return this;
  18150. }
  18151. this.physicsImpostor.applyImpulse(force, contactPoint);
  18152. return this;
  18153. };
  18154. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18155. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18156. return this;
  18157. }
  18158. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18159. mainPivot: pivot1,
  18160. connectedPivot: pivot2,
  18161. nativeParams: options
  18162. });
  18163. return this;
  18164. };
  18165. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18166. // Collisions
  18167. /**
  18168. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18169. * Default `false`.
  18170. */
  18171. get: function () {
  18172. return this._checkCollisions;
  18173. },
  18174. set: function (collisionEnabled) {
  18175. this._checkCollisions = collisionEnabled;
  18176. if (this.getScene().workerCollisions) {
  18177. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18178. }
  18179. },
  18180. enumerable: true,
  18181. configurable: true
  18182. });
  18183. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18184. /**
  18185. * Gets Collider object used to compute collisions (not physics)
  18186. */
  18187. get: function () {
  18188. return this._collider;
  18189. },
  18190. enumerable: true,
  18191. configurable: true
  18192. });
  18193. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18194. var globalPosition = this.getAbsolutePosition();
  18195. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18196. if (!this._collider) {
  18197. this._collider = new BABYLON.Collider();
  18198. }
  18199. this._collider._radius = this.ellipsoid;
  18200. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18201. return this;
  18202. };
  18203. // Submeshes octree
  18204. /**
  18205. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18206. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18207. * Returns an Octree of submeshes.
  18208. */
  18209. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18210. if (maxCapacity === void 0) { maxCapacity = 64; }
  18211. if (maxDepth === void 0) { maxDepth = 2; }
  18212. if (!this._submeshesOctree) {
  18213. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18214. }
  18215. this.computeWorldMatrix(true);
  18216. var boundingInfo = this.getBoundingInfo();
  18217. // Update octree
  18218. var bbox = boundingInfo.boundingBox;
  18219. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18220. return this._submeshesOctree;
  18221. };
  18222. // Collisions
  18223. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18224. this._generatePointsArray();
  18225. if (!this._positions) {
  18226. return this;
  18227. }
  18228. // Transformation
  18229. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18230. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18231. subMesh._lastColliderWorldVertices = [];
  18232. subMesh._trianglePlanes = [];
  18233. var start = subMesh.verticesStart;
  18234. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18235. for (var i = start; i < end; i++) {
  18236. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18237. }
  18238. }
  18239. // Collide
  18240. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18241. if (collider.collisionFound) {
  18242. collider.collidedMesh = this;
  18243. }
  18244. return this;
  18245. };
  18246. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18247. var subMeshes;
  18248. var len;
  18249. // Octrees
  18250. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18251. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18252. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18253. len = intersections.length;
  18254. subMeshes = intersections.data;
  18255. }
  18256. else {
  18257. subMeshes = this.subMeshes;
  18258. len = subMeshes.length;
  18259. }
  18260. for (var index = 0; index < len; index++) {
  18261. var subMesh = subMeshes[index];
  18262. // Bounding test
  18263. if (len > 1 && !subMesh._checkCollision(collider))
  18264. continue;
  18265. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18266. }
  18267. return this;
  18268. };
  18269. AbstractMesh.prototype._checkCollision = function (collider) {
  18270. // Bounding box test
  18271. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18272. return this;
  18273. // Transformation matrix
  18274. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18275. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18276. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18277. return this;
  18278. };
  18279. // Picking
  18280. AbstractMesh.prototype._generatePointsArray = function () {
  18281. return false;
  18282. };
  18283. /**
  18284. * Checks if the passed Ray intersects with the mesh.
  18285. * Returns an object PickingInfo.
  18286. */
  18287. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18288. var pickingInfo = new BABYLON.PickingInfo();
  18289. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18290. return pickingInfo;
  18291. }
  18292. if (!this._generatePointsArray()) {
  18293. return pickingInfo;
  18294. }
  18295. var intersectInfo = null;
  18296. // Octrees
  18297. var subMeshes;
  18298. var len;
  18299. if (this._submeshesOctree && this.useOctreeForPicking) {
  18300. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18301. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18302. len = intersections.length;
  18303. subMeshes = intersections.data;
  18304. }
  18305. else {
  18306. subMeshes = this.subMeshes;
  18307. len = subMeshes.length;
  18308. }
  18309. for (var index = 0; index < len; index++) {
  18310. var subMesh = subMeshes[index];
  18311. // Bounding test
  18312. if (len > 1 && !subMesh.canIntersects(ray))
  18313. continue;
  18314. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18315. if (currentIntersectInfo) {
  18316. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18317. intersectInfo = currentIntersectInfo;
  18318. intersectInfo.subMeshId = index;
  18319. if (fastCheck) {
  18320. break;
  18321. }
  18322. }
  18323. }
  18324. }
  18325. if (intersectInfo) {
  18326. // Get picked point
  18327. var world = this.getWorldMatrix();
  18328. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18329. var direction = ray.direction.clone();
  18330. direction = direction.scale(intersectInfo.distance);
  18331. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18332. var pickedPoint = worldOrigin.add(worldDirection);
  18333. // Return result
  18334. pickingInfo.hit = true;
  18335. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18336. pickingInfo.pickedPoint = pickedPoint;
  18337. pickingInfo.pickedMesh = this;
  18338. pickingInfo.bu = intersectInfo.bu || 0;
  18339. pickingInfo.bv = intersectInfo.bv || 0;
  18340. pickingInfo.faceId = intersectInfo.faceId;
  18341. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18342. return pickingInfo;
  18343. }
  18344. return pickingInfo;
  18345. };
  18346. /**
  18347. * Clones the mesh, used by the class Mesh.
  18348. * Just returns `null` for an AbstractMesh.
  18349. */
  18350. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18351. return null;
  18352. };
  18353. /**
  18354. * Disposes all the mesh submeshes.
  18355. * Returns the AbstractMesh.
  18356. */
  18357. AbstractMesh.prototype.releaseSubMeshes = function () {
  18358. if (this.subMeshes) {
  18359. while (this.subMeshes.length) {
  18360. this.subMeshes[0].dispose();
  18361. }
  18362. }
  18363. else {
  18364. this.subMeshes = new Array();
  18365. }
  18366. return this;
  18367. };
  18368. /**
  18369. * Disposes the AbstractMesh.
  18370. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18371. * Returns nothing.
  18372. */
  18373. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18374. var _this = this;
  18375. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18376. var index;
  18377. // Action manager
  18378. if (this.actionManager !== undefined && this.actionManager !== null) {
  18379. this.actionManager.dispose();
  18380. this.actionManager = null;
  18381. }
  18382. // Skeleton
  18383. this.skeleton = null;
  18384. // Physics
  18385. if (this.physicsImpostor) {
  18386. this.physicsImpostor.dispose();
  18387. }
  18388. // Intersections in progress
  18389. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18390. var other = this._intersectionsInProgress[index];
  18391. var pos = other._intersectionsInProgress.indexOf(this);
  18392. other._intersectionsInProgress.splice(pos, 1);
  18393. }
  18394. this._intersectionsInProgress = [];
  18395. // Lights
  18396. var lights = this.getScene().lights;
  18397. lights.forEach(function (light) {
  18398. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18399. if (meshIndex !== -1) {
  18400. light.includedOnlyMeshes.splice(meshIndex, 1);
  18401. }
  18402. meshIndex = light.excludedMeshes.indexOf(_this);
  18403. if (meshIndex !== -1) {
  18404. light.excludedMeshes.splice(meshIndex, 1);
  18405. }
  18406. // Shadow generators
  18407. var generator = light.getShadowGenerator();
  18408. if (generator) {
  18409. var shadowMap = generator.getShadowMap();
  18410. if (shadowMap && shadowMap.renderList) {
  18411. meshIndex = shadowMap.renderList.indexOf(_this);
  18412. if (meshIndex !== -1) {
  18413. shadowMap.renderList.splice(meshIndex, 1);
  18414. }
  18415. }
  18416. }
  18417. });
  18418. // Edges
  18419. if (this._edgesRenderer) {
  18420. this._edgesRenderer.dispose();
  18421. this._edgesRenderer = null;
  18422. }
  18423. // SubMeshes
  18424. if (this.getClassName() !== "InstancedMesh") {
  18425. this.releaseSubMeshes();
  18426. }
  18427. // Octree
  18428. var sceneOctree = this.getScene().selectionOctree;
  18429. if (sceneOctree !== undefined && sceneOctree !== null) {
  18430. var index = sceneOctree.dynamicContent.indexOf(this);
  18431. if (index !== -1) {
  18432. sceneOctree.dynamicContent.splice(index, 1);
  18433. }
  18434. }
  18435. // Query
  18436. var engine = this.getScene().getEngine();
  18437. if (this._occlusionQuery) {
  18438. this._isOcclusionQueryInProgress = false;
  18439. engine.deleteQuery(this._occlusionQuery);
  18440. this._occlusionQuery = null;
  18441. }
  18442. // Engine
  18443. engine.wipeCaches();
  18444. // Remove from scene
  18445. this.getScene().removeMesh(this);
  18446. if (disposeMaterialAndTextures) {
  18447. if (this.material) {
  18448. this.material.dispose(false, true);
  18449. }
  18450. }
  18451. if (!doNotRecurse) {
  18452. // Particles
  18453. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18454. if (this.getScene().particleSystems[index].emitter === this) {
  18455. this.getScene().particleSystems[index].dispose();
  18456. index--;
  18457. }
  18458. }
  18459. }
  18460. // facet data
  18461. if (this._facetDataEnabled) {
  18462. this.disableFacetData();
  18463. }
  18464. this.onAfterWorldMatrixUpdateObservable.clear();
  18465. this.onCollideObservable.clear();
  18466. this.onCollisionPositionChangeObservable.clear();
  18467. _super.prototype.dispose.call(this, doNotRecurse);
  18468. };
  18469. /**
  18470. * Adds the passed mesh as a child to the current mesh.
  18471. * Returns the AbstractMesh.
  18472. */
  18473. AbstractMesh.prototype.addChild = function (mesh) {
  18474. mesh.setParent(this);
  18475. return this;
  18476. };
  18477. /**
  18478. * Removes the passed mesh from the current mesh children list.
  18479. * Returns the AbstractMesh.
  18480. */
  18481. AbstractMesh.prototype.removeChild = function (mesh) {
  18482. mesh.setParent(null);
  18483. return this;
  18484. };
  18485. // Facet data
  18486. /**
  18487. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18488. * Returns the AbstractMesh.
  18489. */
  18490. AbstractMesh.prototype._initFacetData = function () {
  18491. if (!this._facetNormals) {
  18492. this._facetNormals = new Array();
  18493. }
  18494. if (!this._facetPositions) {
  18495. this._facetPositions = new Array();
  18496. }
  18497. if (!this._facetPartitioning) {
  18498. this._facetPartitioning = new Array();
  18499. }
  18500. this._facetNb = (this.getIndices().length / 3) | 0;
  18501. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18502. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18503. for (var f = 0; f < this._facetNb; f++) {
  18504. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18505. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18506. }
  18507. this._facetDataEnabled = true;
  18508. return this;
  18509. };
  18510. /**
  18511. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18512. * This method can be called within the render loop.
  18513. * 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.
  18514. * Returns the AbstractMesh.
  18515. */
  18516. AbstractMesh.prototype.updateFacetData = function () {
  18517. if (!this._facetDataEnabled) {
  18518. this._initFacetData();
  18519. }
  18520. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18521. var indices = this.getIndices();
  18522. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18523. var bInfo = this.getBoundingInfo();
  18524. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18525. // init arrays, matrix and sort function on first call
  18526. this._facetDepthSortEnabled = true;
  18527. if (indices instanceof Uint16Array) {
  18528. this._depthSortedIndices = new Uint16Array(indices);
  18529. }
  18530. else if (indices instanceof Uint32Array) {
  18531. this._depthSortedIndices = new Uint32Array(indices);
  18532. }
  18533. else {
  18534. var needs32bits = false;
  18535. for (var i = 0; i < indices.length; i++) {
  18536. if (indices[i] > 65535) {
  18537. needs32bits = true;
  18538. break;
  18539. }
  18540. }
  18541. if (needs32bits) {
  18542. this._depthSortedIndices = new Uint32Array(indices);
  18543. }
  18544. else {
  18545. this._depthSortedIndices = new Uint16Array(indices);
  18546. }
  18547. }
  18548. this._facetDepthSortFunction = function (f1, f2) {
  18549. return (f2.sqDistance - f1.sqDistance);
  18550. };
  18551. if (!this._facetDepthSortFrom) {
  18552. var camera = this.getScene().activeCamera;
  18553. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18554. }
  18555. this._depthSortedFacets = [];
  18556. for (var f = 0; f < this._facetNb; f++) {
  18557. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18558. this._depthSortedFacets.push(depthSortedFacet);
  18559. }
  18560. this._invertedMatrix = BABYLON.Matrix.Identity();
  18561. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18562. }
  18563. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18564. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18565. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18566. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18567. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18568. this._subDiv.max = this._partitioningSubdivisions;
  18569. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18570. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18571. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18572. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18573. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18574. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18575. // set the parameters for ComputeNormals()
  18576. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18577. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18578. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18579. this._facetParameters.bInfo = bInfo;
  18580. this._facetParameters.bbSize = this._bbSize;
  18581. this._facetParameters.subDiv = this._subDiv;
  18582. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18583. this._facetParameters.depthSort = this._facetDepthSort;
  18584. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18585. this.computeWorldMatrix(true);
  18586. this._worldMatrix.invertToRef(this._invertedMatrix);
  18587. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18588. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18589. }
  18590. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18591. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18592. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18593. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18594. var l = (this._depthSortedIndices.length / 3) | 0;
  18595. for (var f = 0; f < l; f++) {
  18596. var sind = this._depthSortedFacets[f].ind;
  18597. this._depthSortedIndices[f * 3] = indices[sind];
  18598. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18599. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18600. }
  18601. this.updateIndices(this._depthSortedIndices);
  18602. }
  18603. return this;
  18604. };
  18605. /**
  18606. * Returns the facetLocalNormals array.
  18607. * The normals are expressed in the mesh local space.
  18608. */
  18609. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18610. if (!this._facetNormals) {
  18611. this.updateFacetData();
  18612. }
  18613. return this._facetNormals;
  18614. };
  18615. /**
  18616. * Returns the facetLocalPositions array.
  18617. * The facet positions are expressed in the mesh local space.
  18618. */
  18619. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18620. if (!this._facetPositions) {
  18621. this.updateFacetData();
  18622. }
  18623. return this._facetPositions;
  18624. };
  18625. /**
  18626. * Returns the facetLocalPartioning array.
  18627. */
  18628. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18629. if (!this._facetPartitioning) {
  18630. this.updateFacetData();
  18631. }
  18632. return this._facetPartitioning;
  18633. };
  18634. /**
  18635. * Returns the i-th facet position in the world system.
  18636. * This method allocates a new Vector3 per call.
  18637. */
  18638. AbstractMesh.prototype.getFacetPosition = function (i) {
  18639. var pos = BABYLON.Vector3.Zero();
  18640. this.getFacetPositionToRef(i, pos);
  18641. return pos;
  18642. };
  18643. /**
  18644. * Sets the reference Vector3 with the i-th facet position in the world system.
  18645. * Returns the AbstractMesh.
  18646. */
  18647. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18648. var localPos = (this.getFacetLocalPositions())[i];
  18649. var world = this.getWorldMatrix();
  18650. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18651. return this;
  18652. };
  18653. /**
  18654. * Returns the i-th facet normal in the world system.
  18655. * This method allocates a new Vector3 per call.
  18656. */
  18657. AbstractMesh.prototype.getFacetNormal = function (i) {
  18658. var norm = BABYLON.Vector3.Zero();
  18659. this.getFacetNormalToRef(i, norm);
  18660. return norm;
  18661. };
  18662. /**
  18663. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18664. * Returns the AbstractMesh.
  18665. */
  18666. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18667. var localNorm = (this.getFacetLocalNormals())[i];
  18668. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18669. return this;
  18670. };
  18671. /**
  18672. * 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).
  18673. */
  18674. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18675. var bInfo = this.getBoundingInfo();
  18676. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18677. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18678. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18679. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18680. return null;
  18681. }
  18682. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18683. };
  18684. /**
  18685. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18686. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18687. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18688. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18689. * 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.
  18690. */
  18691. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18692. if (checkFace === void 0) { checkFace = false; }
  18693. if (facing === void 0) { facing = true; }
  18694. var world = this.getWorldMatrix();
  18695. var invMat = BABYLON.Tmp.Matrix[5];
  18696. world.invertToRef(invMat);
  18697. var invVect = BABYLON.Tmp.Vector3[8];
  18698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18699. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18700. if (projected) {
  18701. // tranform the local computed projected vector to world coordinates
  18702. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18703. }
  18704. return closest;
  18705. };
  18706. /**
  18707. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18708. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18709. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  18710. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18711. * 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.
  18712. */
  18713. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18714. if (checkFace === void 0) { checkFace = false; }
  18715. if (facing === void 0) { facing = true; }
  18716. var closest = null;
  18717. var tmpx = 0.0;
  18718. var tmpy = 0.0;
  18719. var tmpz = 0.0;
  18720. var d = 0.0; // tmp dot facet normal * facet position
  18721. var t0 = 0.0;
  18722. var projx = 0.0;
  18723. var projy = 0.0;
  18724. var projz = 0.0;
  18725. // Get all the facets in the same partitioning block than (x, y, z)
  18726. var facetPositions = this.getFacetLocalPositions();
  18727. var facetNormals = this.getFacetLocalNormals();
  18728. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18729. if (!facetsInBlock) {
  18730. return null;
  18731. }
  18732. // Get the closest facet to (x, y, z)
  18733. var shortest = Number.MAX_VALUE; // init distance vars
  18734. var tmpDistance = shortest;
  18735. var fib; // current facet in the block
  18736. var norm; // current facet normal
  18737. var p0; // current facet barycenter position
  18738. // loop on all the facets in the current partitioning block
  18739. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18740. fib = facetsInBlock[idx];
  18741. norm = facetNormals[fib];
  18742. p0 = facetPositions[fib];
  18743. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18744. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18745. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18746. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18747. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18748. projx = x + norm.x * t0;
  18749. projy = y + norm.y * t0;
  18750. projz = z + norm.z * t0;
  18751. tmpx = projx - x;
  18752. tmpy = projy - y;
  18753. tmpz = projz - z;
  18754. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18755. if (tmpDistance < shortest) {
  18756. shortest = tmpDistance;
  18757. closest = fib;
  18758. if (projected) {
  18759. projected.x = projx;
  18760. projected.y = projy;
  18761. projected.z = projz;
  18762. }
  18763. }
  18764. }
  18765. }
  18766. return closest;
  18767. };
  18768. /**
  18769. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18770. */
  18771. AbstractMesh.prototype.getFacetDataParameters = function () {
  18772. return this._facetParameters;
  18773. };
  18774. /**
  18775. * Disables the feature FacetData and frees the related memory.
  18776. * Returns the AbstractMesh.
  18777. */
  18778. AbstractMesh.prototype.disableFacetData = function () {
  18779. if (this._facetDataEnabled) {
  18780. this._facetDataEnabled = false;
  18781. this._facetPositions = new Array();
  18782. this._facetNormals = new Array();
  18783. this._facetPartitioning = new Array();
  18784. this._facetParameters = null;
  18785. this._depthSortedIndices = new Uint32Array(0);
  18786. }
  18787. return this;
  18788. };
  18789. /**
  18790. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18791. * Returns the mesh.
  18792. */
  18793. AbstractMesh.prototype.updateIndices = function (indices) {
  18794. return this;
  18795. };
  18796. /**
  18797. * The mesh Geometry. Actually used by the Mesh object.
  18798. * Returns a blank geometry object.
  18799. */
  18800. /**
  18801. * Creates new normals data for the mesh.
  18802. * @param updatable.
  18803. */
  18804. AbstractMesh.prototype.createNormals = function (updatable) {
  18805. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18806. var indices = this.getIndices();
  18807. var normals;
  18808. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18809. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18810. }
  18811. else {
  18812. normals = [];
  18813. }
  18814. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18815. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18816. };
  18817. /**
  18818. * Align the mesh with a normal.
  18819. * Returns the mesh.
  18820. */
  18821. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18822. if (!upDirection) {
  18823. upDirection = BABYLON.Axis.Y;
  18824. }
  18825. var axisX = BABYLON.Tmp.Vector3[0];
  18826. var axisZ = BABYLON.Tmp.Vector3[1];
  18827. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18828. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18829. if (this.rotationQuaternion) {
  18830. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18831. }
  18832. else {
  18833. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18834. }
  18835. return this;
  18836. };
  18837. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18838. var engine = this.getEngine();
  18839. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18840. this._isOccluded = false;
  18841. return;
  18842. }
  18843. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18844. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18845. if (isOcclusionQueryAvailable) {
  18846. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18847. this._isOcclusionQueryInProgress = false;
  18848. this._occlusionInternalRetryCounter = 0;
  18849. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18850. }
  18851. else {
  18852. this._occlusionInternalRetryCounter++;
  18853. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18854. this._isOcclusionQueryInProgress = false;
  18855. this._occlusionInternalRetryCounter = 0;
  18856. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18857. // if strict continue the last state of the object.
  18858. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18859. }
  18860. else {
  18861. return;
  18862. }
  18863. }
  18864. }
  18865. var scene = this.getScene();
  18866. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18867. if (!this._occlusionQuery) {
  18868. this._occlusionQuery = engine.createQuery();
  18869. }
  18870. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18871. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18872. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18873. this._isOcclusionQueryInProgress = true;
  18874. };
  18875. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18876. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18877. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18878. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18879. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18880. return AbstractMesh;
  18881. }(BABYLON.TransformNode));
  18882. BABYLON.AbstractMesh = AbstractMesh;
  18883. })(BABYLON || (BABYLON = {}));
  18884. //# sourceMappingURL=babylon.abstractMesh.js.map
  18885. var BABYLON;
  18886. (function (BABYLON) {
  18887. /**
  18888. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18889. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18890. * 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.
  18891. */
  18892. var Light = /** @class */ (function (_super) {
  18893. __extends(Light, _super);
  18894. /**
  18895. * Creates a Light object in the scene.
  18896. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18897. * @param name The firendly name of the light
  18898. * @param scene The scene the light belongs too
  18899. */
  18900. function Light(name, scene) {
  18901. var _this = _super.call(this, name, scene) || this;
  18902. /**
  18903. * Diffuse gives the basic color to an object.
  18904. */
  18905. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18906. /**
  18907. * Specular produces a highlight color on an object.
  18908. * Note: This is note affecting PBR materials.
  18909. */
  18910. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18911. /**
  18912. * Strength of the light.
  18913. * Note: By default it is define in the framework own unit.
  18914. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18915. */
  18916. _this.intensity = 1.0;
  18917. /**
  18918. * Defines how far from the source the light is impacting in scene units.
  18919. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18920. */
  18921. _this.range = Number.MAX_VALUE;
  18922. /**
  18923. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18924. * of light.
  18925. */
  18926. _this._photometricScale = 1.0;
  18927. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18928. _this._radius = 0.00001;
  18929. /**
  18930. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18931. * exceeding the number allowed of the materials.
  18932. */
  18933. _this.renderPriority = 0;
  18934. /**
  18935. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18936. * the current shadow generator.
  18937. */
  18938. _this.shadowEnabled = true;
  18939. _this._excludeWithLayerMask = 0;
  18940. _this._includeOnlyWithLayerMask = 0;
  18941. _this._lightmapMode = 0;
  18942. /**
  18943. * @ignore Internal use only.
  18944. */
  18945. _this._excludedMeshesIds = new Array();
  18946. /**
  18947. * @ignore Internal use only.
  18948. */
  18949. _this._includedOnlyMeshesIds = new Array();
  18950. _this.getScene().addLight(_this);
  18951. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18952. _this._buildUniformLayout();
  18953. _this.includedOnlyMeshes = new Array();
  18954. _this.excludedMeshes = new Array();
  18955. _this._resyncMeshes();
  18956. return _this;
  18957. }
  18958. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18959. /**
  18960. * If every light affecting the material is in this lightmapMode,
  18961. * material.lightmapTexture adds or multiplies
  18962. * (depends on material.useLightmapAsShadowmap)
  18963. * after every other light calculations.
  18964. */
  18965. get: function () {
  18966. return Light._LIGHTMAP_DEFAULT;
  18967. },
  18968. enumerable: true,
  18969. configurable: true
  18970. });
  18971. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18972. /**
  18973. * material.lightmapTexture as only diffuse lighting from this light
  18974. * adds only specular lighting from this light
  18975. * adds dynamic shadows
  18976. */
  18977. get: function () {
  18978. return Light._LIGHTMAP_SPECULAR;
  18979. },
  18980. enumerable: true,
  18981. configurable: true
  18982. });
  18983. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18984. /**
  18985. * material.lightmapTexture as only lighting
  18986. * no light calculation from this light
  18987. * only adds dynamic shadows from this light
  18988. */
  18989. get: function () {
  18990. return Light._LIGHTMAP_SHADOWSONLY;
  18991. },
  18992. enumerable: true,
  18993. configurable: true
  18994. });
  18995. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18996. /**
  18997. * Each light type uses the default quantity according to its type:
  18998. * point/spot lights use luminous intensity
  18999. * directional lights use illuminance
  19000. */
  19001. get: function () {
  19002. return Light._INTENSITYMODE_AUTOMATIC;
  19003. },
  19004. enumerable: true,
  19005. configurable: true
  19006. });
  19007. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19008. /**
  19009. * lumen (lm)
  19010. */
  19011. get: function () {
  19012. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19013. },
  19014. enumerable: true,
  19015. configurable: true
  19016. });
  19017. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19018. /**
  19019. * candela (lm/sr)
  19020. */
  19021. get: function () {
  19022. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19023. },
  19024. enumerable: true,
  19025. configurable: true
  19026. });
  19027. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19028. /**
  19029. * lux (lm/m^2)
  19030. */
  19031. get: function () {
  19032. return Light._INTENSITYMODE_ILLUMINANCE;
  19033. },
  19034. enumerable: true,
  19035. configurable: true
  19036. });
  19037. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19038. /**
  19039. * nit (cd/m^2)
  19040. */
  19041. get: function () {
  19042. return Light._INTENSITYMODE_LUMINANCE;
  19043. },
  19044. enumerable: true,
  19045. configurable: true
  19046. });
  19047. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19048. /**
  19049. * Light type const id of the point light.
  19050. */
  19051. get: function () {
  19052. return Light._LIGHTTYPEID_POINTLIGHT;
  19053. },
  19054. enumerable: true,
  19055. configurable: true
  19056. });
  19057. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19058. /**
  19059. * Light type const id of the directional light.
  19060. */
  19061. get: function () {
  19062. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19068. /**
  19069. * Light type const id of the spot light.
  19070. */
  19071. get: function () {
  19072. return Light._LIGHTTYPEID_SPOTLIGHT;
  19073. },
  19074. enumerable: true,
  19075. configurable: true
  19076. });
  19077. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19078. /**
  19079. * Light type const id of the hemispheric light.
  19080. */
  19081. get: function () {
  19082. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(Light.prototype, "intensityMode", {
  19088. /**
  19089. * Gets the photometric scale used to interpret the intensity.
  19090. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19091. */
  19092. get: function () {
  19093. return this._intensityMode;
  19094. },
  19095. /**
  19096. * Sets the photometric scale used to interpret the intensity.
  19097. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19098. */
  19099. set: function (value) {
  19100. this._intensityMode = value;
  19101. this._computePhotometricScale();
  19102. },
  19103. enumerable: true,
  19104. configurable: true
  19105. });
  19106. ;
  19107. ;
  19108. Object.defineProperty(Light.prototype, "radius", {
  19109. /**
  19110. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19111. */
  19112. get: function () {
  19113. return this._radius;
  19114. },
  19115. /**
  19116. * sets the light radius used by PBR Materials to simulate soft area lights.
  19117. */
  19118. set: function (value) {
  19119. this._radius = value;
  19120. this._computePhotometricScale();
  19121. },
  19122. enumerable: true,
  19123. configurable: true
  19124. });
  19125. ;
  19126. ;
  19127. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19128. /**
  19129. * Gets the only meshes impacted by this light.
  19130. */
  19131. get: function () {
  19132. return this._includedOnlyMeshes;
  19133. },
  19134. /**
  19135. * Sets the only meshes impacted by this light.
  19136. */
  19137. set: function (value) {
  19138. this._includedOnlyMeshes = value;
  19139. this._hookArrayForIncludedOnly(value);
  19140. },
  19141. enumerable: true,
  19142. configurable: true
  19143. });
  19144. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19145. /**
  19146. * Gets the meshes not impacted by this light.
  19147. */
  19148. get: function () {
  19149. return this._excludedMeshes;
  19150. },
  19151. /**
  19152. * Sets the meshes not impacted by this light.
  19153. */
  19154. set: function (value) {
  19155. this._excludedMeshes = value;
  19156. this._hookArrayForExcluded(value);
  19157. },
  19158. enumerable: true,
  19159. configurable: true
  19160. });
  19161. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19162. /**
  19163. * Gets the layer id use to find what meshes are not impacted by the light.
  19164. * Inactive if 0
  19165. */
  19166. get: function () {
  19167. return this._excludeWithLayerMask;
  19168. },
  19169. /**
  19170. * Sets the layer id use to find what meshes are not impacted by the light.
  19171. * Inactive if 0
  19172. */
  19173. set: function (value) {
  19174. this._excludeWithLayerMask = value;
  19175. this._resyncMeshes();
  19176. },
  19177. enumerable: true,
  19178. configurable: true
  19179. });
  19180. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19181. /**
  19182. * Gets the layer id use to find what meshes are impacted by the light.
  19183. * Inactive if 0
  19184. */
  19185. get: function () {
  19186. return this._includeOnlyWithLayerMask;
  19187. },
  19188. /**
  19189. * Sets the layer id use to find what meshes are impacted by the light.
  19190. * Inactive if 0
  19191. */
  19192. set: function (value) {
  19193. this._includeOnlyWithLayerMask = value;
  19194. this._resyncMeshes();
  19195. },
  19196. enumerable: true,
  19197. configurable: true
  19198. });
  19199. Object.defineProperty(Light.prototype, "lightmapMode", {
  19200. /**
  19201. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19202. */
  19203. get: function () {
  19204. return this._lightmapMode;
  19205. },
  19206. /**
  19207. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19208. */
  19209. set: function (value) {
  19210. if (this._lightmapMode === value) {
  19211. return;
  19212. }
  19213. this._lightmapMode = value;
  19214. this._markMeshesAsLightDirty();
  19215. },
  19216. enumerable: true,
  19217. configurable: true
  19218. });
  19219. /**
  19220. * Returns the string "Light".
  19221. * @returns the class name
  19222. */
  19223. Light.prototype.getClassName = function () {
  19224. return "Light";
  19225. };
  19226. /**
  19227. * Converts the light information to a readable string for debug purpose.
  19228. * @param fullDetails Supports for multiple levels of logging within scene loading
  19229. * @returns the human readable light info
  19230. */
  19231. Light.prototype.toString = function (fullDetails) {
  19232. var ret = "Name: " + this.name;
  19233. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19234. if (this.animations) {
  19235. for (var i = 0; i < this.animations.length; i++) {
  19236. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19237. }
  19238. }
  19239. if (fullDetails) {
  19240. }
  19241. return ret;
  19242. };
  19243. /**
  19244. * Set the enabled state of this node.
  19245. * @param value - the new enabled state
  19246. * @see isEnabled
  19247. */
  19248. Light.prototype.setEnabled = function (value) {
  19249. _super.prototype.setEnabled.call(this, value);
  19250. this._resyncMeshes();
  19251. };
  19252. /**
  19253. * Returns the Light associated shadow generator if any.
  19254. * @return the associated shadow generator.
  19255. */
  19256. Light.prototype.getShadowGenerator = function () {
  19257. return this._shadowGenerator;
  19258. };
  19259. /**
  19260. * Returns a Vector3, the absolute light position in the World.
  19261. * @returns the world space position of the light
  19262. */
  19263. Light.prototype.getAbsolutePosition = function () {
  19264. return BABYLON.Vector3.Zero();
  19265. };
  19266. /**
  19267. * Specifies if the light will affect the passed mesh.
  19268. * @param mesh The mesh to test against the light
  19269. * @return true the mesh is affected otherwise, false.
  19270. */
  19271. Light.prototype.canAffectMesh = function (mesh) {
  19272. if (!mesh) {
  19273. return true;
  19274. }
  19275. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19276. return false;
  19277. }
  19278. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19279. return false;
  19280. }
  19281. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19282. return false;
  19283. }
  19284. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19285. return false;
  19286. }
  19287. return true;
  19288. };
  19289. /**
  19290. * Computes and Returns the light World matrix.
  19291. * @returns the world matrix
  19292. */
  19293. Light.prototype.getWorldMatrix = function () {
  19294. this._currentRenderId = this.getScene().getRenderId();
  19295. var worldMatrix = this._getWorldMatrix();
  19296. if (this.parent && this.parent.getWorldMatrix) {
  19297. if (!this._parentedWorldMatrix) {
  19298. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19299. }
  19300. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19301. this._markSyncedWithParent();
  19302. return this._parentedWorldMatrix;
  19303. }
  19304. return worldMatrix;
  19305. };
  19306. /**
  19307. * Sort function to order lights for rendering.
  19308. * @param a First Light object to compare to second.
  19309. * @param b Second Light object to compare first.
  19310. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19311. */
  19312. Light.CompareLightsPriority = function (a, b) {
  19313. //shadow-casting lights have priority over non-shadow-casting lights
  19314. //the renderPrioirty is a secondary sort criterion
  19315. if (a.shadowEnabled !== b.shadowEnabled) {
  19316. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19317. }
  19318. return b.renderPriority - a.renderPriority;
  19319. };
  19320. /**
  19321. * Disposes the light.
  19322. */
  19323. Light.prototype.dispose = function () {
  19324. if (this._shadowGenerator) {
  19325. this._shadowGenerator.dispose();
  19326. this._shadowGenerator = null;
  19327. }
  19328. // Animations
  19329. this.getScene().stopAnimation(this);
  19330. // Remove from meshes
  19331. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19332. var mesh = _a[_i];
  19333. mesh._removeLightSource(this);
  19334. }
  19335. this._uniformBuffer.dispose();
  19336. // Remove from scene
  19337. this.getScene().removeLight(this);
  19338. _super.prototype.dispose.call(this);
  19339. };
  19340. /**
  19341. * Returns the light type ID (integer).
  19342. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19343. */
  19344. Light.prototype.getTypeID = function () {
  19345. return 0;
  19346. };
  19347. /**
  19348. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19349. * @returns the scaled intensity in intensity mode unit
  19350. */
  19351. Light.prototype.getScaledIntensity = function () {
  19352. return this._photometricScale * this.intensity;
  19353. };
  19354. /**
  19355. * Returns a new Light object, named "name", from the current one.
  19356. * @param name The name of the cloned light
  19357. * @returns the new created light
  19358. */
  19359. Light.prototype.clone = function (name) {
  19360. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19361. if (!constructor) {
  19362. return null;
  19363. }
  19364. return BABYLON.SerializationHelper.Clone(constructor, this);
  19365. };
  19366. /**
  19367. * Serializes the current light into a Serialization object.
  19368. * @returns the serialized object.
  19369. */
  19370. Light.prototype.serialize = function () {
  19371. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19372. // Type
  19373. serializationObject.type = this.getTypeID();
  19374. // Parent
  19375. if (this.parent) {
  19376. serializationObject.parentId = this.parent.id;
  19377. }
  19378. // Inclusion / exclusions
  19379. if (this.excludedMeshes.length > 0) {
  19380. serializationObject.excludedMeshesIds = [];
  19381. this.excludedMeshes.forEach(function (mesh) {
  19382. serializationObject.excludedMeshesIds.push(mesh.id);
  19383. });
  19384. }
  19385. if (this.includedOnlyMeshes.length > 0) {
  19386. serializationObject.includedOnlyMeshesIds = [];
  19387. this.includedOnlyMeshes.forEach(function (mesh) {
  19388. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19389. });
  19390. }
  19391. // Animations
  19392. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19393. serializationObject.ranges = this.serializeAnimationRanges();
  19394. return serializationObject;
  19395. };
  19396. /**
  19397. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19398. * This new light is named "name" and added to the passed scene.
  19399. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19400. * @param name The friendly name of the light
  19401. * @param scene The scene the new light will belong to
  19402. * @returns the constructor function
  19403. */
  19404. Light.GetConstructorFromName = function (type, name, scene) {
  19405. switch (type) {
  19406. case 0:
  19407. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19408. case 1:
  19409. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19410. case 2:
  19411. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19412. case 3:
  19413. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19414. }
  19415. return null;
  19416. };
  19417. /**
  19418. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19419. * @param parsedLight The JSON representation of the light
  19420. * @param scene The scene to create the parsed light in
  19421. * @returns the created light after parsing
  19422. */
  19423. Light.Parse = function (parsedLight, scene) {
  19424. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19425. if (!constructor) {
  19426. return null;
  19427. }
  19428. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19429. // Inclusion / exclusions
  19430. if (parsedLight.excludedMeshesIds) {
  19431. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19432. }
  19433. if (parsedLight.includedOnlyMeshesIds) {
  19434. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19435. }
  19436. // Parent
  19437. if (parsedLight.parentId) {
  19438. light._waitingParentId = parsedLight.parentId;
  19439. }
  19440. // Animations
  19441. if (parsedLight.animations) {
  19442. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19443. var parsedAnimation = parsedLight.animations[animationIndex];
  19444. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19445. }
  19446. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19447. }
  19448. if (parsedLight.autoAnimate) {
  19449. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19450. }
  19451. return light;
  19452. };
  19453. Light.prototype._hookArrayForExcluded = function (array) {
  19454. var _this = this;
  19455. var oldPush = array.push;
  19456. array.push = function () {
  19457. var items = [];
  19458. for (var _i = 0; _i < arguments.length; _i++) {
  19459. items[_i] = arguments[_i];
  19460. }
  19461. var result = oldPush.apply(array, items);
  19462. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19463. var item = items_1[_a];
  19464. item._resyncLighSource(_this);
  19465. }
  19466. return result;
  19467. };
  19468. var oldSplice = array.splice;
  19469. array.splice = function (index, deleteCount) {
  19470. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19471. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19472. var item = deleted_1[_i];
  19473. item._resyncLighSource(_this);
  19474. }
  19475. return deleted;
  19476. };
  19477. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19478. var item = array_1[_i];
  19479. item._resyncLighSource(this);
  19480. }
  19481. };
  19482. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19483. var _this = this;
  19484. var oldPush = array.push;
  19485. array.push = function () {
  19486. var items = [];
  19487. for (var _i = 0; _i < arguments.length; _i++) {
  19488. items[_i] = arguments[_i];
  19489. }
  19490. var result = oldPush.apply(array, items);
  19491. _this._resyncMeshes();
  19492. return result;
  19493. };
  19494. var oldSplice = array.splice;
  19495. array.splice = function (index, deleteCount) {
  19496. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19497. _this._resyncMeshes();
  19498. return deleted;
  19499. };
  19500. this._resyncMeshes();
  19501. };
  19502. Light.prototype._resyncMeshes = function () {
  19503. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19504. var mesh = _a[_i];
  19505. mesh._resyncLighSource(this);
  19506. }
  19507. };
  19508. /**
  19509. * Forces the meshes to update their light related information in their rendering used effects
  19510. * @ignore Internal Use Only
  19511. */
  19512. Light.prototype._markMeshesAsLightDirty = function () {
  19513. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19514. var mesh = _a[_i];
  19515. if (mesh._lightSources.indexOf(this) !== -1) {
  19516. mesh._markSubMeshesAsLightDirty();
  19517. }
  19518. }
  19519. };
  19520. /**
  19521. * Recomputes the cached photometric scale if needed.
  19522. */
  19523. Light.prototype._computePhotometricScale = function () {
  19524. this._photometricScale = this._getPhotometricScale();
  19525. this.getScene().resetCachedMaterial();
  19526. };
  19527. /**
  19528. * Returns the Photometric Scale according to the light type and intensity mode.
  19529. */
  19530. Light.prototype._getPhotometricScale = function () {
  19531. var photometricScale = 0.0;
  19532. var lightTypeID = this.getTypeID();
  19533. //get photometric mode
  19534. var photometricMode = this.intensityMode;
  19535. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19536. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19537. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19538. }
  19539. else {
  19540. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19541. }
  19542. }
  19543. //compute photometric scale
  19544. switch (lightTypeID) {
  19545. case Light.LIGHTTYPEID_POINTLIGHT:
  19546. case Light.LIGHTTYPEID_SPOTLIGHT:
  19547. switch (photometricMode) {
  19548. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19549. photometricScale = 1.0 / (4.0 * Math.PI);
  19550. break;
  19551. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19552. photometricScale = 1.0;
  19553. break;
  19554. case Light.INTENSITYMODE_LUMINANCE:
  19555. photometricScale = this.radius * this.radius;
  19556. break;
  19557. }
  19558. break;
  19559. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19560. switch (photometricMode) {
  19561. case Light.INTENSITYMODE_ILLUMINANCE:
  19562. photometricScale = 1.0;
  19563. break;
  19564. case Light.INTENSITYMODE_LUMINANCE:
  19565. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19566. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19567. var apexAngleRadians = this.radius;
  19568. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19569. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19570. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19571. photometricScale = solidAngle;
  19572. break;
  19573. }
  19574. break;
  19575. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19576. // No fall off in hemisperic light.
  19577. photometricScale = 1.0;
  19578. break;
  19579. }
  19580. return photometricScale;
  19581. };
  19582. /**
  19583. * Reorder the light in the scene according to their defined priority.
  19584. * @ignore Internal Use Only
  19585. */
  19586. Light.prototype._reorderLightsInScene = function () {
  19587. var scene = this.getScene();
  19588. if (this._renderPriority != 0) {
  19589. scene.requireLightSorting = true;
  19590. }
  19591. this.getScene().sortLightsByPriority();
  19592. };
  19593. //lightmapMode Consts
  19594. Light._LIGHTMAP_DEFAULT = 0;
  19595. Light._LIGHTMAP_SPECULAR = 1;
  19596. Light._LIGHTMAP_SHADOWSONLY = 2;
  19597. // Intensity Mode Consts
  19598. Light._INTENSITYMODE_AUTOMATIC = 0;
  19599. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19600. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19601. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19602. Light._INTENSITYMODE_LUMINANCE = 4;
  19603. // Light types ids const.
  19604. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19605. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19606. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19607. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19608. __decorate([
  19609. BABYLON.serializeAsColor3()
  19610. ], Light.prototype, "diffuse", void 0);
  19611. __decorate([
  19612. BABYLON.serializeAsColor3()
  19613. ], Light.prototype, "specular", void 0);
  19614. __decorate([
  19615. BABYLON.serialize()
  19616. ], Light.prototype, "intensity", void 0);
  19617. __decorate([
  19618. BABYLON.serialize()
  19619. ], Light.prototype, "range", void 0);
  19620. __decorate([
  19621. BABYLON.serialize()
  19622. ], Light.prototype, "intensityMode", null);
  19623. __decorate([
  19624. BABYLON.serialize()
  19625. ], Light.prototype, "radius", null);
  19626. __decorate([
  19627. BABYLON.serialize()
  19628. ], Light.prototype, "_renderPriority", void 0);
  19629. __decorate([
  19630. BABYLON.expandToProperty("_reorderLightsInScene")
  19631. ], Light.prototype, "renderPriority", void 0);
  19632. __decorate([
  19633. BABYLON.serialize()
  19634. ], Light.prototype, "shadowEnabled", void 0);
  19635. __decorate([
  19636. BABYLON.serialize("excludeWithLayerMask")
  19637. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19638. __decorate([
  19639. BABYLON.serialize("includeOnlyWithLayerMask")
  19640. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19641. __decorate([
  19642. BABYLON.serialize("lightmapMode")
  19643. ], Light.prototype, "_lightmapMode", void 0);
  19644. return Light;
  19645. }(BABYLON.Node));
  19646. BABYLON.Light = Light;
  19647. })(BABYLON || (BABYLON = {}));
  19648. //# sourceMappingURL=babylon.light.js.map
  19649. var BABYLON;
  19650. (function (BABYLON) {
  19651. var Camera = /** @class */ (function (_super) {
  19652. __extends(Camera, _super);
  19653. function Camera(name, position, scene) {
  19654. var _this = _super.call(this, name, scene) || this;
  19655. /**
  19656. * The vector the camera should consider as up.
  19657. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19658. */
  19659. _this.upVector = BABYLON.Vector3.Up();
  19660. _this.orthoLeft = null;
  19661. _this.orthoRight = null;
  19662. _this.orthoBottom = null;
  19663. _this.orthoTop = null;
  19664. /**
  19665. * FOV is set in Radians. (default is 0.8)
  19666. */
  19667. _this.fov = 0.8;
  19668. _this.minZ = 1;
  19669. _this.maxZ = 10000.0;
  19670. _this.inertia = 0.9;
  19671. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19672. _this.isIntermediate = false;
  19673. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19674. /**
  19675. * Restricts the camera to viewing objects with the same layerMask.
  19676. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19677. */
  19678. _this.layerMask = 0x0FFFFFFF;
  19679. /**
  19680. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19681. */
  19682. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19683. // Camera rig members
  19684. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19685. _this._rigCameras = new Array();
  19686. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19687. _this._skipRendering = false;
  19688. _this.customRenderTargets = new Array();
  19689. // Observables
  19690. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19691. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19692. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19693. _this.onRestoreStateObservable = new BABYLON.Observable();
  19694. // Cache
  19695. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19696. _this._projectionMatrix = new BABYLON.Matrix();
  19697. _this._doNotComputeProjectionMatrix = false;
  19698. _this._postProcesses = new Array();
  19699. _this._transformMatrix = BABYLON.Matrix.Zero();
  19700. _this._activeMeshes = new BABYLON.SmartArray(256);
  19701. _this._globalPosition = BABYLON.Vector3.Zero();
  19702. _this._refreshFrustumPlanes = true;
  19703. _this.getScene().addCamera(_this);
  19704. if (!_this.getScene().activeCamera) {
  19705. _this.getScene().activeCamera = _this;
  19706. }
  19707. _this.position = position;
  19708. return _this;
  19709. }
  19710. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19711. get: function () {
  19712. return Camera._PERSPECTIVE_CAMERA;
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19718. get: function () {
  19719. return Camera._ORTHOGRAPHIC_CAMERA;
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19725. /**
  19726. * This is the default FOV mode for perspective cameras.
  19727. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19728. *
  19729. */
  19730. get: function () {
  19731. return Camera._FOVMODE_VERTICAL_FIXED;
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19737. /**
  19738. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19739. *
  19740. */
  19741. get: function () {
  19742. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19748. get: function () {
  19749. return Camera._RIG_MODE_NONE;
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19755. get: function () {
  19756. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19762. get: function () {
  19763. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19769. get: function () {
  19770. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19776. get: function () {
  19777. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19783. get: function () {
  19784. return Camera._RIG_MODE_VR;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19790. get: function () {
  19791. return Camera._RIG_MODE_WEBVR;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. /**
  19797. * Store current camera state (fov, position, etc..)
  19798. */
  19799. Camera.prototype.storeState = function () {
  19800. this._stateStored = true;
  19801. this._storedFov = this.fov;
  19802. return this;
  19803. };
  19804. /**
  19805. * Restores the camera state values if it has been stored. You must call storeState() first
  19806. */
  19807. Camera.prototype._restoreStateValues = function () {
  19808. if (!this._stateStored) {
  19809. return false;
  19810. }
  19811. this.fov = this._storedFov;
  19812. return true;
  19813. };
  19814. /**
  19815. * Restored camera state. You must call storeState() first
  19816. */
  19817. Camera.prototype.restoreState = function () {
  19818. if (this._restoreStateValues()) {
  19819. this.onRestoreStateObservable.notifyObservers(this);
  19820. return true;
  19821. }
  19822. return false;
  19823. };
  19824. Camera.prototype.getClassName = function () {
  19825. return "Camera";
  19826. };
  19827. /**
  19828. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19829. */
  19830. Camera.prototype.toString = function (fullDetails) {
  19831. var ret = "Name: " + this.name;
  19832. ret += ", type: " + this.getClassName();
  19833. if (this.animations) {
  19834. for (var i = 0; i < this.animations.length; i++) {
  19835. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19836. }
  19837. }
  19838. if (fullDetails) {
  19839. }
  19840. return ret;
  19841. };
  19842. Object.defineProperty(Camera.prototype, "globalPosition", {
  19843. get: function () {
  19844. return this._globalPosition;
  19845. },
  19846. enumerable: true,
  19847. configurable: true
  19848. });
  19849. Camera.prototype.getActiveMeshes = function () {
  19850. return this._activeMeshes;
  19851. };
  19852. Camera.prototype.isActiveMesh = function (mesh) {
  19853. return (this._activeMeshes.indexOf(mesh) !== -1);
  19854. };
  19855. //Cache
  19856. Camera.prototype._initCache = function () {
  19857. _super.prototype._initCache.call(this);
  19858. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19859. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19860. this._cache.mode = undefined;
  19861. this._cache.minZ = undefined;
  19862. this._cache.maxZ = undefined;
  19863. this._cache.fov = undefined;
  19864. this._cache.fovMode = undefined;
  19865. this._cache.aspectRatio = undefined;
  19866. this._cache.orthoLeft = undefined;
  19867. this._cache.orthoRight = undefined;
  19868. this._cache.orthoBottom = undefined;
  19869. this._cache.orthoTop = undefined;
  19870. this._cache.renderWidth = undefined;
  19871. this._cache.renderHeight = undefined;
  19872. };
  19873. Camera.prototype._updateCache = function (ignoreParentClass) {
  19874. if (!ignoreParentClass) {
  19875. _super.prototype._updateCache.call(this);
  19876. }
  19877. this._cache.position.copyFrom(this.position);
  19878. this._cache.upVector.copyFrom(this.upVector);
  19879. };
  19880. // Synchronized
  19881. Camera.prototype._isSynchronized = function () {
  19882. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19883. };
  19884. Camera.prototype._isSynchronizedViewMatrix = function () {
  19885. if (!_super.prototype._isSynchronized.call(this))
  19886. return false;
  19887. return this._cache.position.equals(this.position)
  19888. && this._cache.upVector.equals(this.upVector)
  19889. && this.isSynchronizedWithParent();
  19890. };
  19891. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19892. var check = this._cache.mode === this.mode
  19893. && this._cache.minZ === this.minZ
  19894. && this._cache.maxZ === this.maxZ;
  19895. if (!check) {
  19896. return false;
  19897. }
  19898. var engine = this.getEngine();
  19899. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19900. check = this._cache.fov === this.fov
  19901. && this._cache.fovMode === this.fovMode
  19902. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19903. }
  19904. else {
  19905. check = this._cache.orthoLeft === this.orthoLeft
  19906. && this._cache.orthoRight === this.orthoRight
  19907. && this._cache.orthoBottom === this.orthoBottom
  19908. && this._cache.orthoTop === this.orthoTop
  19909. && this._cache.renderWidth === engine.getRenderWidth()
  19910. && this._cache.renderHeight === engine.getRenderHeight();
  19911. }
  19912. return check;
  19913. };
  19914. // Controls
  19915. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19916. };
  19917. Camera.prototype.detachControl = function (element) {
  19918. };
  19919. Camera.prototype.update = function () {
  19920. this._checkInputs();
  19921. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19922. this._updateRigCameras();
  19923. }
  19924. };
  19925. Camera.prototype._checkInputs = function () {
  19926. this.onAfterCheckInputsObservable.notifyObservers(this);
  19927. };
  19928. Object.defineProperty(Camera.prototype, "rigCameras", {
  19929. get: function () {
  19930. return this._rigCameras;
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19936. get: function () {
  19937. return this._rigPostProcess;
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19943. // invalidate framebuffer
  19944. if (this._postProcesses.length > 0) {
  19945. this._postProcesses[0].markTextureDirty();
  19946. }
  19947. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19948. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19949. var cam = this._rigCameras[i];
  19950. var rigPostProcess = cam._rigPostProcess;
  19951. // for VR rig, there does not have to be a post process
  19952. if (rigPostProcess) {
  19953. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19954. if (isPass) {
  19955. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19956. cam.isIntermediate = this._postProcesses.length === 0;
  19957. }
  19958. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19959. rigPostProcess.markTextureDirty();
  19960. }
  19961. else {
  19962. cam._postProcesses = this._postProcesses.slice(0);
  19963. }
  19964. }
  19965. };
  19966. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19967. if (insertAt === void 0) { insertAt = null; }
  19968. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19969. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19970. return 0;
  19971. }
  19972. if (insertAt == null || insertAt < 0) {
  19973. this._postProcesses.push(postProcess);
  19974. }
  19975. else {
  19976. this._postProcesses.splice(insertAt, 0, postProcess);
  19977. }
  19978. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19979. return this._postProcesses.indexOf(postProcess);
  19980. };
  19981. Camera.prototype.detachPostProcess = function (postProcess) {
  19982. var idx = this._postProcesses.indexOf(postProcess);
  19983. if (idx !== -1) {
  19984. this._postProcesses.splice(idx, 1);
  19985. }
  19986. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19987. };
  19988. Camera.prototype.getWorldMatrix = function () {
  19989. if (!this._worldMatrix) {
  19990. this._worldMatrix = BABYLON.Matrix.Identity();
  19991. }
  19992. var viewMatrix = this.getViewMatrix();
  19993. viewMatrix.invertToRef(this._worldMatrix);
  19994. return this._worldMatrix;
  19995. };
  19996. Camera.prototype._getViewMatrix = function () {
  19997. return BABYLON.Matrix.Identity();
  19998. };
  19999. Camera.prototype.getViewMatrix = function (force) {
  20000. if (!force && this._isSynchronizedViewMatrix()) {
  20001. return this._computedViewMatrix;
  20002. }
  20003. this.updateCache();
  20004. this._computedViewMatrix = this._getViewMatrix();
  20005. this._currentRenderId = this.getScene().getRenderId();
  20006. this._refreshFrustumPlanes = true;
  20007. if (!this.parent || !this.parent.getWorldMatrix) {
  20008. this._globalPosition.copyFrom(this.position);
  20009. }
  20010. else {
  20011. if (!this._worldMatrix) {
  20012. this._worldMatrix = BABYLON.Matrix.Identity();
  20013. }
  20014. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20015. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20016. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20017. this._computedViewMatrix.invert();
  20018. this._markSyncedWithParent();
  20019. }
  20020. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20021. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20022. }
  20023. this.onViewMatrixChangedObservable.notifyObservers(this);
  20024. return this._computedViewMatrix;
  20025. };
  20026. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20027. this._doNotComputeProjectionMatrix = true;
  20028. if (projection !== undefined) {
  20029. this._projectionMatrix = projection;
  20030. }
  20031. };
  20032. ;
  20033. Camera.prototype.unfreezeProjectionMatrix = function () {
  20034. this._doNotComputeProjectionMatrix = false;
  20035. };
  20036. ;
  20037. Camera.prototype.getProjectionMatrix = function (force) {
  20038. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20039. return this._projectionMatrix;
  20040. }
  20041. // Cache
  20042. this._cache.mode = this.mode;
  20043. this._cache.minZ = this.minZ;
  20044. this._cache.maxZ = this.maxZ;
  20045. // Matrix
  20046. this._refreshFrustumPlanes = true;
  20047. var engine = this.getEngine();
  20048. var scene = this.getScene();
  20049. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20050. this._cache.fov = this.fov;
  20051. this._cache.fovMode = this.fovMode;
  20052. this._cache.aspectRatio = engine.getAspectRatio(this);
  20053. if (this.minZ <= 0) {
  20054. this.minZ = 0.1;
  20055. }
  20056. if (scene.useRightHandedSystem) {
  20057. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20058. }
  20059. else {
  20060. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20061. }
  20062. }
  20063. else {
  20064. var halfWidth = engine.getRenderWidth() / 2.0;
  20065. var halfHeight = engine.getRenderHeight() / 2.0;
  20066. if (scene.useRightHandedSystem) {
  20067. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20068. }
  20069. else {
  20070. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20071. }
  20072. this._cache.orthoLeft = this.orthoLeft;
  20073. this._cache.orthoRight = this.orthoRight;
  20074. this._cache.orthoBottom = this.orthoBottom;
  20075. this._cache.orthoTop = this.orthoTop;
  20076. this._cache.renderWidth = engine.getRenderWidth();
  20077. this._cache.renderHeight = engine.getRenderHeight();
  20078. }
  20079. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20080. return this._projectionMatrix;
  20081. };
  20082. Camera.prototype.getTranformationMatrix = function () {
  20083. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20084. return this._transformMatrix;
  20085. };
  20086. Camera.prototype.updateFrustumPlanes = function () {
  20087. if (!this._refreshFrustumPlanes) {
  20088. return;
  20089. }
  20090. this.getTranformationMatrix();
  20091. if (!this._frustumPlanes) {
  20092. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20093. }
  20094. else {
  20095. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20096. }
  20097. this._refreshFrustumPlanes = false;
  20098. };
  20099. Camera.prototype.isInFrustum = function (target) {
  20100. this.updateFrustumPlanes();
  20101. return target.isInFrustum(this._frustumPlanes);
  20102. };
  20103. Camera.prototype.isCompletelyInFrustum = function (target) {
  20104. this.updateFrustumPlanes();
  20105. return target.isCompletelyInFrustum(this._frustumPlanes);
  20106. };
  20107. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20108. if (length === void 0) { length = 100; }
  20109. if (!transform) {
  20110. transform = this.getWorldMatrix();
  20111. }
  20112. if (!origin) {
  20113. origin = this.position;
  20114. }
  20115. var forward = new BABYLON.Vector3(0, 0, 1);
  20116. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20117. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20118. return new BABYLON.Ray(origin, direction, length);
  20119. };
  20120. Camera.prototype.dispose = function () {
  20121. // Observables
  20122. this.onViewMatrixChangedObservable.clear();
  20123. this.onProjectionMatrixChangedObservable.clear();
  20124. this.onAfterCheckInputsObservable.clear();
  20125. this.onRestoreStateObservable.clear();
  20126. // Inputs
  20127. if (this.inputs) {
  20128. this.inputs.clear();
  20129. }
  20130. // Animations
  20131. this.getScene().stopAnimation(this);
  20132. // Remove from scene
  20133. this.getScene().removeCamera(this);
  20134. while (this._rigCameras.length > 0) {
  20135. var camera = this._rigCameras.pop();
  20136. if (camera) {
  20137. camera.dispose();
  20138. }
  20139. }
  20140. // Postprocesses
  20141. if (this._rigPostProcess) {
  20142. this._rigPostProcess.dispose(this);
  20143. this._rigPostProcess = null;
  20144. this._postProcesses = [];
  20145. }
  20146. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20147. this._rigPostProcess = null;
  20148. this._postProcesses = [];
  20149. }
  20150. else {
  20151. var i = this._postProcesses.length;
  20152. while (--i >= 0) {
  20153. this._postProcesses[i].dispose(this);
  20154. }
  20155. }
  20156. // Render targets
  20157. var i = this.customRenderTargets.length;
  20158. while (--i >= 0) {
  20159. this.customRenderTargets[i].dispose();
  20160. }
  20161. this.customRenderTargets = [];
  20162. // Active Meshes
  20163. this._activeMeshes.dispose();
  20164. _super.prototype.dispose.call(this);
  20165. };
  20166. Object.defineProperty(Camera.prototype, "leftCamera", {
  20167. // ---- Camera rigs section ----
  20168. get: function () {
  20169. if (this._rigCameras.length < 1) {
  20170. return null;
  20171. }
  20172. return this._rigCameras[0];
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(Camera.prototype, "rightCamera", {
  20178. get: function () {
  20179. if (this._rigCameras.length < 2) {
  20180. return null;
  20181. }
  20182. return this._rigCameras[1];
  20183. },
  20184. enumerable: true,
  20185. configurable: true
  20186. });
  20187. Camera.prototype.getLeftTarget = function () {
  20188. if (this._rigCameras.length < 1) {
  20189. return null;
  20190. }
  20191. return this._rigCameras[0].getTarget();
  20192. };
  20193. Camera.prototype.getRightTarget = function () {
  20194. if (this._rigCameras.length < 2) {
  20195. return null;
  20196. }
  20197. return this._rigCameras[1].getTarget();
  20198. };
  20199. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20200. if (this.cameraRigMode === mode) {
  20201. return;
  20202. }
  20203. while (this._rigCameras.length > 0) {
  20204. var camera = this._rigCameras.pop();
  20205. if (camera) {
  20206. camera.dispose();
  20207. }
  20208. }
  20209. this.cameraRigMode = mode;
  20210. this._cameraRigParams = {};
  20211. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20212. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20213. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20214. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20215. // create the rig cameras, unless none
  20216. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20217. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20218. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20219. if (leftCamera && rightCamera) {
  20220. this._rigCameras.push(leftCamera);
  20221. this._rigCameras.push(rightCamera);
  20222. }
  20223. }
  20224. switch (this.cameraRigMode) {
  20225. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20226. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20227. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20228. break;
  20229. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20230. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20231. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20232. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20233. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20234. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20235. break;
  20236. case Camera.RIG_MODE_VR:
  20237. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20238. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20239. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20240. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20241. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20242. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20243. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20244. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20245. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20246. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20247. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20248. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20249. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20250. if (metrics.compensateDistortion) {
  20251. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20252. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20253. }
  20254. break;
  20255. case Camera.RIG_MODE_WEBVR:
  20256. if (rigParams.vrDisplay) {
  20257. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20258. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20259. //Left eye
  20260. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20261. this._rigCameras[0].setCameraRigParameter("left", true);
  20262. //leaving this for future reference
  20263. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20264. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20265. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20266. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20267. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20268. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20269. this._rigCameras[0].parent = this;
  20270. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20271. //Right eye
  20272. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20273. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20274. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20275. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20276. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20277. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20278. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20279. this._rigCameras[1].parent = this;
  20280. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20281. if (Camera.UseAlternateWebVRRendering) {
  20282. this._rigCameras[1]._skipRendering = true;
  20283. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20284. }
  20285. }
  20286. break;
  20287. }
  20288. this._cascadePostProcessesToRigCams();
  20289. this.update();
  20290. };
  20291. Camera.prototype._getVRProjectionMatrix = function () {
  20292. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20293. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20294. return this._projectionMatrix;
  20295. };
  20296. Camera.prototype._updateCameraRotationMatrix = function () {
  20297. //Here for WebVR
  20298. };
  20299. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20300. //Here for WebVR
  20301. };
  20302. /**
  20303. * This function MUST be overwritten by the different WebVR cameras available.
  20304. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20305. */
  20306. Camera.prototype._getWebVRProjectionMatrix = function () {
  20307. return BABYLON.Matrix.Identity();
  20308. };
  20309. /**
  20310. * This function MUST be overwritten by the different WebVR cameras available.
  20311. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20312. */
  20313. Camera.prototype._getWebVRViewMatrix = function () {
  20314. return BABYLON.Matrix.Identity();
  20315. };
  20316. Camera.prototype.setCameraRigParameter = function (name, value) {
  20317. if (!this._cameraRigParams) {
  20318. this._cameraRigParams = {};
  20319. }
  20320. this._cameraRigParams[name] = value;
  20321. //provisionnally:
  20322. if (name === "interaxialDistance") {
  20323. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20324. }
  20325. };
  20326. /**
  20327. * needs to be overridden by children so sub has required properties to be copied
  20328. */
  20329. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20330. return null;
  20331. };
  20332. /**
  20333. * May need to be overridden by children
  20334. */
  20335. Camera.prototype._updateRigCameras = function () {
  20336. for (var i = 0; i < this._rigCameras.length; i++) {
  20337. this._rigCameras[i].minZ = this.minZ;
  20338. this._rigCameras[i].maxZ = this.maxZ;
  20339. this._rigCameras[i].fov = this.fov;
  20340. }
  20341. // only update viewport when ANAGLYPH
  20342. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20343. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20344. }
  20345. };
  20346. Camera.prototype._setupInputs = function () {
  20347. };
  20348. Camera.prototype.serialize = function () {
  20349. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20350. // Type
  20351. serializationObject.type = this.getClassName();
  20352. // Parent
  20353. if (this.parent) {
  20354. serializationObject.parentId = this.parent.id;
  20355. }
  20356. if (this.inputs) {
  20357. this.inputs.serialize(serializationObject);
  20358. }
  20359. // Animations
  20360. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20361. serializationObject.ranges = this.serializeAnimationRanges();
  20362. return serializationObject;
  20363. };
  20364. Camera.prototype.clone = function (name) {
  20365. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20366. };
  20367. Camera.prototype.getDirection = function (localAxis) {
  20368. var result = BABYLON.Vector3.Zero();
  20369. this.getDirectionToRef(localAxis, result);
  20370. return result;
  20371. };
  20372. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20373. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20374. };
  20375. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20376. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20377. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20378. switch (type) {
  20379. case "ArcRotateCamera":
  20380. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20381. case "DeviceOrientationCamera":
  20382. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20383. case "FollowCamera":
  20384. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20385. case "ArcFollowCamera":
  20386. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20387. case "GamepadCamera":
  20388. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20389. case "TouchCamera":
  20390. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20391. case "VirtualJoysticksCamera":
  20392. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20393. case "WebVRFreeCamera":
  20394. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20395. case "WebVRGamepadCamera":
  20396. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20397. case "VRDeviceOrientationFreeCamera":
  20398. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20399. case "VRDeviceOrientationGamepadCamera":
  20400. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20401. case "AnaglyphArcRotateCamera":
  20402. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20403. case "AnaglyphFreeCamera":
  20404. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20405. case "AnaglyphGamepadCamera":
  20406. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20407. case "AnaglyphUniversalCamera":
  20408. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20409. case "StereoscopicArcRotateCamera":
  20410. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20411. case "StereoscopicFreeCamera":
  20412. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20413. case "StereoscopicGamepadCamera":
  20414. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20415. case "StereoscopicUniversalCamera":
  20416. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20417. case "FreeCamera":// Forcing Universal here
  20418. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20419. default:// Universal Camera is the default value
  20420. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20421. }
  20422. };
  20423. Camera.prototype.computeWorldMatrix = function () {
  20424. return this.getWorldMatrix();
  20425. };
  20426. Camera.Parse = function (parsedCamera, scene) {
  20427. var type = parsedCamera.type;
  20428. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20429. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20430. // Parent
  20431. if (parsedCamera.parentId) {
  20432. camera._waitingParentId = parsedCamera.parentId;
  20433. }
  20434. //If camera has an input manager, let it parse inputs settings
  20435. if (camera.inputs) {
  20436. camera.inputs.parse(parsedCamera);
  20437. camera._setupInputs();
  20438. }
  20439. if (camera.setPosition) {
  20440. camera.position.copyFromFloats(0, 0, 0);
  20441. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20442. }
  20443. // Target
  20444. if (parsedCamera.target) {
  20445. if (camera.setTarget) {
  20446. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20447. }
  20448. }
  20449. // Apply 3d rig, when found
  20450. if (parsedCamera.cameraRigMode) {
  20451. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20452. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20453. }
  20454. // Animations
  20455. if (parsedCamera.animations) {
  20456. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20457. var parsedAnimation = parsedCamera.animations[animationIndex];
  20458. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20459. }
  20460. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20461. }
  20462. if (parsedCamera.autoAnimate) {
  20463. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20464. }
  20465. return camera;
  20466. };
  20467. // Statics
  20468. Camera._PERSPECTIVE_CAMERA = 0;
  20469. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20470. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20471. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20472. Camera._RIG_MODE_NONE = 0;
  20473. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20474. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20475. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20476. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20477. Camera._RIG_MODE_VR = 20;
  20478. Camera._RIG_MODE_WEBVR = 21;
  20479. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20480. Camera.UseAlternateWebVRRendering = false;
  20481. __decorate([
  20482. BABYLON.serializeAsVector3()
  20483. ], Camera.prototype, "position", void 0);
  20484. __decorate([
  20485. BABYLON.serializeAsVector3()
  20486. ], Camera.prototype, "upVector", void 0);
  20487. __decorate([
  20488. BABYLON.serialize()
  20489. ], Camera.prototype, "orthoLeft", void 0);
  20490. __decorate([
  20491. BABYLON.serialize()
  20492. ], Camera.prototype, "orthoRight", void 0);
  20493. __decorate([
  20494. BABYLON.serialize()
  20495. ], Camera.prototype, "orthoBottom", void 0);
  20496. __decorate([
  20497. BABYLON.serialize()
  20498. ], Camera.prototype, "orthoTop", void 0);
  20499. __decorate([
  20500. BABYLON.serialize()
  20501. ], Camera.prototype, "fov", void 0);
  20502. __decorate([
  20503. BABYLON.serialize()
  20504. ], Camera.prototype, "minZ", void 0);
  20505. __decorate([
  20506. BABYLON.serialize()
  20507. ], Camera.prototype, "maxZ", void 0);
  20508. __decorate([
  20509. BABYLON.serialize()
  20510. ], Camera.prototype, "inertia", void 0);
  20511. __decorate([
  20512. BABYLON.serialize()
  20513. ], Camera.prototype, "mode", void 0);
  20514. __decorate([
  20515. BABYLON.serialize()
  20516. ], Camera.prototype, "layerMask", void 0);
  20517. __decorate([
  20518. BABYLON.serialize()
  20519. ], Camera.prototype, "fovMode", void 0);
  20520. __decorate([
  20521. BABYLON.serialize()
  20522. ], Camera.prototype, "cameraRigMode", void 0);
  20523. __decorate([
  20524. BABYLON.serialize()
  20525. ], Camera.prototype, "interaxialDistance", void 0);
  20526. __decorate([
  20527. BABYLON.serialize()
  20528. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20529. return Camera;
  20530. }(BABYLON.Node));
  20531. BABYLON.Camera = Camera;
  20532. })(BABYLON || (BABYLON = {}));
  20533. //# sourceMappingURL=babylon.camera.js.map
  20534. var BABYLON;
  20535. (function (BABYLON) {
  20536. var RenderingManager = /** @class */ (function () {
  20537. function RenderingManager(scene) {
  20538. this._renderingGroups = new Array();
  20539. this._autoClearDepthStencil = {};
  20540. this._customOpaqueSortCompareFn = {};
  20541. this._customAlphaTestSortCompareFn = {};
  20542. this._customTransparentSortCompareFn = {};
  20543. this._renderinGroupInfo = null;
  20544. this._scene = scene;
  20545. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20546. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20547. }
  20548. }
  20549. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20550. if (depth === void 0) { depth = true; }
  20551. if (stencil === void 0) { stencil = true; }
  20552. if (this._depthStencilBufferAlreadyCleaned) {
  20553. return;
  20554. }
  20555. this._scene.getEngine().clear(null, false, depth, stencil);
  20556. this._depthStencilBufferAlreadyCleaned = true;
  20557. };
  20558. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20559. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20560. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20561. var info = null;
  20562. if (observable) {
  20563. if (!this._renderinGroupInfo) {
  20564. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20565. }
  20566. info = this._renderinGroupInfo;
  20567. info.scene = this._scene;
  20568. info.camera = this._scene.activeCamera;
  20569. }
  20570. // Dispatch sprites
  20571. if (renderSprites) {
  20572. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20573. var manager = this._scene.spriteManagers[index];
  20574. this.dispatchSprites(manager);
  20575. }
  20576. }
  20577. // Render
  20578. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20579. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20580. var renderingGroup = this._renderingGroups[index];
  20581. if (!renderingGroup && !observable)
  20582. continue;
  20583. var renderingGroupMask = 0;
  20584. // Fire PRECLEAR stage
  20585. if (observable && info) {
  20586. renderingGroupMask = Math.pow(2, index);
  20587. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20588. info.renderingGroupId = index;
  20589. observable.notifyObservers(info, renderingGroupMask);
  20590. }
  20591. // Clear depth/stencil if needed
  20592. if (RenderingManager.AUTOCLEAR) {
  20593. var autoClear = this._autoClearDepthStencil[index];
  20594. if (autoClear && autoClear.autoClear) {
  20595. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20596. }
  20597. }
  20598. if (observable && info) {
  20599. // Fire PREOPAQUE stage
  20600. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20601. observable.notifyObservers(info, renderingGroupMask);
  20602. // Fire PRETRANSPARENT stage
  20603. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20604. observable.notifyObservers(info, renderingGroupMask);
  20605. }
  20606. if (renderingGroup)
  20607. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20608. // Fire POSTTRANSPARENT stage
  20609. if (observable && info) {
  20610. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20611. observable.notifyObservers(info, renderingGroupMask);
  20612. }
  20613. }
  20614. };
  20615. RenderingManager.prototype.reset = function () {
  20616. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20617. var renderingGroup = this._renderingGroups[index];
  20618. if (renderingGroup) {
  20619. renderingGroup.prepare();
  20620. }
  20621. }
  20622. };
  20623. RenderingManager.prototype.dispose = function () {
  20624. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20625. var renderingGroup = this._renderingGroups[index];
  20626. if (renderingGroup) {
  20627. renderingGroup.dispose();
  20628. }
  20629. }
  20630. this._renderingGroups.length = 0;
  20631. };
  20632. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20633. if (this._renderingGroups[renderingGroupId] === undefined) {
  20634. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20635. }
  20636. };
  20637. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20638. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20639. this._prepareRenderingGroup(renderingGroupId);
  20640. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20641. };
  20642. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20643. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20644. this._prepareRenderingGroup(renderingGroupId);
  20645. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20646. };
  20647. /**
  20648. * @param subMesh The submesh to dispatch
  20649. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20650. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20651. */
  20652. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20653. if (mesh === undefined) {
  20654. mesh = subMesh.getMesh();
  20655. }
  20656. var renderingGroupId = mesh.renderingGroupId || 0;
  20657. this._prepareRenderingGroup(renderingGroupId);
  20658. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20659. };
  20660. /**
  20661. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20662. * This allowed control for front to back rendering or reversly depending of the special needs.
  20663. *
  20664. * @param renderingGroupId The rendering group id corresponding to its index
  20665. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20666. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20667. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20668. */
  20669. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20670. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20671. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20672. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20673. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20674. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20675. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20676. if (this._renderingGroups[renderingGroupId]) {
  20677. var group = this._renderingGroups[renderingGroupId];
  20678. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20679. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20680. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20681. }
  20682. };
  20683. /**
  20684. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20685. *
  20686. * @param renderingGroupId The rendering group id corresponding to its index
  20687. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20688. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20689. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20690. */
  20691. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20692. if (depth === void 0) { depth = true; }
  20693. if (stencil === void 0) { stencil = true; }
  20694. this._autoClearDepthStencil[renderingGroupId] = {
  20695. autoClear: autoClearDepthStencil,
  20696. depth: depth,
  20697. stencil: stencil
  20698. };
  20699. };
  20700. /**
  20701. * The max id used for rendering groups (not included)
  20702. */
  20703. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20704. /**
  20705. * The min id used for rendering groups (included)
  20706. */
  20707. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20708. /**
  20709. * Used to globally prevent autoclearing scenes.
  20710. */
  20711. RenderingManager.AUTOCLEAR = true;
  20712. return RenderingManager;
  20713. }());
  20714. BABYLON.RenderingManager = RenderingManager;
  20715. })(BABYLON || (BABYLON = {}));
  20716. //# sourceMappingURL=babylon.renderingManager.js.map
  20717. var BABYLON;
  20718. (function (BABYLON) {
  20719. var RenderingGroup = /** @class */ (function () {
  20720. /**
  20721. * Creates a new rendering group.
  20722. * @param index The rendering group index
  20723. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20724. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20725. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20726. */
  20727. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20728. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20729. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20730. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20731. this.index = index;
  20732. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20733. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20734. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20735. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20736. this._particleSystems = new BABYLON.SmartArray(256);
  20737. this._spriteManagers = new BABYLON.SmartArray(256);
  20738. this._edgesRenderers = new BABYLON.SmartArray(16);
  20739. this._scene = scene;
  20740. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20741. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20742. this.transparentSortCompareFn = transparentSortCompareFn;
  20743. }
  20744. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20745. /**
  20746. * Set the opaque sort comparison function.
  20747. * If null the sub meshes will be render in the order they were created
  20748. */
  20749. set: function (value) {
  20750. this._opaqueSortCompareFn = value;
  20751. if (value) {
  20752. this._renderOpaque = this.renderOpaqueSorted;
  20753. }
  20754. else {
  20755. this._renderOpaque = RenderingGroup.renderUnsorted;
  20756. }
  20757. },
  20758. enumerable: true,
  20759. configurable: true
  20760. });
  20761. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20762. /**
  20763. * Set the alpha test sort comparison function.
  20764. * If null the sub meshes will be render in the order they were created
  20765. */
  20766. set: function (value) {
  20767. this._alphaTestSortCompareFn = value;
  20768. if (value) {
  20769. this._renderAlphaTest = this.renderAlphaTestSorted;
  20770. }
  20771. else {
  20772. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20773. }
  20774. },
  20775. enumerable: true,
  20776. configurable: true
  20777. });
  20778. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20779. /**
  20780. * Set the transparent sort comparison function.
  20781. * If null the sub meshes will be render in the order they were created
  20782. */
  20783. set: function (value) {
  20784. if (value) {
  20785. this._transparentSortCompareFn = value;
  20786. }
  20787. else {
  20788. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20789. }
  20790. this._renderTransparent = this.renderTransparentSorted;
  20791. },
  20792. enumerable: true,
  20793. configurable: true
  20794. });
  20795. /**
  20796. * Render all the sub meshes contained in the group.
  20797. * @param customRenderFunction Used to override the default render behaviour of the group.
  20798. * @returns true if rendered some submeshes.
  20799. */
  20800. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20801. if (customRenderFunction) {
  20802. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20803. return;
  20804. }
  20805. var engine = this._scene.getEngine();
  20806. // Depth only
  20807. if (this._depthOnlySubMeshes.length !== 0) {
  20808. engine.setColorWrite(false);
  20809. this._renderAlphaTest(this._depthOnlySubMeshes);
  20810. engine.setColorWrite(true);
  20811. }
  20812. // Opaque
  20813. if (this._opaqueSubMeshes.length !== 0) {
  20814. this._renderOpaque(this._opaqueSubMeshes);
  20815. }
  20816. // Alpha test
  20817. if (this._alphaTestSubMeshes.length !== 0) {
  20818. this._renderAlphaTest(this._alphaTestSubMeshes);
  20819. }
  20820. var stencilState = engine.getStencilBuffer();
  20821. engine.setStencilBuffer(false);
  20822. // Sprites
  20823. if (renderSprites) {
  20824. this._renderSprites();
  20825. }
  20826. // Particles
  20827. if (renderParticles) {
  20828. this._renderParticles(activeMeshes);
  20829. }
  20830. if (this.onBeforeTransparentRendering) {
  20831. this.onBeforeTransparentRendering();
  20832. }
  20833. // Transparent
  20834. if (this._transparentSubMeshes.length !== 0) {
  20835. this._renderTransparent(this._transparentSubMeshes);
  20836. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20837. }
  20838. // Set back stencil to false in case it changes before the edge renderer.
  20839. engine.setStencilBuffer(false);
  20840. // Edges
  20841. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20842. this._edgesRenderers.data[edgesRendererIndex].render();
  20843. }
  20844. // Restore Stencil state.
  20845. engine.setStencilBuffer(stencilState);
  20846. };
  20847. /**
  20848. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20849. * @param subMeshes The submeshes to render
  20850. */
  20851. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20852. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20853. };
  20854. /**
  20855. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20856. * @param subMeshes The submeshes to render
  20857. */
  20858. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20859. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20860. };
  20861. /**
  20862. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20863. * @param subMeshes The submeshes to render
  20864. */
  20865. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20866. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20867. };
  20868. /**
  20869. * Renders the submeshes in a specified order.
  20870. * @param subMeshes The submeshes to sort before render
  20871. * @param sortCompareFn The comparison function use to sort
  20872. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20873. * @param transparent Specifies to activate blending if true
  20874. */
  20875. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20876. var subIndex = 0;
  20877. var subMesh;
  20878. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20879. for (; subIndex < subMeshes.length; subIndex++) {
  20880. subMesh = subMeshes.data[subIndex];
  20881. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20882. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20883. }
  20884. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20885. if (sortCompareFn) {
  20886. sortedArray.sort(sortCompareFn);
  20887. }
  20888. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20889. subMesh = sortedArray[subIndex];
  20890. if (transparent) {
  20891. var material = subMesh.getMaterial();
  20892. if (material && material.needDepthPrePass) {
  20893. var engine = material.getScene().getEngine();
  20894. engine.setColorWrite(false);
  20895. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20896. subMesh.render(false);
  20897. engine.setColorWrite(true);
  20898. }
  20899. }
  20900. subMesh.render(transparent);
  20901. }
  20902. };
  20903. /**
  20904. * Renders the submeshes in the order they were dispatched (no sort applied).
  20905. * @param subMeshes The submeshes to render
  20906. */
  20907. RenderingGroup.renderUnsorted = function (subMeshes) {
  20908. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20909. var submesh = subMeshes.data[subIndex];
  20910. submesh.render(false);
  20911. }
  20912. };
  20913. /**
  20914. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20915. * are rendered back to front if in the same alpha index.
  20916. *
  20917. * @param a The first submesh
  20918. * @param b The second submesh
  20919. * @returns The result of the comparison
  20920. */
  20921. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20922. // Alpha index first
  20923. if (a._alphaIndex > b._alphaIndex) {
  20924. return 1;
  20925. }
  20926. if (a._alphaIndex < b._alphaIndex) {
  20927. return -1;
  20928. }
  20929. // Then distance to camera
  20930. return RenderingGroup.backToFrontSortCompare(a, b);
  20931. };
  20932. /**
  20933. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20934. * are rendered back to front.
  20935. *
  20936. * @param a The first submesh
  20937. * @param b The second submesh
  20938. * @returns The result of the comparison
  20939. */
  20940. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20941. // Then distance to camera
  20942. if (a._distanceToCamera < b._distanceToCamera) {
  20943. return 1;
  20944. }
  20945. if (a._distanceToCamera > b._distanceToCamera) {
  20946. return -1;
  20947. }
  20948. return 0;
  20949. };
  20950. /**
  20951. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20952. * are rendered front to back (prevent overdraw).
  20953. *
  20954. * @param a The first submesh
  20955. * @param b The second submesh
  20956. * @returns The result of the comparison
  20957. */
  20958. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20959. // Then distance to camera
  20960. if (a._distanceToCamera < b._distanceToCamera) {
  20961. return -1;
  20962. }
  20963. if (a._distanceToCamera > b._distanceToCamera) {
  20964. return 1;
  20965. }
  20966. return 0;
  20967. };
  20968. /**
  20969. * Resets the different lists of submeshes to prepare a new frame.
  20970. */
  20971. RenderingGroup.prototype.prepare = function () {
  20972. this._opaqueSubMeshes.reset();
  20973. this._transparentSubMeshes.reset();
  20974. this._alphaTestSubMeshes.reset();
  20975. this._depthOnlySubMeshes.reset();
  20976. this._particleSystems.reset();
  20977. this._spriteManagers.reset();
  20978. this._edgesRenderers.reset();
  20979. };
  20980. RenderingGroup.prototype.dispose = function () {
  20981. this._opaqueSubMeshes.dispose();
  20982. this._transparentSubMeshes.dispose();
  20983. this._alphaTestSubMeshes.dispose();
  20984. this._depthOnlySubMeshes.dispose();
  20985. this._particleSystems.dispose();
  20986. this._spriteManagers.dispose();
  20987. this._edgesRenderers.dispose();
  20988. };
  20989. /**
  20990. * Inserts the submesh in its correct queue depending on its material.
  20991. * @param subMesh The submesh to dispatch
  20992. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20993. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20994. */
  20995. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20996. // Get mesh and materials if not provided
  20997. if (mesh === undefined) {
  20998. mesh = subMesh.getMesh();
  20999. }
  21000. if (material === undefined) {
  21001. material = subMesh.getMaterial();
  21002. }
  21003. if (material === null || material === undefined) {
  21004. return;
  21005. }
  21006. if (material.needAlphaBlendingForMesh(mesh)) {
  21007. this._transparentSubMeshes.push(subMesh);
  21008. }
  21009. else if (material.needAlphaTesting()) {
  21010. if (material.needDepthPrePass) {
  21011. this._depthOnlySubMeshes.push(subMesh);
  21012. }
  21013. this._alphaTestSubMeshes.push(subMesh);
  21014. }
  21015. else {
  21016. if (material.needDepthPrePass) {
  21017. this._depthOnlySubMeshes.push(subMesh);
  21018. }
  21019. this._opaqueSubMeshes.push(subMesh); // Opaque
  21020. }
  21021. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21022. this._edgesRenderers.push(mesh._edgesRenderer);
  21023. }
  21024. };
  21025. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21026. this._spriteManagers.push(spriteManager);
  21027. };
  21028. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21029. this._particleSystems.push(particleSystem);
  21030. };
  21031. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21032. if (this._particleSystems.length === 0) {
  21033. return;
  21034. }
  21035. // Particles
  21036. var activeCamera = this._scene.activeCamera;
  21037. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21038. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21039. var particleSystem = this._particleSystems.data[particleIndex];
  21040. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21041. continue;
  21042. }
  21043. var emitter = particleSystem.emitter;
  21044. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21045. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21046. }
  21047. }
  21048. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21049. };
  21050. RenderingGroup.prototype._renderSprites = function () {
  21051. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21052. return;
  21053. }
  21054. // Sprites
  21055. var activeCamera = this._scene.activeCamera;
  21056. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21057. for (var id = 0; id < this._spriteManagers.length; id++) {
  21058. var spriteManager = this._spriteManagers.data[id];
  21059. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21060. spriteManager.render();
  21061. }
  21062. }
  21063. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21064. };
  21065. return RenderingGroup;
  21066. }());
  21067. BABYLON.RenderingGroup = RenderingGroup;
  21068. })(BABYLON || (BABYLON = {}));
  21069. //# sourceMappingURL=babylon.renderingGroup.js.map
  21070. var BABYLON;
  21071. (function (BABYLON) {
  21072. var ClickInfo = /** @class */ (function () {
  21073. function ClickInfo() {
  21074. this._singleClick = false;
  21075. this._doubleClick = false;
  21076. this._hasSwiped = false;
  21077. this._ignore = false;
  21078. }
  21079. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21080. get: function () {
  21081. return this._singleClick;
  21082. },
  21083. set: function (b) {
  21084. this._singleClick = b;
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21090. get: function () {
  21091. return this._doubleClick;
  21092. },
  21093. set: function (b) {
  21094. this._doubleClick = b;
  21095. },
  21096. enumerable: true,
  21097. configurable: true
  21098. });
  21099. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21100. get: function () {
  21101. return this._hasSwiped;
  21102. },
  21103. set: function (b) {
  21104. this._hasSwiped = b;
  21105. },
  21106. enumerable: true,
  21107. configurable: true
  21108. });
  21109. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21110. get: function () {
  21111. return this._ignore;
  21112. },
  21113. set: function (b) {
  21114. this._ignore = b;
  21115. },
  21116. enumerable: true,
  21117. configurable: true
  21118. });
  21119. return ClickInfo;
  21120. }());
  21121. /**
  21122. * This class is used by the onRenderingGroupObservable
  21123. */
  21124. var RenderingGroupInfo = /** @class */ (function () {
  21125. function RenderingGroupInfo() {
  21126. }
  21127. /**
  21128. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21129. * This stage will be fired no matter what
  21130. */
  21131. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21132. /**
  21133. * Called before opaque object are rendered.
  21134. * This stage will be fired only if there's 3D Opaque content to render
  21135. */
  21136. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21137. /**
  21138. * Called after the opaque objects are rendered and before the transparent ones
  21139. * This stage will be fired only if there's 3D transparent content to render
  21140. */
  21141. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21142. /**
  21143. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21144. * This stage will be fired no matter what
  21145. */
  21146. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21147. return RenderingGroupInfo;
  21148. }());
  21149. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21150. /**
  21151. * Represents a scene to be rendered by the engine.
  21152. * @see http://doc.babylonjs.com/page.php?p=21911
  21153. */
  21154. var Scene = /** @class */ (function () {
  21155. /**
  21156. * @constructor
  21157. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21158. */
  21159. function Scene(engine) {
  21160. // Members
  21161. this.autoClear = true;
  21162. this.autoClearDepthAndStencil = true;
  21163. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21164. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21165. this.forceWireframe = false;
  21166. this._forcePointsCloud = false;
  21167. this.forceShowBoundingBoxes = false;
  21168. this.animationsEnabled = true;
  21169. this.useConstantAnimationDeltaTime = false;
  21170. this.constantlyUpdateMeshUnderPointer = false;
  21171. this.hoverCursor = "pointer";
  21172. this.defaultCursor = "";
  21173. /**
  21174. * This is used to call preventDefault() on pointer down
  21175. * in order to block unwanted artifacts like system double clicks
  21176. */
  21177. this.preventDefaultOnPointerDown = true;
  21178. // Metadata
  21179. this.metadata = null;
  21180. /**
  21181. * An event triggered when the scene is disposed.
  21182. * @type {BABYLON.Observable}
  21183. */
  21184. this.onDisposeObservable = new BABYLON.Observable();
  21185. /**
  21186. * An event triggered before rendering the scene (right after animations and physics)
  21187. * @type {BABYLON.Observable}
  21188. */
  21189. this.onBeforeRenderObservable = new BABYLON.Observable();
  21190. /**
  21191. * An event triggered after rendering the scene
  21192. * @type {BABYLON.Observable}
  21193. */
  21194. this.onAfterRenderObservable = new BABYLON.Observable();
  21195. /**
  21196. * An event triggered before animating the scene
  21197. * @type {BABYLON.Observable}
  21198. */
  21199. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21200. /**
  21201. * An event triggered after animations processing
  21202. * @type {BABYLON.Observable}
  21203. */
  21204. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21205. /**
  21206. * An event triggered before draw calls are ready to be sent
  21207. * @type {BABYLON.Observable}
  21208. */
  21209. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21210. /**
  21211. * An event triggered after draw calls have been sent
  21212. * @type {BABYLON.Observable}
  21213. */
  21214. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21215. /**
  21216. * An event triggered when physic simulation is about to be run
  21217. * @type {BABYLON.Observable}
  21218. */
  21219. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21220. /**
  21221. * An event triggered when physic simulation has been done
  21222. * @type {BABYLON.Observable}
  21223. */
  21224. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21225. /**
  21226. * An event triggered when the scene is ready
  21227. * @type {BABYLON.Observable}
  21228. */
  21229. this.onReadyObservable = new BABYLON.Observable();
  21230. /**
  21231. * An event triggered before rendering a camera
  21232. * @type {BABYLON.Observable}
  21233. */
  21234. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21235. /**
  21236. * An event triggered after rendering a camera
  21237. * @type {BABYLON.Observable}
  21238. */
  21239. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21240. /**
  21241. * An event triggered when active meshes evaluation is about to start
  21242. * @type {BABYLON.Observable}
  21243. */
  21244. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21245. /**
  21246. * An event triggered when active meshes evaluation is done
  21247. * @type {BABYLON.Observable}
  21248. */
  21249. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21250. /**
  21251. * An event triggered when particles rendering is about to start
  21252. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21253. * @type {BABYLON.Observable}
  21254. */
  21255. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21256. /**
  21257. * An event triggered when particles rendering is done
  21258. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21259. * @type {BABYLON.Observable}
  21260. */
  21261. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21262. /**
  21263. * An event triggered when sprites rendering is about to start
  21264. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21265. * @type {BABYLON.Observable}
  21266. */
  21267. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21268. /**
  21269. * An event triggered when sprites rendering is done
  21270. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21271. * @type {BABYLON.Observable}
  21272. */
  21273. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21274. /**
  21275. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21276. * @type {BABYLON.Observable}
  21277. */
  21278. this.onDataLoadedObservable = new BABYLON.Observable();
  21279. /**
  21280. * An event triggered when a camera is created
  21281. * @type {BABYLON.Observable}
  21282. */
  21283. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21284. /**
  21285. * An event triggered when a camera is removed
  21286. * @type {BABYLON.Observable}
  21287. */
  21288. this.onCameraRemovedObservable = new BABYLON.Observable();
  21289. /**
  21290. * An event triggered when a light is created
  21291. * @type {BABYLON.Observable}
  21292. */
  21293. this.onNewLightAddedObservable = new BABYLON.Observable();
  21294. /**
  21295. * An event triggered when a light is removed
  21296. * @type {BABYLON.Observable}
  21297. */
  21298. this.onLightRemovedObservable = new BABYLON.Observable();
  21299. /**
  21300. * An event triggered when a geometry is created
  21301. * @type {BABYLON.Observable}
  21302. */
  21303. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21304. /**
  21305. * An event triggered when a geometry is removed
  21306. * @type {BABYLON.Observable}
  21307. */
  21308. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21309. /**
  21310. * An event triggered when a transform node is created
  21311. * @type {BABYLON.Observable}
  21312. */
  21313. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21314. /**
  21315. * An event triggered when a transform node is removed
  21316. * @type {BABYLON.Observable}
  21317. */
  21318. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21319. /**
  21320. * An event triggered when a mesh is created
  21321. * @type {BABYLON.Observable}
  21322. */
  21323. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21324. /**
  21325. * An event triggered when a mesh is removed
  21326. * @type {BABYLON.Observable}
  21327. */
  21328. this.onMeshRemovedObservable = new BABYLON.Observable();
  21329. /**
  21330. * An event triggered when render targets are about to be rendered
  21331. * Can happen multiple times per frame.
  21332. * @type {BABYLON.Observable}
  21333. */
  21334. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21335. /**
  21336. * An event triggered when render targets were rendered.
  21337. * Can happen multiple times per frame.
  21338. * @type {BABYLON.Observable}
  21339. */
  21340. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21341. /**
  21342. * An event triggered before calculating deterministic simulation step
  21343. * @type {BABYLON.Observable}
  21344. */
  21345. this.onBeforeStepObservable = new BABYLON.Observable();
  21346. /**
  21347. * An event triggered after calculating deterministic simulation step
  21348. * @type {BABYLON.Observable}
  21349. */
  21350. this.onAfterStepObservable = new BABYLON.Observable();
  21351. /**
  21352. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21353. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21354. * 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)
  21355. */
  21356. this.onRenderingGroupObservable = new BABYLON.Observable();
  21357. // Animations
  21358. this.animations = [];
  21359. /**
  21360. * 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).
  21361. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21362. */
  21363. this.onPrePointerObservable = new BABYLON.Observable();
  21364. /**
  21365. * Observable event triggered each time an input event is received from the rendering canvas
  21366. */
  21367. this.onPointerObservable = new BABYLON.Observable();
  21368. this._meshPickProceed = false;
  21369. this._currentPickResult = null;
  21370. this._previousPickResult = null;
  21371. this._totalPointersPressed = 0;
  21372. this._doubleClickOccured = false;
  21373. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21374. this.cameraToUseForPointers = null;
  21375. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21376. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21377. this._startingPointerTime = 0;
  21378. this._previousStartingPointerTime = 0;
  21379. // Deterministic lockstep
  21380. this._timeAccumulator = 0;
  21381. this._currentStepId = 0;
  21382. this._currentInternalStep = 0;
  21383. // Keyboard
  21384. /**
  21385. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21386. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21387. */
  21388. this.onPreKeyboardObservable = new BABYLON.Observable();
  21389. /**
  21390. * Observable event triggered each time an keyboard event is received from the hosting window
  21391. */
  21392. this.onKeyboardObservable = new BABYLON.Observable();
  21393. // Coordinate system
  21394. /**
  21395. * use right-handed coordinate system on this scene.
  21396. * @type {boolean}
  21397. */
  21398. this._useRightHandedSystem = false;
  21399. // Fog
  21400. this._fogEnabled = true;
  21401. this._fogMode = Scene.FOGMODE_NONE;
  21402. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21403. this.fogDensity = 0.1;
  21404. this.fogStart = 0;
  21405. this.fogEnd = 1000.0;
  21406. // Lights
  21407. /**
  21408. * is shadow enabled on this scene.
  21409. * @type {boolean}
  21410. */
  21411. this._shadowsEnabled = true;
  21412. /**
  21413. * is light enabled on this scene.
  21414. * @type {boolean}
  21415. */
  21416. this._lightsEnabled = true;
  21417. /**
  21418. * All of the lights added to this scene.
  21419. * @see BABYLON.Light
  21420. * @type {BABYLON.Light[]}
  21421. */
  21422. this.lights = new Array();
  21423. // Cameras
  21424. /** All of the cameras added to this scene. */
  21425. this.cameras = new Array();
  21426. /** All of the active cameras added to this scene. */
  21427. this.activeCameras = new Array();
  21428. // Meshes
  21429. /**
  21430. * All of the tranform nodes added to this scene.
  21431. * @see BABYLON.TransformNode
  21432. * @type {BABYLON.TransformNode[]}
  21433. */
  21434. this.transformNodes = new Array();
  21435. /**
  21436. * All of the (abstract) meshes added to this scene.
  21437. * @see BABYLON.AbstractMesh
  21438. * @type {BABYLON.AbstractMesh[]}
  21439. */
  21440. this.meshes = new Array();
  21441. /**
  21442. * All of the animation groups added to this scene.
  21443. * @see BABYLON.AnimationGroup
  21444. * @type {BABYLON.AnimationGroup[]}
  21445. */
  21446. this.animationGroups = new Array();
  21447. // Geometries
  21448. this._geometries = new Array();
  21449. this.materials = new Array();
  21450. this.multiMaterials = new Array();
  21451. // Textures
  21452. this._texturesEnabled = true;
  21453. this.textures = new Array();
  21454. // Particles
  21455. this.particlesEnabled = true;
  21456. this.particleSystems = new Array();
  21457. // Sprites
  21458. this.spritesEnabled = true;
  21459. this.spriteManagers = new Array();
  21460. /**
  21461. * The list of layers (background and foreground) of the scene.
  21462. */
  21463. this.layers = new Array();
  21464. /**
  21465. * The list of effect layers (highlights/glow) contained in the scene.
  21466. */
  21467. this.effectLayers = new Array();
  21468. // Skeletons
  21469. this._skeletonsEnabled = true;
  21470. this.skeletons = new Array();
  21471. // Morph targets
  21472. this.morphTargetManagers = new Array();
  21473. // Lens flares
  21474. this.lensFlaresEnabled = true;
  21475. this.lensFlareSystems = new Array();
  21476. // Collisions
  21477. this.collisionsEnabled = true;
  21478. /** Defines the gravity applied to this scene */
  21479. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21480. // Postprocesses
  21481. this.postProcesses = new Array();
  21482. this.postProcessesEnabled = true;
  21483. // Customs render targets
  21484. this.renderTargetsEnabled = true;
  21485. this.dumpNextRenderTargets = false;
  21486. this.customRenderTargets = new Array();
  21487. // Imported meshes
  21488. this.importedMeshesFiles = new Array();
  21489. // Probes
  21490. this.probesEnabled = true;
  21491. this.reflectionProbes = new Array();
  21492. this._actionManagers = new Array();
  21493. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21494. // Procedural textures
  21495. this.proceduralTexturesEnabled = true;
  21496. this._proceduralTextures = new Array();
  21497. this.soundTracks = new Array();
  21498. this._audioEnabled = true;
  21499. this._headphone = false;
  21500. // Performance counters
  21501. this._totalVertices = new BABYLON.PerfCounter();
  21502. this._activeIndices = new BABYLON.PerfCounter();
  21503. this._activeParticles = new BABYLON.PerfCounter();
  21504. this._activeBones = new BABYLON.PerfCounter();
  21505. this._animationTime = 0;
  21506. this.animationTimeScale = 1;
  21507. this._renderId = 0;
  21508. this._executeWhenReadyTimeoutId = -1;
  21509. this._intermediateRendering = false;
  21510. this._viewUpdateFlag = -1;
  21511. this._projectionUpdateFlag = -1;
  21512. this._alternateViewUpdateFlag = -1;
  21513. this._alternateProjectionUpdateFlag = -1;
  21514. this._toBeDisposed = new BABYLON.SmartArray(256);
  21515. this._activeRequests = new Array();
  21516. this._pendingData = new Array();
  21517. this._isDisposed = false;
  21518. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21519. this._activeMeshes = new BABYLON.SmartArray(256);
  21520. this._processedMaterials = new BABYLON.SmartArray(256);
  21521. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21522. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21523. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21524. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21525. this._activeAnimatables = new Array();
  21526. this._transformMatrix = BABYLON.Matrix.Zero();
  21527. this._useAlternateCameraConfiguration = false;
  21528. this._alternateRendering = false;
  21529. this.requireLightSorting = false;
  21530. this._depthRenderer = {};
  21531. this._activeMeshesFrozen = false;
  21532. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21533. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21534. this._engine.scenes.push(this);
  21535. this._uid = null;
  21536. this._renderingManager = new BABYLON.RenderingManager(this);
  21537. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21538. if (BABYLON.OutlineRenderer) {
  21539. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21540. }
  21541. if (BABYLON.Tools.IsWindowObjectExist()) {
  21542. this.attachControl();
  21543. }
  21544. //simplification queue
  21545. if (BABYLON.SimplificationQueue) {
  21546. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21547. }
  21548. //collision coordinator initialization. For now legacy per default.
  21549. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21550. // Uniform Buffer
  21551. this._createUbo();
  21552. // Default Image processing definition.
  21553. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21554. }
  21555. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21556. /** The fog is deactivated */
  21557. get: function () {
  21558. return Scene._FOGMODE_NONE;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21564. /** The fog density is following an exponential function */
  21565. get: function () {
  21566. return Scene._FOGMODE_EXP;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21572. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21573. get: function () {
  21574. return Scene._FOGMODE_EXP2;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21580. /** The fog density is following a linear function. */
  21581. get: function () {
  21582. return Scene._FOGMODE_LINEAR;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21588. /**
  21589. * Texture used in all pbr material as the reflection texture.
  21590. * As in the majority of the scene they are the same (exception for multi room and so on),
  21591. * this is easier to reference from here than from all the materials.
  21592. */
  21593. get: function () {
  21594. return this._environmentTexture;
  21595. },
  21596. /**
  21597. * Texture used in all pbr material as the reflection texture.
  21598. * As in the majority of the scene they are the same (exception for multi room and so on),
  21599. * this is easier to set here than in all the materials.
  21600. */
  21601. set: function (value) {
  21602. if (this._environmentTexture === value) {
  21603. return;
  21604. }
  21605. this._environmentTexture = value;
  21606. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21607. },
  21608. enumerable: true,
  21609. configurable: true
  21610. });
  21611. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21612. /**
  21613. * Default image processing configuration used either in the rendering
  21614. * Forward main pass or through the imageProcessingPostProcess if present.
  21615. * As in the majority of the scene they are the same (exception for multi camera),
  21616. * this is easier to reference from here than from all the materials and post process.
  21617. *
  21618. * No setter as we it is a shared configuration, you can set the values instead.
  21619. */
  21620. get: function () {
  21621. return this._imageProcessingConfiguration;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21627. get: function () {
  21628. return this._forcePointsCloud;
  21629. },
  21630. set: function (value) {
  21631. if (this._forcePointsCloud === value) {
  21632. return;
  21633. }
  21634. this._forcePointsCloud = value;
  21635. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(Scene.prototype, "onDispose", {
  21641. /** A function to be executed when this scene is disposed. */
  21642. set: function (callback) {
  21643. if (this._onDisposeObserver) {
  21644. this.onDisposeObservable.remove(this._onDisposeObserver);
  21645. }
  21646. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. Object.defineProperty(Scene.prototype, "beforeRender", {
  21652. /** A function to be executed before rendering this scene */
  21653. set: function (callback) {
  21654. if (this._onBeforeRenderObserver) {
  21655. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21656. }
  21657. if (callback) {
  21658. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21659. }
  21660. },
  21661. enumerable: true,
  21662. configurable: true
  21663. });
  21664. Object.defineProperty(Scene.prototype, "afterRender", {
  21665. /** A function to be executed after rendering this scene */
  21666. set: function (callback) {
  21667. if (this._onAfterRenderObserver) {
  21668. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21669. }
  21670. if (callback) {
  21671. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21672. }
  21673. },
  21674. enumerable: true,
  21675. configurable: true
  21676. });
  21677. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21678. set: function (callback) {
  21679. if (this._onBeforeCameraRenderObserver) {
  21680. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21681. }
  21682. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21688. set: function (callback) {
  21689. if (this._onAfterCameraRenderObserver) {
  21690. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21691. }
  21692. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21693. },
  21694. enumerable: true,
  21695. configurable: true
  21696. });
  21697. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21698. get: function () {
  21699. if (!this._gamepadManager) {
  21700. this._gamepadManager = new BABYLON.GamepadManager(this);
  21701. }
  21702. return this._gamepadManager;
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21708. get: function () {
  21709. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21710. },
  21711. enumerable: true,
  21712. configurable: true
  21713. });
  21714. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21715. get: function () {
  21716. return this._useRightHandedSystem;
  21717. },
  21718. set: function (value) {
  21719. if (this._useRightHandedSystem === value) {
  21720. return;
  21721. }
  21722. this._useRightHandedSystem = value;
  21723. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21724. },
  21725. enumerable: true,
  21726. configurable: true
  21727. });
  21728. Scene.prototype.setStepId = function (newStepId) {
  21729. this._currentStepId = newStepId;
  21730. };
  21731. ;
  21732. Scene.prototype.getStepId = function () {
  21733. return this._currentStepId;
  21734. };
  21735. ;
  21736. Scene.prototype.getInternalStep = function () {
  21737. return this._currentInternalStep;
  21738. };
  21739. ;
  21740. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21741. get: function () {
  21742. return this._fogEnabled;
  21743. },
  21744. /**
  21745. * is fog enabled on this scene.
  21746. */
  21747. set: function (value) {
  21748. if (this._fogEnabled === value) {
  21749. return;
  21750. }
  21751. this._fogEnabled = value;
  21752. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. Object.defineProperty(Scene.prototype, "fogMode", {
  21758. get: function () {
  21759. return this._fogMode;
  21760. },
  21761. set: function (value) {
  21762. if (this._fogMode === value) {
  21763. return;
  21764. }
  21765. this._fogMode = value;
  21766. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21772. get: function () {
  21773. return this._shadowsEnabled;
  21774. },
  21775. set: function (value) {
  21776. if (this._shadowsEnabled === value) {
  21777. return;
  21778. }
  21779. this._shadowsEnabled = value;
  21780. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21781. },
  21782. enumerable: true,
  21783. configurable: true
  21784. });
  21785. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21786. get: function () {
  21787. return this._lightsEnabled;
  21788. },
  21789. set: function (value) {
  21790. if (this._lightsEnabled === value) {
  21791. return;
  21792. }
  21793. this._lightsEnabled = value;
  21794. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21795. },
  21796. enumerable: true,
  21797. configurable: true
  21798. });
  21799. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21800. /** The default material used on meshes when no material is affected */
  21801. get: function () {
  21802. if (!this._defaultMaterial) {
  21803. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21804. }
  21805. return this._defaultMaterial;
  21806. },
  21807. /** The default material used on meshes when no material is affected */
  21808. set: function (value) {
  21809. this._defaultMaterial = value;
  21810. },
  21811. enumerable: true,
  21812. configurable: true
  21813. });
  21814. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21815. get: function () {
  21816. return this._texturesEnabled;
  21817. },
  21818. set: function (value) {
  21819. if (this._texturesEnabled === value) {
  21820. return;
  21821. }
  21822. this._texturesEnabled = value;
  21823. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21824. },
  21825. enumerable: true,
  21826. configurable: true
  21827. });
  21828. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21829. get: function () {
  21830. return this._skeletonsEnabled;
  21831. },
  21832. set: function (value) {
  21833. if (this._skeletonsEnabled === value) {
  21834. return;
  21835. }
  21836. this._skeletonsEnabled = value;
  21837. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21838. },
  21839. enumerable: true,
  21840. configurable: true
  21841. });
  21842. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21843. get: function () {
  21844. if (!this._postProcessRenderPipelineManager) {
  21845. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21846. }
  21847. return this._postProcessRenderPipelineManager;
  21848. },
  21849. enumerable: true,
  21850. configurable: true
  21851. });
  21852. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21853. get: function () {
  21854. if (!this._mainSoundTrack) {
  21855. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21856. }
  21857. return this._mainSoundTrack;
  21858. },
  21859. enumerable: true,
  21860. configurable: true
  21861. });
  21862. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21863. get: function () {
  21864. return this._alternateRendering;
  21865. },
  21866. enumerable: true,
  21867. configurable: true
  21868. });
  21869. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21870. get: function () {
  21871. return this._frustumPlanes;
  21872. },
  21873. enumerable: true,
  21874. configurable: true
  21875. });
  21876. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21877. /**
  21878. * Gets the current geometry buffer associated to the scene.
  21879. */
  21880. get: function () {
  21881. return this._geometryBufferRenderer;
  21882. },
  21883. /**
  21884. * Sets the current geometry buffer for the scene.
  21885. */
  21886. set: function (geometryBufferRenderer) {
  21887. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21888. this._geometryBufferRenderer = geometryBufferRenderer;
  21889. }
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. Object.defineProperty(Scene.prototype, "debugLayer", {
  21895. // Properties
  21896. get: function () {
  21897. if (!this._debugLayer) {
  21898. this._debugLayer = new BABYLON.DebugLayer(this);
  21899. }
  21900. return this._debugLayer;
  21901. },
  21902. enumerable: true,
  21903. configurable: true
  21904. });
  21905. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21906. get: function () {
  21907. return this._workerCollisions;
  21908. },
  21909. set: function (enabled) {
  21910. if (!BABYLON.CollisionCoordinatorLegacy) {
  21911. return;
  21912. }
  21913. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21914. this._workerCollisions = enabled;
  21915. if (this.collisionCoordinator) {
  21916. this.collisionCoordinator.destroy();
  21917. }
  21918. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21919. this.collisionCoordinator.init(this);
  21920. },
  21921. enumerable: true,
  21922. configurable: true
  21923. });
  21924. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21925. get: function () {
  21926. return this._selectionOctree;
  21927. },
  21928. enumerable: true,
  21929. configurable: true
  21930. });
  21931. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21932. /**
  21933. * The mesh that is currently under the pointer.
  21934. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21935. */
  21936. get: function () {
  21937. return this._pointerOverMesh;
  21938. },
  21939. enumerable: true,
  21940. configurable: true
  21941. });
  21942. Object.defineProperty(Scene.prototype, "pointerX", {
  21943. /**
  21944. * Current on-screen X position of the pointer
  21945. * @return {number} X position of the pointer
  21946. */
  21947. get: function () {
  21948. return this._pointerX;
  21949. },
  21950. enumerable: true,
  21951. configurable: true
  21952. });
  21953. Object.defineProperty(Scene.prototype, "pointerY", {
  21954. /**
  21955. * Current on-screen Y position of the pointer
  21956. * @return {number} Y position of the pointer
  21957. */
  21958. get: function () {
  21959. return this._pointerY;
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Scene.prototype.getCachedMaterial = function () {
  21965. return this._cachedMaterial;
  21966. };
  21967. Scene.prototype.getCachedEffect = function () {
  21968. return this._cachedEffect;
  21969. };
  21970. Scene.prototype.getCachedVisibility = function () {
  21971. return this._cachedVisibility;
  21972. };
  21973. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21974. if (visibility === void 0) { visibility = 1; }
  21975. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21976. };
  21977. Scene.prototype.getBoundingBoxRenderer = function () {
  21978. if (!this._boundingBoxRenderer) {
  21979. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21980. }
  21981. return this._boundingBoxRenderer;
  21982. };
  21983. Scene.prototype.getOutlineRenderer = function () {
  21984. return this._outlineRenderer;
  21985. };
  21986. Scene.prototype.getEngine = function () {
  21987. return this._engine;
  21988. };
  21989. Scene.prototype.getTotalVertices = function () {
  21990. return this._totalVertices.current;
  21991. };
  21992. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21993. get: function () {
  21994. return this._totalVertices;
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Scene.prototype.getActiveIndices = function () {
  22000. return this._activeIndices.current;
  22001. };
  22002. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22003. get: function () {
  22004. return this._activeIndices;
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Scene.prototype.getActiveParticles = function () {
  22010. return this._activeParticles.current;
  22011. };
  22012. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22013. get: function () {
  22014. return this._activeParticles;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Scene.prototype.getActiveBones = function () {
  22020. return this._activeBones.current;
  22021. };
  22022. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22023. get: function () {
  22024. return this._activeBones;
  22025. },
  22026. enumerable: true,
  22027. configurable: true
  22028. });
  22029. // Stats
  22030. Scene.prototype.getInterFramePerfCounter = function () {
  22031. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22032. return 0;
  22033. };
  22034. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22035. get: function () {
  22036. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22037. return null;
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Scene.prototype.getLastFrameDuration = function () {
  22043. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22044. return 0;
  22045. };
  22046. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22047. get: function () {
  22048. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22049. return null;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22055. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22056. return 0;
  22057. };
  22058. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22059. get: function () {
  22060. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22061. return null;
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Scene.prototype.getActiveMeshes = function () {
  22067. return this._activeMeshes;
  22068. };
  22069. Scene.prototype.getRenderTargetsDuration = function () {
  22070. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22071. return 0;
  22072. };
  22073. Scene.prototype.getRenderDuration = function () {
  22074. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22075. return 0;
  22076. };
  22077. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22078. get: function () {
  22079. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22080. return null;
  22081. },
  22082. enumerable: true,
  22083. configurable: true
  22084. });
  22085. Scene.prototype.getParticlesDuration = function () {
  22086. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22087. return 0;
  22088. };
  22089. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22090. get: function () {
  22091. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22092. return null;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Scene.prototype.getSpritesDuration = function () {
  22098. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22099. return 0;
  22100. };
  22101. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22102. get: function () {
  22103. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22104. return null;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Scene.prototype.getAnimationRatio = function () {
  22110. return this._animationRatio;
  22111. };
  22112. Scene.prototype.getRenderId = function () {
  22113. return this._renderId;
  22114. };
  22115. Scene.prototype.incrementRenderId = function () {
  22116. this._renderId++;
  22117. };
  22118. Scene.prototype._updatePointerPosition = function (evt) {
  22119. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22120. if (!canvasRect) {
  22121. return;
  22122. }
  22123. this._pointerX = evt.clientX - canvasRect.left;
  22124. this._pointerY = evt.clientY - canvasRect.top;
  22125. this._unTranslatedPointerX = this._pointerX;
  22126. this._unTranslatedPointerY = this._pointerY;
  22127. };
  22128. Scene.prototype._createUbo = function () {
  22129. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22130. this._sceneUbo.addUniform("viewProjection", 16);
  22131. this._sceneUbo.addUniform("view", 16);
  22132. };
  22133. Scene.prototype._createAlternateUbo = function () {
  22134. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22135. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22136. this._alternateSceneUbo.addUniform("view", 16);
  22137. };
  22138. // Pointers handling
  22139. /**
  22140. * Use this method to simulate a pointer move on a mesh
  22141. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22142. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22143. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22144. */
  22145. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22146. var evt = new PointerEvent("pointermove", pointerEventInit);
  22147. return this._processPointerMove(pickResult, evt);
  22148. };
  22149. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22150. var canvas = this._engine.getRenderingCanvas();
  22151. if (!canvas) {
  22152. return this;
  22153. }
  22154. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22155. this.setPointerOverSprite(null);
  22156. this.setPointerOverMesh(pickResult.pickedMesh);
  22157. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22158. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22159. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22160. }
  22161. else {
  22162. canvas.style.cursor = this.hoverCursor;
  22163. }
  22164. }
  22165. else {
  22166. canvas.style.cursor = this.defaultCursor;
  22167. }
  22168. }
  22169. else {
  22170. this.setPointerOverMesh(null);
  22171. // Sprites
  22172. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22173. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22174. this.setPointerOverSprite(pickResult.pickedSprite);
  22175. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22176. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22177. }
  22178. else {
  22179. canvas.style.cursor = this.hoverCursor;
  22180. }
  22181. }
  22182. else {
  22183. this.setPointerOverSprite(null);
  22184. // Restore pointer
  22185. canvas.style.cursor = this.defaultCursor;
  22186. }
  22187. }
  22188. if (pickResult) {
  22189. if (this.onPointerMove) {
  22190. this.onPointerMove(evt, pickResult);
  22191. }
  22192. if (this.onPointerObservable.hasObservers()) {
  22193. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22194. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22195. this.onPointerObservable.notifyObservers(pi, type);
  22196. }
  22197. }
  22198. return this;
  22199. };
  22200. /**
  22201. * Use this method to simulate a pointer down on a mesh
  22202. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22203. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22204. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22205. */
  22206. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22207. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22208. return this._processPointerDown(pickResult, evt);
  22209. };
  22210. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22211. var _this = this;
  22212. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22213. this._pickedDownMesh = pickResult.pickedMesh;
  22214. var actionManager = pickResult.pickedMesh.actionManager;
  22215. if (actionManager) {
  22216. if (actionManager.hasPickTriggers) {
  22217. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22218. switch (evt.button) {
  22219. case 0:
  22220. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22221. break;
  22222. case 1:
  22223. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22224. break;
  22225. case 2:
  22226. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22227. break;
  22228. }
  22229. }
  22230. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22231. window.setTimeout(function () {
  22232. 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);
  22233. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22234. if (_this._totalPointersPressed !== 0 &&
  22235. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22236. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22237. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22238. _this._startingPointerTime = 0;
  22239. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22240. }
  22241. }
  22242. }, Scene.LongPressDelay);
  22243. }
  22244. }
  22245. }
  22246. if (pickResult) {
  22247. if (this.onPointerDown) {
  22248. this.onPointerDown(evt, pickResult);
  22249. }
  22250. if (this.onPointerObservable.hasObservers()) {
  22251. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22252. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22253. this.onPointerObservable.notifyObservers(pi, type);
  22254. }
  22255. }
  22256. return this;
  22257. };
  22258. /**
  22259. * Use this method to simulate a pointer up on a mesh
  22260. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22261. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22262. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22263. */
  22264. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22265. var evt = new PointerEvent("pointerup", pointerEventInit);
  22266. var clickInfo = new ClickInfo();
  22267. clickInfo.singleClick = true;
  22268. clickInfo.ignore = true;
  22269. return this._processPointerUp(pickResult, evt, clickInfo);
  22270. };
  22271. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22272. if (pickResult && pickResult && pickResult.pickedMesh) {
  22273. this._pickedUpMesh = pickResult.pickedMesh;
  22274. if (this._pickedDownMesh === this._pickedUpMesh) {
  22275. if (this.onPointerPick) {
  22276. this.onPointerPick(evt, pickResult);
  22277. }
  22278. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22279. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22280. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22281. this.onPointerObservable.notifyObservers(pi, type);
  22282. }
  22283. }
  22284. if (pickResult.pickedMesh.actionManager) {
  22285. if (clickInfo.ignore) {
  22286. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22287. }
  22288. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22289. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22290. }
  22291. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22292. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22293. }
  22294. }
  22295. }
  22296. if (this._pickedDownMesh &&
  22297. this._pickedDownMesh.actionManager &&
  22298. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22299. this._pickedDownMesh !== this._pickedUpMesh) {
  22300. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22301. }
  22302. if (this.onPointerUp) {
  22303. this.onPointerUp(evt, pickResult);
  22304. }
  22305. if (this.onPointerObservable.hasObservers()) {
  22306. if (!clickInfo.ignore) {
  22307. if (!clickInfo.hasSwiped) {
  22308. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22309. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22310. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22311. this.onPointerObservable.notifyObservers(pi, type);
  22312. }
  22313. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22314. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22315. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22316. this.onPointerObservable.notifyObservers(pi, type);
  22317. }
  22318. }
  22319. }
  22320. else {
  22321. var type = BABYLON.PointerEventTypes.POINTERUP;
  22322. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22323. this.onPointerObservable.notifyObservers(pi, type);
  22324. }
  22325. }
  22326. return this;
  22327. };
  22328. /**
  22329. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22330. * @param attachUp defines if you want to attach events to pointerup
  22331. * @param attachDown defines if you want to attach events to pointerdown
  22332. * @param attachMove defines if you want to attach events to pointermove
  22333. */
  22334. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22335. var _this = this;
  22336. if (attachUp === void 0) { attachUp = true; }
  22337. if (attachDown === void 0) { attachDown = true; }
  22338. if (attachMove === void 0) { attachMove = true; }
  22339. this._initActionManager = function (act, clickInfo) {
  22340. if (!_this._meshPickProceed) {
  22341. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22342. _this._currentPickResult = pickResult;
  22343. if (pickResult) {
  22344. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22345. }
  22346. _this._meshPickProceed = true;
  22347. }
  22348. return act;
  22349. };
  22350. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22351. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22352. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22353. btn !== _this._previousButtonPressed) {
  22354. _this._doubleClickOccured = false;
  22355. clickInfo.singleClick = true;
  22356. clickInfo.ignore = false;
  22357. cb(clickInfo, _this._currentPickResult);
  22358. }
  22359. };
  22360. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22361. var clickInfo = new ClickInfo();
  22362. _this._currentPickResult = null;
  22363. var act = null;
  22364. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22365. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22366. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22367. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22368. act = _this._initActionManager(act, clickInfo);
  22369. if (act)
  22370. checkPicking = act.hasPickTriggers;
  22371. }
  22372. if (checkPicking) {
  22373. var btn = evt.button;
  22374. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22375. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22376. if (!clickInfo.hasSwiped) {
  22377. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22378. if (!checkSingleClickImmediately) {
  22379. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22380. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22381. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22382. act = _this._initActionManager(act, clickInfo);
  22383. if (act)
  22384. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22385. }
  22386. }
  22387. if (checkSingleClickImmediately) {
  22388. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22389. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22390. btn !== _this._previousButtonPressed) {
  22391. clickInfo.singleClick = true;
  22392. cb(clickInfo, _this._currentPickResult);
  22393. }
  22394. }
  22395. else {
  22396. // wait that no double click has been raised during the double click delay
  22397. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22398. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22399. }
  22400. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22401. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22402. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22403. act = _this._initActionManager(act, clickInfo);
  22404. if (act)
  22405. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22406. }
  22407. if (checkDoubleClick) {
  22408. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22409. if (btn === _this._previousButtonPressed &&
  22410. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22411. !_this._doubleClickOccured) {
  22412. // pointer has not moved for 2 clicks, it's a double click
  22413. if (!clickInfo.hasSwiped &&
  22414. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22415. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22416. _this._previousStartingPointerTime = 0;
  22417. _this._doubleClickOccured = true;
  22418. clickInfo.doubleClick = true;
  22419. clickInfo.ignore = false;
  22420. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22421. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22422. }
  22423. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22424. cb(clickInfo, _this._currentPickResult);
  22425. }
  22426. else {
  22427. _this._doubleClickOccured = false;
  22428. _this._previousStartingPointerTime = _this._startingPointerTime;
  22429. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22430. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22431. _this._previousButtonPressed = btn;
  22432. if (Scene.ExclusiveDoubleClickMode) {
  22433. if (_this._previousDelayedSimpleClickTimeout) {
  22434. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22435. }
  22436. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22437. cb(clickInfo, _this._previousPickResult);
  22438. }
  22439. else {
  22440. cb(clickInfo, _this._currentPickResult);
  22441. }
  22442. }
  22443. }
  22444. else {
  22445. _this._doubleClickOccured = false;
  22446. _this._previousStartingPointerTime = _this._startingPointerTime;
  22447. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22448. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22449. _this._previousButtonPressed = btn;
  22450. }
  22451. }
  22452. }
  22453. }
  22454. clickInfo.ignore = true;
  22455. cb(clickInfo, _this._currentPickResult);
  22456. };
  22457. this._spritePredicate = function (sprite) {
  22458. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22459. };
  22460. this._onPointerMove = function (evt) {
  22461. _this._updatePointerPosition(evt);
  22462. // PreObservable support
  22463. if (_this.onPrePointerObservable.hasObservers()) {
  22464. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22465. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22466. _this.onPrePointerObservable.notifyObservers(pi, type);
  22467. if (pi.skipOnPointerObservable) {
  22468. return;
  22469. }
  22470. }
  22471. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22472. return;
  22473. }
  22474. if (!_this.pointerMovePredicate) {
  22475. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22476. }
  22477. // Meshes
  22478. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22479. _this._processPointerMove(pickResult, evt);
  22480. };
  22481. this._onPointerDown = function (evt) {
  22482. _this._totalPointersPressed++;
  22483. _this._pickedDownMesh = null;
  22484. _this._meshPickProceed = false;
  22485. _this._updatePointerPosition(evt);
  22486. if (_this.preventDefaultOnPointerDown && canvas) {
  22487. evt.preventDefault();
  22488. canvas.focus();
  22489. }
  22490. // PreObservable support
  22491. if (_this.onPrePointerObservable.hasObservers()) {
  22492. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22493. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22494. _this.onPrePointerObservable.notifyObservers(pi, type);
  22495. if (pi.skipOnPointerObservable) {
  22496. return;
  22497. }
  22498. }
  22499. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22500. return;
  22501. }
  22502. _this._startingPointerPosition.x = _this._pointerX;
  22503. _this._startingPointerPosition.y = _this._pointerY;
  22504. _this._startingPointerTime = new Date().getTime();
  22505. if (!_this.pointerDownPredicate) {
  22506. _this.pointerDownPredicate = function (mesh) {
  22507. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22508. };
  22509. }
  22510. // Meshes
  22511. _this._pickedDownMesh = null;
  22512. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22513. _this._processPointerDown(pickResult, evt);
  22514. // Sprites
  22515. _this._pickedDownSprite = null;
  22516. if (_this.spriteManagers.length > 0) {
  22517. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22518. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22519. if (pickResult.pickedSprite.actionManager) {
  22520. _this._pickedDownSprite = pickResult.pickedSprite;
  22521. switch (evt.button) {
  22522. case 0:
  22523. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22524. break;
  22525. case 1:
  22526. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22527. break;
  22528. case 2:
  22529. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22530. break;
  22531. }
  22532. if (pickResult.pickedSprite.actionManager) {
  22533. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22534. }
  22535. }
  22536. }
  22537. }
  22538. };
  22539. this._onPointerUp = function (evt) {
  22540. if (_this._totalPointersPressed === 0) {
  22541. return; // So we need to test it the pointer down was pressed before.
  22542. }
  22543. _this._totalPointersPressed--;
  22544. _this._pickedUpMesh = null;
  22545. _this._meshPickProceed = false;
  22546. _this._updatePointerPosition(evt);
  22547. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22548. // PreObservable support
  22549. if (_this.onPrePointerObservable.hasObservers()) {
  22550. if (!clickInfo.ignore) {
  22551. if (!clickInfo.hasSwiped) {
  22552. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22553. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22554. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22555. _this.onPrePointerObservable.notifyObservers(pi, type);
  22556. if (pi.skipOnPointerObservable) {
  22557. return;
  22558. }
  22559. }
  22560. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22561. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22562. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22563. _this.onPrePointerObservable.notifyObservers(pi, type);
  22564. if (pi.skipOnPointerObservable) {
  22565. return;
  22566. }
  22567. }
  22568. }
  22569. }
  22570. else {
  22571. var type = BABYLON.PointerEventTypes.POINTERUP;
  22572. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22573. _this.onPrePointerObservable.notifyObservers(pi, type);
  22574. if (pi.skipOnPointerObservable) {
  22575. return;
  22576. }
  22577. }
  22578. }
  22579. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22580. return;
  22581. }
  22582. if (!_this.pointerUpPredicate) {
  22583. _this.pointerUpPredicate = function (mesh) {
  22584. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22585. };
  22586. }
  22587. // Meshes
  22588. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22589. _this._initActionManager(null, clickInfo);
  22590. }
  22591. if (!pickResult) {
  22592. pickResult = _this._currentPickResult;
  22593. }
  22594. _this._processPointerUp(pickResult, evt, clickInfo);
  22595. // Sprites
  22596. if (_this.spriteManagers.length > 0) {
  22597. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22598. if (spritePickResult) {
  22599. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22600. if (spritePickResult.pickedSprite.actionManager) {
  22601. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22602. if (spritePickResult.pickedSprite.actionManager) {
  22603. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22604. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22605. }
  22606. }
  22607. }
  22608. }
  22609. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22610. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22611. }
  22612. }
  22613. }
  22614. _this._previousPickResult = _this._currentPickResult;
  22615. });
  22616. };
  22617. this._onKeyDown = function (evt) {
  22618. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22619. if (_this.onPreKeyboardObservable.hasObservers()) {
  22620. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22621. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22622. if (pi.skipOnPointerObservable) {
  22623. return;
  22624. }
  22625. }
  22626. if (_this.onKeyboardObservable.hasObservers()) {
  22627. var pi = new BABYLON.KeyboardInfo(type, evt);
  22628. _this.onKeyboardObservable.notifyObservers(pi, type);
  22629. }
  22630. if (_this.actionManager) {
  22631. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22632. }
  22633. };
  22634. this._onKeyUp = function (evt) {
  22635. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22636. if (_this.onPreKeyboardObservable.hasObservers()) {
  22637. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22638. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22639. if (pi.skipOnPointerObservable) {
  22640. return;
  22641. }
  22642. }
  22643. if (_this.onKeyboardObservable.hasObservers()) {
  22644. var pi = new BABYLON.KeyboardInfo(type, evt);
  22645. _this.onKeyboardObservable.notifyObservers(pi, type);
  22646. }
  22647. if (_this.actionManager) {
  22648. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22649. }
  22650. };
  22651. var engine = this.getEngine();
  22652. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22653. if (!canvas) {
  22654. return;
  22655. }
  22656. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22657. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22658. });
  22659. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22660. if (!canvas) {
  22661. return;
  22662. }
  22663. canvas.removeEventListener("keydown", _this._onKeyDown);
  22664. canvas.removeEventListener("keyup", _this._onKeyUp);
  22665. });
  22666. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22667. var canvas = this._engine.getRenderingCanvas();
  22668. if (!canvas) {
  22669. return;
  22670. }
  22671. if (attachMove) {
  22672. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22673. // Wheel
  22674. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22675. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22676. }
  22677. if (attachDown) {
  22678. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22679. }
  22680. if (attachUp) {
  22681. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22682. }
  22683. canvas.tabIndex = 1;
  22684. };
  22685. Scene.prototype.detachControl = function () {
  22686. var engine = this.getEngine();
  22687. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22688. var canvas = engine.getRenderingCanvas();
  22689. if (!canvas) {
  22690. return;
  22691. }
  22692. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22693. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22694. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22695. if (this._onCanvasBlurObserver) {
  22696. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22697. }
  22698. if (this._onCanvasFocusObserver) {
  22699. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22700. }
  22701. // Wheel
  22702. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22703. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22704. // Keyboard
  22705. canvas.removeEventListener("keydown", this._onKeyDown);
  22706. canvas.removeEventListener("keyup", this._onKeyUp);
  22707. // Observables
  22708. this.onKeyboardObservable.clear();
  22709. this.onPreKeyboardObservable.clear();
  22710. this.onPointerObservable.clear();
  22711. this.onPrePointerObservable.clear();
  22712. };
  22713. /**
  22714. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22715. * Delay loaded resources are not taking in account
  22716. * @return true if all required resources are ready
  22717. */
  22718. Scene.prototype.isReady = function () {
  22719. if (this._isDisposed) {
  22720. return false;
  22721. }
  22722. if (this._pendingData.length > 0) {
  22723. return false;
  22724. }
  22725. var index;
  22726. var engine = this.getEngine();
  22727. // Geometries
  22728. for (index = 0; index < this._geometries.length; index++) {
  22729. var geometry = this._geometries[index];
  22730. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22731. return false;
  22732. }
  22733. }
  22734. // Meshes
  22735. for (index = 0; index < this.meshes.length; index++) {
  22736. var mesh = this.meshes[index];
  22737. if (!mesh.isEnabled()) {
  22738. continue;
  22739. }
  22740. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22741. continue;
  22742. }
  22743. if (!mesh.isReady(true)) {
  22744. return false;
  22745. }
  22746. // Effect layers
  22747. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22748. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22749. var layer = _a[_i];
  22750. if (!layer.hasMesh(mesh)) {
  22751. continue;
  22752. }
  22753. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22754. var subMesh = _c[_b];
  22755. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22756. return false;
  22757. }
  22758. }
  22759. }
  22760. }
  22761. return true;
  22762. };
  22763. Scene.prototype.resetCachedMaterial = function () {
  22764. this._cachedMaterial = null;
  22765. this._cachedEffect = null;
  22766. this._cachedVisibility = null;
  22767. };
  22768. Scene.prototype.registerBeforeRender = function (func) {
  22769. this.onBeforeRenderObservable.add(func);
  22770. };
  22771. Scene.prototype.unregisterBeforeRender = function (func) {
  22772. this.onBeforeRenderObservable.removeCallback(func);
  22773. };
  22774. Scene.prototype.registerAfterRender = function (func) {
  22775. this.onAfterRenderObservable.add(func);
  22776. };
  22777. Scene.prototype.unregisterAfterRender = function (func) {
  22778. this.onAfterRenderObservable.removeCallback(func);
  22779. };
  22780. Scene.prototype._executeOnceBeforeRender = function (func) {
  22781. var _this = this;
  22782. var execFunc = function () {
  22783. func();
  22784. setTimeout(function () {
  22785. _this.unregisterBeforeRender(execFunc);
  22786. });
  22787. };
  22788. this.registerBeforeRender(execFunc);
  22789. };
  22790. /**
  22791. * The provided function will run before render once and will be disposed afterwards.
  22792. * A timeout delay can be provided so that the function will be executed in N ms.
  22793. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22794. * @param func The function to be executed.
  22795. * @param timeout optional delay in ms
  22796. */
  22797. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22798. var _this = this;
  22799. if (timeout !== undefined) {
  22800. setTimeout(function () {
  22801. _this._executeOnceBeforeRender(func);
  22802. }, timeout);
  22803. }
  22804. else {
  22805. this._executeOnceBeforeRender(func);
  22806. }
  22807. };
  22808. Scene.prototype._addPendingData = function (data) {
  22809. this._pendingData.push(data);
  22810. };
  22811. Scene.prototype._removePendingData = function (data) {
  22812. var wasLoading = this.isLoading;
  22813. var index = this._pendingData.indexOf(data);
  22814. if (index !== -1) {
  22815. this._pendingData.splice(index, 1);
  22816. }
  22817. if (wasLoading && !this.isLoading) {
  22818. this.onDataLoadedObservable.notifyObservers(this);
  22819. }
  22820. };
  22821. Scene.prototype.getWaitingItemsCount = function () {
  22822. return this._pendingData.length;
  22823. };
  22824. Object.defineProperty(Scene.prototype, "isLoading", {
  22825. get: function () {
  22826. return this._pendingData.length > 0;
  22827. },
  22828. enumerable: true,
  22829. configurable: true
  22830. });
  22831. /**
  22832. * Registers a function to be executed when the scene is ready.
  22833. * @param {Function} func - the function to be executed.
  22834. */
  22835. Scene.prototype.executeWhenReady = function (func) {
  22836. var _this = this;
  22837. this.onReadyObservable.add(func);
  22838. if (this._executeWhenReadyTimeoutId !== -1) {
  22839. return;
  22840. }
  22841. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22842. _this._checkIsReady();
  22843. }, 150);
  22844. };
  22845. /**
  22846. * Returns a promise that resolves when the scene is ready.
  22847. * @returns A promise that resolves when the scene is ready.
  22848. */
  22849. Scene.prototype.whenReadyAsync = function () {
  22850. var _this = this;
  22851. return new Promise(function (resolve) {
  22852. _this.executeWhenReady(function () {
  22853. resolve();
  22854. });
  22855. });
  22856. };
  22857. Scene.prototype._checkIsReady = function () {
  22858. var _this = this;
  22859. if (this.isReady()) {
  22860. this.onReadyObservable.notifyObservers(this);
  22861. this.onReadyObservable.clear();
  22862. this._executeWhenReadyTimeoutId = -1;
  22863. return;
  22864. }
  22865. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22866. _this._checkIsReady();
  22867. }, 150);
  22868. };
  22869. // Animations
  22870. /**
  22871. * Will start the animation sequence of a given target
  22872. * @param target - the target
  22873. * @param {number} from - from which frame should animation start
  22874. * @param {number} to - till which frame should animation run.
  22875. * @param {boolean} [loop] - should the animation loop
  22876. * @param {number} [speedRatio] - the speed in which to run the animation
  22877. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22878. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22879. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22880. * See BABYLON.Animatable
  22881. */
  22882. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22883. if (speedRatio === void 0) { speedRatio = 1.0; }
  22884. if (from > to && speedRatio > 0) {
  22885. speedRatio *= -1;
  22886. }
  22887. this.stopAnimation(target);
  22888. if (!animatable) {
  22889. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22890. }
  22891. // Local animations
  22892. if (target.animations) {
  22893. animatable.appendAnimations(target, target.animations);
  22894. }
  22895. // Children animations
  22896. if (target.getAnimatables) {
  22897. var animatables = target.getAnimatables();
  22898. for (var index = 0; index < animatables.length; index++) {
  22899. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22900. }
  22901. }
  22902. animatable.reset();
  22903. return animatable;
  22904. };
  22905. /**
  22906. * Begin a new animation on a given node
  22907. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22908. * @param {BABYLON.Animation[]} defines the list of animations to start
  22909. * @param {number} from defines the initial value
  22910. * @param {number} to defines the final value
  22911. * @param {boolean} loop defines if you want animation to loop (off by default)
  22912. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22913. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22914. * @returns the list of created animatables
  22915. */
  22916. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22917. if (speedRatio === undefined) {
  22918. speedRatio = 1.0;
  22919. }
  22920. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22921. return animatable;
  22922. };
  22923. /**
  22924. * Begin a new animation on a given node and its hierarchy
  22925. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22926. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  22927. * @param {BABYLON.Animation[]} defines the list of animations to start
  22928. * @param {number} from defines the initial value
  22929. * @param {number} to defines the final value
  22930. * @param {boolean} loop defines if you want animation to loop (off by default)
  22931. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22932. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22933. * @returns the list of animatables created for all nodes
  22934. */
  22935. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22936. var children = target.getDescendants(directDescendantsOnly);
  22937. var result = [];
  22938. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22939. var child = children_1[_i];
  22940. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22941. }
  22942. return result;
  22943. };
  22944. Scene.prototype.getAnimatableByTarget = function (target) {
  22945. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22946. if (this._activeAnimatables[index].target === target) {
  22947. return this._activeAnimatables[index];
  22948. }
  22949. }
  22950. return null;
  22951. };
  22952. Object.defineProperty(Scene.prototype, "animatables", {
  22953. get: function () {
  22954. return this._activeAnimatables;
  22955. },
  22956. enumerable: true,
  22957. configurable: true
  22958. });
  22959. /**
  22960. * Will stop the animation of the given target
  22961. * @param target - the target
  22962. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22963. * @see beginAnimation
  22964. */
  22965. Scene.prototype.stopAnimation = function (target, animationName) {
  22966. var animatable = this.getAnimatableByTarget(target);
  22967. if (animatable) {
  22968. animatable.stop(animationName);
  22969. }
  22970. };
  22971. /**
  22972. * Stops and removes all animations that have been applied to the scene
  22973. */
  22974. Scene.prototype.stopAllAnimations = function () {
  22975. if (this._activeAnimatables) {
  22976. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22977. this._activeAnimatables[i].stop();
  22978. }
  22979. this._activeAnimatables = [];
  22980. }
  22981. };
  22982. Scene.prototype._animate = function () {
  22983. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22984. return;
  22985. }
  22986. // Getting time
  22987. var now = BABYLON.Tools.Now;
  22988. if (!this._animationTimeLast) {
  22989. if (this._pendingData.length > 0) {
  22990. return;
  22991. }
  22992. this._animationTimeLast = now;
  22993. }
  22994. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22995. this._animationTime += deltaTime;
  22996. this._animationTimeLast = now;
  22997. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22998. this._activeAnimatables[index]._animate(this._animationTime);
  22999. }
  23000. };
  23001. // Matrix
  23002. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23003. this._useAlternateCameraConfiguration = active;
  23004. };
  23005. Scene.prototype.getViewMatrix = function () {
  23006. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23007. };
  23008. Scene.prototype.getProjectionMatrix = function () {
  23009. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23010. };
  23011. Scene.prototype.getTransformMatrix = function () {
  23012. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23013. };
  23014. Scene.prototype.setTransformMatrix = function (view, projection) {
  23015. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23016. return;
  23017. }
  23018. this._viewUpdateFlag = view.updateFlag;
  23019. this._projectionUpdateFlag = projection.updateFlag;
  23020. this._viewMatrix = view;
  23021. this._projectionMatrix = projection;
  23022. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23023. // Update frustum
  23024. if (!this._frustumPlanes) {
  23025. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23026. }
  23027. else {
  23028. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23029. }
  23030. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23031. var otherCamera = this.activeCamera._alternateCamera;
  23032. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23033. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23034. }
  23035. if (this._sceneUbo.useUbo) {
  23036. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23037. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23038. this._sceneUbo.update();
  23039. }
  23040. };
  23041. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23042. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23043. return;
  23044. }
  23045. this._alternateViewUpdateFlag = view.updateFlag;
  23046. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23047. this._alternateViewMatrix = view;
  23048. this._alternateProjectionMatrix = projection;
  23049. if (!this._alternateTransformMatrix) {
  23050. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23051. }
  23052. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23053. if (!this._alternateSceneUbo) {
  23054. this._createAlternateUbo();
  23055. }
  23056. if (this._alternateSceneUbo.useUbo) {
  23057. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23058. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23059. this._alternateSceneUbo.update();
  23060. }
  23061. };
  23062. Scene.prototype.getSceneUniformBuffer = function () {
  23063. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23064. };
  23065. // Methods
  23066. Scene.prototype.getUniqueId = function () {
  23067. var result = Scene._uniqueIdCounter;
  23068. Scene._uniqueIdCounter++;
  23069. return result;
  23070. };
  23071. Scene.prototype.addMesh = function (newMesh) {
  23072. this.meshes.push(newMesh);
  23073. //notify the collision coordinator
  23074. if (this.collisionCoordinator) {
  23075. this.collisionCoordinator.onMeshAdded(newMesh);
  23076. }
  23077. newMesh._resyncLightSources();
  23078. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23079. };
  23080. Scene.prototype.removeMesh = function (toRemove) {
  23081. var index = this.meshes.indexOf(toRemove);
  23082. if (index !== -1) {
  23083. // Remove from the scene if mesh found
  23084. this.meshes.splice(index, 1);
  23085. }
  23086. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23087. return index;
  23088. };
  23089. Scene.prototype.addTransformNode = function (newTransformNode) {
  23090. this.transformNodes.push(newTransformNode);
  23091. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23092. };
  23093. Scene.prototype.removeTransformNode = function (toRemove) {
  23094. var index = this.transformNodes.indexOf(toRemove);
  23095. if (index !== -1) {
  23096. // Remove from the scene if found
  23097. this.transformNodes.splice(index, 1);
  23098. }
  23099. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23100. return index;
  23101. };
  23102. Scene.prototype.removeSkeleton = function (toRemove) {
  23103. var index = this.skeletons.indexOf(toRemove);
  23104. if (index !== -1) {
  23105. // Remove from the scene if found
  23106. this.skeletons.splice(index, 1);
  23107. }
  23108. return index;
  23109. };
  23110. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23111. var index = this.morphTargetManagers.indexOf(toRemove);
  23112. if (index !== -1) {
  23113. // Remove from the scene if found
  23114. this.morphTargetManagers.splice(index, 1);
  23115. }
  23116. return index;
  23117. };
  23118. Scene.prototype.removeLight = function (toRemove) {
  23119. var index = this.lights.indexOf(toRemove);
  23120. if (index !== -1) {
  23121. // Remove from meshes
  23122. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23123. var mesh = _a[_i];
  23124. mesh._removeLightSource(toRemove);
  23125. }
  23126. // Remove from the scene if mesh found
  23127. this.lights.splice(index, 1);
  23128. this.sortLightsByPriority();
  23129. }
  23130. this.onLightRemovedObservable.notifyObservers(toRemove);
  23131. return index;
  23132. };
  23133. Scene.prototype.removeCamera = function (toRemove) {
  23134. var index = this.cameras.indexOf(toRemove);
  23135. if (index !== -1) {
  23136. // Remove from the scene if mesh found
  23137. this.cameras.splice(index, 1);
  23138. }
  23139. // Remove from activeCameras
  23140. var index2 = this.activeCameras.indexOf(toRemove);
  23141. if (index2 !== -1) {
  23142. // Remove from the scene if mesh found
  23143. this.activeCameras.splice(index2, 1);
  23144. }
  23145. // Reset the activeCamera
  23146. if (this.activeCamera === toRemove) {
  23147. if (this.cameras.length > 0) {
  23148. this.activeCamera = this.cameras[0];
  23149. }
  23150. else {
  23151. this.activeCamera = null;
  23152. }
  23153. }
  23154. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23155. return index;
  23156. };
  23157. Scene.prototype.removeParticleSystem = function (toRemove) {
  23158. var index = this.particleSystems.indexOf(toRemove);
  23159. if (index !== -1) {
  23160. this.particleSystems.splice(index, 1);
  23161. }
  23162. return index;
  23163. };
  23164. ;
  23165. Scene.prototype.removeAnimation = function (toRemove) {
  23166. var index = this.animations.indexOf(toRemove);
  23167. if (index !== -1) {
  23168. this.animations.splice(index, 1);
  23169. }
  23170. return index;
  23171. };
  23172. ;
  23173. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23174. var index = this.multiMaterials.indexOf(toRemove);
  23175. if (index !== -1) {
  23176. this.multiMaterials.splice(index, 1);
  23177. }
  23178. return index;
  23179. };
  23180. ;
  23181. Scene.prototype.removeMaterial = function (toRemove) {
  23182. var index = this.materials.indexOf(toRemove);
  23183. if (index !== -1) {
  23184. this.materials.splice(index, 1);
  23185. }
  23186. return index;
  23187. };
  23188. ;
  23189. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23190. var index = this.lensFlareSystems.indexOf(toRemove);
  23191. if (index !== -1) {
  23192. this.lensFlareSystems.splice(index, 1);
  23193. }
  23194. return index;
  23195. };
  23196. ;
  23197. Scene.prototype.removeActionManager = function (toRemove) {
  23198. var index = this._actionManagers.indexOf(toRemove);
  23199. if (index !== -1) {
  23200. this._actionManagers.splice(index, 1);
  23201. }
  23202. return index;
  23203. };
  23204. ;
  23205. Scene.prototype.addLight = function (newLight) {
  23206. this.lights.push(newLight);
  23207. this.sortLightsByPriority();
  23208. // Add light to all meshes (To support if the light is removed and then readded)
  23209. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23210. var mesh = _a[_i];
  23211. if (mesh._lightSources.indexOf(newLight) === -1) {
  23212. mesh._lightSources.push(newLight);
  23213. mesh._resyncLightSources();
  23214. }
  23215. }
  23216. this.onNewLightAddedObservable.notifyObservers(newLight);
  23217. };
  23218. Scene.prototype.sortLightsByPriority = function () {
  23219. if (this.requireLightSorting) {
  23220. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23221. }
  23222. };
  23223. Scene.prototype.addCamera = function (newCamera) {
  23224. this.cameras.push(newCamera);
  23225. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23226. };
  23227. Scene.prototype.addSkeleton = function (newSkeleton) {
  23228. this.skeletons.push(newSkeleton);
  23229. };
  23230. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23231. this.particleSystems.push(newParticleSystem);
  23232. };
  23233. Scene.prototype.addAnimation = function (newAnimation) {
  23234. this.animations.push(newAnimation);
  23235. };
  23236. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23237. this.multiMaterials.push(newMultiMaterial);
  23238. };
  23239. Scene.prototype.addMaterial = function (newMaterial) {
  23240. this.materials.push(newMaterial);
  23241. };
  23242. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23243. this.morphTargetManagers.push(newMorphTargetManager);
  23244. };
  23245. Scene.prototype.addGeometry = function (newGeometrie) {
  23246. this._geometries.push(newGeometrie);
  23247. };
  23248. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23249. this.lensFlareSystems.push(newLensFlareSystem);
  23250. };
  23251. Scene.prototype.addActionManager = function (newActionManager) {
  23252. this._actionManagers.push(newActionManager);
  23253. };
  23254. /**
  23255. * Switch active camera
  23256. * @param {Camera} newCamera - new active camera
  23257. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23258. */
  23259. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23260. if (attachControl === void 0) { attachControl = true; }
  23261. var canvas = this._engine.getRenderingCanvas();
  23262. if (!canvas) {
  23263. return;
  23264. }
  23265. if (this.activeCamera) {
  23266. this.activeCamera.detachControl(canvas);
  23267. }
  23268. this.activeCamera = newCamera;
  23269. if (attachControl) {
  23270. newCamera.attachControl(canvas);
  23271. }
  23272. };
  23273. /**
  23274. * sets the active camera of the scene using its ID
  23275. * @param {string} id - the camera's ID
  23276. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23277. * @see activeCamera
  23278. */
  23279. Scene.prototype.setActiveCameraByID = function (id) {
  23280. var camera = this.getCameraByID(id);
  23281. if (camera) {
  23282. this.activeCamera = camera;
  23283. return camera;
  23284. }
  23285. return null;
  23286. };
  23287. /**
  23288. * sets the active camera of the scene using its name
  23289. * @param {string} name - the camera's name
  23290. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23291. * @see activeCamera
  23292. */
  23293. Scene.prototype.setActiveCameraByName = function (name) {
  23294. var camera = this.getCameraByName(name);
  23295. if (camera) {
  23296. this.activeCamera = camera;
  23297. return camera;
  23298. }
  23299. return null;
  23300. };
  23301. /**
  23302. * get an animation group using its name
  23303. * @param {string} the material's name
  23304. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23305. */
  23306. Scene.prototype.getAnimationGroupByName = function (name) {
  23307. for (var index = 0; index < this.animationGroups.length; index++) {
  23308. if (this.animationGroups[index].name === name) {
  23309. return this.animationGroups[index];
  23310. }
  23311. }
  23312. return null;
  23313. };
  23314. /**
  23315. * get a material using its id
  23316. * @param {string} the material's ID
  23317. * @return {BABYLON.Material|null} the material or null if none found.
  23318. */
  23319. Scene.prototype.getMaterialByID = function (id) {
  23320. for (var index = 0; index < this.materials.length; index++) {
  23321. if (this.materials[index].id === id) {
  23322. return this.materials[index];
  23323. }
  23324. }
  23325. return null;
  23326. };
  23327. /**
  23328. * get a material using its name
  23329. * @param {string} the material's name
  23330. * @return {BABYLON.Material|null} the material or null if none found.
  23331. */
  23332. Scene.prototype.getMaterialByName = function (name) {
  23333. for (var index = 0; index < this.materials.length; index++) {
  23334. if (this.materials[index].name === name) {
  23335. return this.materials[index];
  23336. }
  23337. }
  23338. return null;
  23339. };
  23340. Scene.prototype.getLensFlareSystemByName = function (name) {
  23341. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23342. if (this.lensFlareSystems[index].name === name) {
  23343. return this.lensFlareSystems[index];
  23344. }
  23345. }
  23346. return null;
  23347. };
  23348. Scene.prototype.getLensFlareSystemByID = function (id) {
  23349. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23350. if (this.lensFlareSystems[index].id === id) {
  23351. return this.lensFlareSystems[index];
  23352. }
  23353. }
  23354. return null;
  23355. };
  23356. Scene.prototype.getCameraByID = function (id) {
  23357. for (var index = 0; index < this.cameras.length; index++) {
  23358. if (this.cameras[index].id === id) {
  23359. return this.cameras[index];
  23360. }
  23361. }
  23362. return null;
  23363. };
  23364. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23365. for (var index = 0; index < this.cameras.length; index++) {
  23366. if (this.cameras[index].uniqueId === uniqueId) {
  23367. return this.cameras[index];
  23368. }
  23369. }
  23370. return null;
  23371. };
  23372. /**
  23373. * get a camera using its name
  23374. * @param {string} the camera's name
  23375. * @return {BABYLON.Camera|null} the camera or null if none found.
  23376. */
  23377. Scene.prototype.getCameraByName = function (name) {
  23378. for (var index = 0; index < this.cameras.length; index++) {
  23379. if (this.cameras[index].name === name) {
  23380. return this.cameras[index];
  23381. }
  23382. }
  23383. return null;
  23384. };
  23385. /**
  23386. * get a bone using its id
  23387. * @param {string} the bone's id
  23388. * @return {BABYLON.Bone|null} the bone or null if not found
  23389. */
  23390. Scene.prototype.getBoneByID = function (id) {
  23391. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23392. var skeleton = this.skeletons[skeletonIndex];
  23393. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23394. if (skeleton.bones[boneIndex].id === id) {
  23395. return skeleton.bones[boneIndex];
  23396. }
  23397. }
  23398. }
  23399. return null;
  23400. };
  23401. /**
  23402. * get a bone using its id
  23403. * @param {string} the bone's name
  23404. * @return {BABYLON.Bone|null} the bone or null if not found
  23405. */
  23406. Scene.prototype.getBoneByName = function (name) {
  23407. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23408. var skeleton = this.skeletons[skeletonIndex];
  23409. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23410. if (skeleton.bones[boneIndex].name === name) {
  23411. return skeleton.bones[boneIndex];
  23412. }
  23413. }
  23414. }
  23415. return null;
  23416. };
  23417. /**
  23418. * get a light node using its name
  23419. * @param {string} the light's name
  23420. * @return {BABYLON.Light|null} the light or null if none found.
  23421. */
  23422. Scene.prototype.getLightByName = function (name) {
  23423. for (var index = 0; index < this.lights.length; index++) {
  23424. if (this.lights[index].name === name) {
  23425. return this.lights[index];
  23426. }
  23427. }
  23428. return null;
  23429. };
  23430. /**
  23431. * get a light node using its ID
  23432. * @param {string} the light's id
  23433. * @return {BABYLON.Light|null} the light or null if none found.
  23434. */
  23435. Scene.prototype.getLightByID = function (id) {
  23436. for (var index = 0; index < this.lights.length; index++) {
  23437. if (this.lights[index].id === id) {
  23438. return this.lights[index];
  23439. }
  23440. }
  23441. return null;
  23442. };
  23443. /**
  23444. * get a light node using its scene-generated unique ID
  23445. * @param {number} the light's unique id
  23446. * @return {BABYLON.Light|null} the light or null if none found.
  23447. */
  23448. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23449. for (var index = 0; index < this.lights.length; index++) {
  23450. if (this.lights[index].uniqueId === uniqueId) {
  23451. return this.lights[index];
  23452. }
  23453. }
  23454. return null;
  23455. };
  23456. /**
  23457. * get a particle system by id
  23458. * @param id {number} the particle system id
  23459. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23460. */
  23461. Scene.prototype.getParticleSystemByID = function (id) {
  23462. for (var index = 0; index < this.particleSystems.length; index++) {
  23463. if (this.particleSystems[index].id === id) {
  23464. return this.particleSystems[index];
  23465. }
  23466. }
  23467. return null;
  23468. };
  23469. /**
  23470. * get a geometry using its ID
  23471. * @param {string} the geometry's id
  23472. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23473. */
  23474. Scene.prototype.getGeometryByID = function (id) {
  23475. for (var index = 0; index < this._geometries.length; index++) {
  23476. if (this._geometries[index].id === id) {
  23477. return this._geometries[index];
  23478. }
  23479. }
  23480. return null;
  23481. };
  23482. /**
  23483. * add a new geometry to this scene.
  23484. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23485. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23486. * @return {boolean} was the geometry added or not
  23487. */
  23488. Scene.prototype.pushGeometry = function (geometry, force) {
  23489. if (!force && this.getGeometryByID(geometry.id)) {
  23490. return false;
  23491. }
  23492. this._geometries.push(geometry);
  23493. //notify the collision coordinator
  23494. if (this.collisionCoordinator) {
  23495. this.collisionCoordinator.onGeometryAdded(geometry);
  23496. }
  23497. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23498. return true;
  23499. };
  23500. /**
  23501. * Removes an existing geometry
  23502. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23503. * @return {boolean} was the geometry removed or not
  23504. */
  23505. Scene.prototype.removeGeometry = function (geometry) {
  23506. var index = this._geometries.indexOf(geometry);
  23507. if (index > -1) {
  23508. this._geometries.splice(index, 1);
  23509. //notify the collision coordinator
  23510. if (this.collisionCoordinator) {
  23511. this.collisionCoordinator.onGeometryDeleted(geometry);
  23512. }
  23513. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23514. return true;
  23515. }
  23516. return false;
  23517. };
  23518. Scene.prototype.getGeometries = function () {
  23519. return this._geometries;
  23520. };
  23521. /**
  23522. * Get the first added mesh found of a given ID
  23523. * @param {string} id - the id to search for
  23524. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23525. */
  23526. Scene.prototype.getMeshByID = function (id) {
  23527. for (var index = 0; index < this.meshes.length; index++) {
  23528. if (this.meshes[index].id === id) {
  23529. return this.meshes[index];
  23530. }
  23531. }
  23532. return null;
  23533. };
  23534. Scene.prototype.getMeshesByID = function (id) {
  23535. return this.meshes.filter(function (m) {
  23536. return m.id === id;
  23537. });
  23538. };
  23539. /**
  23540. * Get the first added transform node found of a given ID
  23541. * @param {string} id - the id to search for
  23542. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23543. */
  23544. Scene.prototype.getTransformNodeByID = function (id) {
  23545. for (var index = 0; index < this.transformNodes.length; index++) {
  23546. if (this.transformNodes[index].id === id) {
  23547. return this.transformNodes[index];
  23548. }
  23549. }
  23550. return null;
  23551. };
  23552. Scene.prototype.getTransformNodesByID = function (id) {
  23553. return this.transformNodes.filter(function (m) {
  23554. return m.id === id;
  23555. });
  23556. };
  23557. /**
  23558. * Get a mesh with its auto-generated unique id
  23559. * @param {number} uniqueId - the unique id to search for
  23560. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23561. */
  23562. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23563. for (var index = 0; index < this.meshes.length; index++) {
  23564. if (this.meshes[index].uniqueId === uniqueId) {
  23565. return this.meshes[index];
  23566. }
  23567. }
  23568. return null;
  23569. };
  23570. /**
  23571. * Get a the last added mesh found of a given ID
  23572. * @param {string} id - the id to search for
  23573. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23574. */
  23575. Scene.prototype.getLastMeshByID = function (id) {
  23576. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23577. if (this.meshes[index].id === id) {
  23578. return this.meshes[index];
  23579. }
  23580. }
  23581. return null;
  23582. };
  23583. /**
  23584. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23585. * @param {string} id - the id to search for
  23586. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23587. */
  23588. Scene.prototype.getLastEntryByID = function (id) {
  23589. var index;
  23590. for (index = this.meshes.length - 1; index >= 0; index--) {
  23591. if (this.meshes[index].id === id) {
  23592. return this.meshes[index];
  23593. }
  23594. }
  23595. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23596. if (this.transformNodes[index].id === id) {
  23597. return this.transformNodes[index];
  23598. }
  23599. }
  23600. for (index = this.cameras.length - 1; index >= 0; index--) {
  23601. if (this.cameras[index].id === id) {
  23602. return this.cameras[index];
  23603. }
  23604. }
  23605. for (index = this.lights.length - 1; index >= 0; index--) {
  23606. if (this.lights[index].id === id) {
  23607. return this.lights[index];
  23608. }
  23609. }
  23610. return null;
  23611. };
  23612. Scene.prototype.getNodeByID = function (id) {
  23613. var mesh = this.getMeshByID(id);
  23614. if (mesh) {
  23615. return mesh;
  23616. }
  23617. var light = this.getLightByID(id);
  23618. if (light) {
  23619. return light;
  23620. }
  23621. var camera = this.getCameraByID(id);
  23622. if (camera) {
  23623. return camera;
  23624. }
  23625. var bone = this.getBoneByID(id);
  23626. return bone;
  23627. };
  23628. Scene.prototype.getNodeByName = function (name) {
  23629. var mesh = this.getMeshByName(name);
  23630. if (mesh) {
  23631. return mesh;
  23632. }
  23633. var light = this.getLightByName(name);
  23634. if (light) {
  23635. return light;
  23636. }
  23637. var camera = this.getCameraByName(name);
  23638. if (camera) {
  23639. return camera;
  23640. }
  23641. var bone = this.getBoneByName(name);
  23642. return bone;
  23643. };
  23644. Scene.prototype.getMeshByName = function (name) {
  23645. for (var index = 0; index < this.meshes.length; index++) {
  23646. if (this.meshes[index].name === name) {
  23647. return this.meshes[index];
  23648. }
  23649. }
  23650. return null;
  23651. };
  23652. Scene.prototype.getTransformNodeByName = function (name) {
  23653. for (var index = 0; index < this.transformNodes.length; index++) {
  23654. if (this.transformNodes[index].name === name) {
  23655. return this.transformNodes[index];
  23656. }
  23657. }
  23658. return null;
  23659. };
  23660. Scene.prototype.getSoundByName = function (name) {
  23661. var index;
  23662. if (BABYLON.AudioEngine) {
  23663. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23664. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23665. return this.mainSoundTrack.soundCollection[index];
  23666. }
  23667. }
  23668. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23669. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23670. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23671. return this.soundTracks[sdIndex].soundCollection[index];
  23672. }
  23673. }
  23674. }
  23675. }
  23676. return null;
  23677. };
  23678. Scene.prototype.getLastSkeletonByID = function (id) {
  23679. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23680. if (this.skeletons[index].id === id) {
  23681. return this.skeletons[index];
  23682. }
  23683. }
  23684. return null;
  23685. };
  23686. Scene.prototype.getSkeletonById = function (id) {
  23687. for (var index = 0; index < this.skeletons.length; index++) {
  23688. if (this.skeletons[index].id === id) {
  23689. return this.skeletons[index];
  23690. }
  23691. }
  23692. return null;
  23693. };
  23694. Scene.prototype.getSkeletonByName = function (name) {
  23695. for (var index = 0; index < this.skeletons.length; index++) {
  23696. if (this.skeletons[index].name === name) {
  23697. return this.skeletons[index];
  23698. }
  23699. }
  23700. return null;
  23701. };
  23702. Scene.prototype.getMorphTargetManagerById = function (id) {
  23703. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23704. if (this.morphTargetManagers[index].uniqueId === id) {
  23705. return this.morphTargetManagers[index];
  23706. }
  23707. }
  23708. return null;
  23709. };
  23710. Scene.prototype.isActiveMesh = function (mesh) {
  23711. return (this._activeMeshes.indexOf(mesh) !== -1);
  23712. };
  23713. /**
  23714. * Return a the first highlight layer of the scene with a given name.
  23715. * @param name The name of the highlight layer to look for.
  23716. * @return The highlight layer if found otherwise null.
  23717. */
  23718. Scene.prototype.getHighlightLayerByName = function (name) {
  23719. for (var index = 0; index < this.effectLayers.length; index++) {
  23720. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23721. return this.effectLayers[index];
  23722. }
  23723. }
  23724. return null;
  23725. };
  23726. /**
  23727. * Return a the first highlight layer of the scene with a given name.
  23728. * @param name The name of the highlight layer to look for.
  23729. * @return The highlight layer if found otherwise null.
  23730. */
  23731. Scene.prototype.getGlowLayerByName = function (name) {
  23732. for (var index = 0; index < this.effectLayers.length; index++) {
  23733. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23734. return this.effectLayers[index];
  23735. }
  23736. }
  23737. return null;
  23738. };
  23739. Object.defineProperty(Scene.prototype, "uid", {
  23740. /**
  23741. * Return a unique id as a string which can serve as an identifier for the scene
  23742. */
  23743. get: function () {
  23744. if (!this._uid) {
  23745. this._uid = BABYLON.Tools.RandomId();
  23746. }
  23747. return this._uid;
  23748. },
  23749. enumerable: true,
  23750. configurable: true
  23751. });
  23752. /**
  23753. * Add an externaly attached data from its key.
  23754. * This method call will fail and return false, if such key already exists.
  23755. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23756. * @param key the unique key that identifies the data
  23757. * @param data the data object to associate to the key for this Engine instance
  23758. * @return true if no such key were already present and the data was added successfully, false otherwise
  23759. */
  23760. Scene.prototype.addExternalData = function (key, data) {
  23761. if (!this._externalData) {
  23762. this._externalData = new BABYLON.StringDictionary();
  23763. }
  23764. return this._externalData.add(key, data);
  23765. };
  23766. /**
  23767. * Get an externaly attached data from its key
  23768. * @param key the unique key that identifies the data
  23769. * @return the associated data, if present (can be null), or undefined if not present
  23770. */
  23771. Scene.prototype.getExternalData = function (key) {
  23772. if (!this._externalData) {
  23773. return null;
  23774. }
  23775. return this._externalData.get(key);
  23776. };
  23777. /**
  23778. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23779. * @param key the unique key that identifies the data
  23780. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23781. * @return the associated data, can be null if the factory returned null.
  23782. */
  23783. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23784. if (!this._externalData) {
  23785. this._externalData = new BABYLON.StringDictionary();
  23786. }
  23787. return this._externalData.getOrAddWithFactory(key, factory);
  23788. };
  23789. /**
  23790. * Remove an externaly attached data from the Engine instance
  23791. * @param key the unique key that identifies the data
  23792. * @return true if the data was successfully removed, false if it doesn't exist
  23793. */
  23794. Scene.prototype.removeExternalData = function (key) {
  23795. return this._externalData.remove(key);
  23796. };
  23797. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23798. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23799. if (mesh.showSubMeshesBoundingBox) {
  23800. var boundingInfo = subMesh.getBoundingInfo();
  23801. if (boundingInfo !== null && boundingInfo !== undefined) {
  23802. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23803. }
  23804. }
  23805. var material = subMesh.getMaterial();
  23806. if (material !== null && material !== undefined) {
  23807. // Render targets
  23808. if (material.getRenderTargetTextures !== undefined) {
  23809. if (this._processedMaterials.indexOf(material) === -1) {
  23810. this._processedMaterials.push(material);
  23811. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23812. }
  23813. }
  23814. // Dispatch
  23815. this._activeIndices.addCount(subMesh.indexCount, false);
  23816. this._renderingManager.dispatch(subMesh, mesh, material);
  23817. }
  23818. }
  23819. };
  23820. Scene.prototype._isInIntermediateRendering = function () {
  23821. return this._intermediateRendering;
  23822. };
  23823. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23824. this._activeMeshCandidateProvider = provider;
  23825. };
  23826. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23827. return this._activeMeshCandidateProvider;
  23828. };
  23829. /**
  23830. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23831. */
  23832. Scene.prototype.freezeActiveMeshes = function () {
  23833. this._evaluateActiveMeshes();
  23834. this._activeMeshesFrozen = true;
  23835. return this;
  23836. };
  23837. /**
  23838. * Use this function to restart evaluating active meshes on every frame
  23839. */
  23840. Scene.prototype.unfreezeActiveMeshes = function () {
  23841. this._activeMeshesFrozen = false;
  23842. return this;
  23843. };
  23844. Scene.prototype._evaluateActiveMeshes = function () {
  23845. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23846. return;
  23847. }
  23848. if (!this.activeCamera) {
  23849. return;
  23850. }
  23851. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23852. this.activeCamera._activeMeshes.reset();
  23853. this._activeMeshes.reset();
  23854. this._renderingManager.reset();
  23855. this._processedMaterials.reset();
  23856. this._activeParticleSystems.reset();
  23857. this._activeSkeletons.reset();
  23858. this._softwareSkinnedMeshes.reset();
  23859. if (this._boundingBoxRenderer) {
  23860. this._boundingBoxRenderer.reset();
  23861. }
  23862. // Meshes
  23863. var meshes;
  23864. var len;
  23865. var checkIsEnabled = true;
  23866. // Determine mesh candidates
  23867. if (this._activeMeshCandidateProvider !== undefined) {
  23868. // Use _activeMeshCandidateProvider
  23869. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23870. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23871. if (meshes !== undefined) {
  23872. len = meshes.length;
  23873. }
  23874. else {
  23875. len = 0;
  23876. }
  23877. }
  23878. else if (this._selectionOctree !== undefined) {
  23879. // Octree
  23880. var selection = this._selectionOctree.select(this._frustumPlanes);
  23881. meshes = selection.data;
  23882. len = selection.length;
  23883. }
  23884. else {
  23885. // Full scene traversal
  23886. len = this.meshes.length;
  23887. meshes = this.meshes;
  23888. }
  23889. // Check each mesh
  23890. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23891. mesh = meshes[meshIndex];
  23892. if (mesh.isBlocked) {
  23893. continue;
  23894. }
  23895. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23896. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23897. continue;
  23898. }
  23899. mesh.computeWorldMatrix();
  23900. // Intersections
  23901. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23902. this._meshesForIntersections.pushNoDuplicate(mesh);
  23903. }
  23904. // Switch to current LOD
  23905. meshLOD = mesh.getLOD(this.activeCamera);
  23906. if (meshLOD === undefined || meshLOD === null) {
  23907. continue;
  23908. }
  23909. mesh._preActivate();
  23910. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23911. this._activeMeshes.push(mesh);
  23912. this.activeCamera._activeMeshes.push(mesh);
  23913. mesh._activate(this._renderId);
  23914. if (meshLOD !== mesh) {
  23915. meshLOD._activate(this._renderId);
  23916. }
  23917. this._activeMesh(mesh, meshLOD);
  23918. }
  23919. }
  23920. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23921. // Particle systems
  23922. if (this.particlesEnabled) {
  23923. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23924. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23925. var particleSystem = this.particleSystems[particleIndex];
  23926. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23927. continue;
  23928. }
  23929. var emitter = particleSystem.emitter;
  23930. if (!emitter.position || emitter.isEnabled()) {
  23931. this._activeParticleSystems.push(particleSystem);
  23932. particleSystem.animate();
  23933. this._renderingManager.dispatchParticles(particleSystem);
  23934. }
  23935. }
  23936. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23937. }
  23938. };
  23939. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23940. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23941. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23942. mesh.skeleton.prepare();
  23943. }
  23944. if (!mesh.computeBonesUsingShaders) {
  23945. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23946. }
  23947. }
  23948. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23949. var boundingInfo = sourceMesh.getBoundingInfo();
  23950. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23951. }
  23952. if (mesh !== undefined && mesh !== null
  23953. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23954. // Submeshes Octrees
  23955. var len;
  23956. var subMeshes;
  23957. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23958. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23959. len = intersections.length;
  23960. subMeshes = intersections.data;
  23961. }
  23962. else {
  23963. subMeshes = mesh.subMeshes;
  23964. len = subMeshes.length;
  23965. }
  23966. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23967. subMesh = subMeshes[subIndex];
  23968. this._evaluateSubMesh(subMesh, mesh);
  23969. }
  23970. }
  23971. };
  23972. Scene.prototype.updateTransformMatrix = function (force) {
  23973. if (!this.activeCamera) {
  23974. return;
  23975. }
  23976. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23977. };
  23978. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23979. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23980. };
  23981. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23982. if (camera && camera._skipRendering) {
  23983. return;
  23984. }
  23985. var engine = this._engine;
  23986. this.activeCamera = camera;
  23987. if (!this.activeCamera)
  23988. throw new Error("Active camera not set");
  23989. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23990. // Viewport
  23991. engine.setViewport(this.activeCamera.viewport);
  23992. // Camera
  23993. this.resetCachedMaterial();
  23994. this._renderId++;
  23995. this.updateTransformMatrix();
  23996. if (camera._alternateCamera) {
  23997. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23998. this._alternateRendering = true;
  23999. }
  24000. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24001. // Meshes
  24002. this._evaluateActiveMeshes();
  24003. // Software skinning
  24004. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24005. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24006. mesh.applySkeleton(mesh.skeleton);
  24007. }
  24008. // Render targets
  24009. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24010. var needsRestoreFrameBuffer = false;
  24011. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24012. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24013. }
  24014. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24015. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24016. }
  24017. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24018. this._intermediateRendering = true;
  24019. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24020. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24021. var renderTarget = this._renderTargets.data[renderIndex];
  24022. if (renderTarget._shouldRender()) {
  24023. this._renderId++;
  24024. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24025. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24026. }
  24027. }
  24028. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24029. this._intermediateRendering = false;
  24030. this._renderId++;
  24031. needsRestoreFrameBuffer = true; // Restore back buffer
  24032. }
  24033. // Render EffecttLayer Texture
  24034. var stencilState = this._engine.getStencilBuffer();
  24035. var renderEffects = false;
  24036. var needStencil = false;
  24037. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24038. this._intermediateRendering = true;
  24039. for (var i = 0; i < this.effectLayers.length; i++) {
  24040. var effectLayer = this.effectLayers[i];
  24041. if (effectLayer.shouldRender() &&
  24042. (!effectLayer.camera ||
  24043. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24044. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24045. renderEffects = true;
  24046. needStencil = needStencil || effectLayer.needStencil();
  24047. var renderTarget = effectLayer._mainTexture;
  24048. if (renderTarget._shouldRender()) {
  24049. this._renderId++;
  24050. renderTarget.render(false, false);
  24051. needsRestoreFrameBuffer = true;
  24052. }
  24053. }
  24054. }
  24055. this._intermediateRendering = false;
  24056. this._renderId++;
  24057. }
  24058. if (needsRestoreFrameBuffer) {
  24059. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24060. }
  24061. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24062. // Prepare Frame
  24063. this.postProcessManager._prepareFrame();
  24064. // Backgrounds
  24065. var layerIndex;
  24066. var layer;
  24067. if (this.layers.length) {
  24068. engine.setDepthBuffer(false);
  24069. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24070. layer = this.layers[layerIndex];
  24071. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24072. layer.render();
  24073. }
  24074. }
  24075. engine.setDepthBuffer(true);
  24076. }
  24077. // Activate effect Layer stencil
  24078. if (needStencil) {
  24079. this._engine.setStencilBuffer(true);
  24080. }
  24081. // Render
  24082. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24083. this._renderingManager.render(null, null, true, true);
  24084. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24085. // Restore effect Layer stencil
  24086. if (needStencil) {
  24087. this._engine.setStencilBuffer(stencilState);
  24088. }
  24089. // Bounding boxes
  24090. if (this._boundingBoxRenderer) {
  24091. this._boundingBoxRenderer.render();
  24092. }
  24093. // Lens flares
  24094. if (this.lensFlaresEnabled) {
  24095. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24096. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24097. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24098. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24099. lensFlareSystem.render();
  24100. }
  24101. }
  24102. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24103. }
  24104. // Foregrounds
  24105. if (this.layers.length) {
  24106. engine.setDepthBuffer(false);
  24107. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24108. layer = this.layers[layerIndex];
  24109. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24110. layer.render();
  24111. }
  24112. }
  24113. engine.setDepthBuffer(true);
  24114. }
  24115. // Effect Layer
  24116. if (renderEffects) {
  24117. engine.setDepthBuffer(false);
  24118. for (var i = 0; i < this.effectLayers.length; i++) {
  24119. if (this.effectLayers[i].shouldRender()) {
  24120. this.effectLayers[i].render();
  24121. }
  24122. }
  24123. engine.setDepthBuffer(true);
  24124. }
  24125. // Finalize frame
  24126. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24127. // Reset some special arrays
  24128. this._renderTargets.reset();
  24129. this._alternateRendering = false;
  24130. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24131. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24132. };
  24133. Scene.prototype._processSubCameras = function (camera) {
  24134. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24135. this._renderForCamera(camera);
  24136. return;
  24137. }
  24138. // rig cameras
  24139. for (var index = 0; index < camera._rigCameras.length; index++) {
  24140. this._renderForCamera(camera._rigCameras[index], camera);
  24141. }
  24142. this.activeCamera = camera;
  24143. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24144. };
  24145. Scene.prototype._checkIntersections = function () {
  24146. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24147. var sourceMesh = this._meshesForIntersections.data[index];
  24148. if (!sourceMesh.actionManager) {
  24149. continue;
  24150. }
  24151. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24152. var action = sourceMesh.actionManager.actions[actionIndex];
  24153. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24154. var parameters = action.getTriggerParameter();
  24155. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24156. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24157. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24158. if (areIntersecting && currentIntersectionInProgress === -1) {
  24159. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24160. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24161. sourceMesh._intersectionsInProgress.push(otherMesh);
  24162. }
  24163. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24164. sourceMesh._intersectionsInProgress.push(otherMesh);
  24165. }
  24166. }
  24167. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24168. //They intersected, and now they don't.
  24169. //is this trigger an exit trigger? execute an event.
  24170. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24171. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24172. }
  24173. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24174. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24175. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24176. }
  24177. }
  24178. }
  24179. }
  24180. }
  24181. };
  24182. Scene.prototype.render = function () {
  24183. if (this.isDisposed) {
  24184. return;
  24185. }
  24186. this._activeParticles.fetchNewFrame();
  24187. this._totalVertices.fetchNewFrame();
  24188. this._activeIndices.fetchNewFrame();
  24189. this._activeBones.fetchNewFrame();
  24190. this._meshesForIntersections.reset();
  24191. this.resetCachedMaterial();
  24192. this.onBeforeAnimationsObservable.notifyObservers(this);
  24193. // Actions
  24194. if (this.actionManager) {
  24195. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24196. }
  24197. //Simplification Queue
  24198. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24199. this.simplificationQueue.executeNext();
  24200. }
  24201. if (this._engine.isDeterministicLockStep()) {
  24202. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24203. var defaultFPS = (60.0 / 1000.0);
  24204. var defaultFrameTime = 1000 / 60; // frame time in MS
  24205. if (this._physicsEngine) {
  24206. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24207. }
  24208. var stepsTaken = 0;
  24209. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24210. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24211. internalSteps = Math.min(internalSteps, maxSubSteps);
  24212. do {
  24213. this.onBeforeStepObservable.notifyObservers(this);
  24214. // Animations
  24215. this._animationRatio = defaultFrameTime * defaultFPS;
  24216. this._animate();
  24217. this.onAfterAnimationsObservable.notifyObservers(this);
  24218. // Physics
  24219. if (this._physicsEngine) {
  24220. this.onBeforePhysicsObservable.notifyObservers(this);
  24221. this._physicsEngine._step(defaultFrameTime / 1000);
  24222. this.onAfterPhysicsObservable.notifyObservers(this);
  24223. }
  24224. this.onAfterStepObservable.notifyObservers(this);
  24225. this._currentStepId++;
  24226. stepsTaken++;
  24227. deltaTime -= defaultFrameTime;
  24228. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24229. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24230. }
  24231. else {
  24232. // Animations
  24233. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24234. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24235. this._animate();
  24236. this.onAfterAnimationsObservable.notifyObservers(this);
  24237. // Physics
  24238. if (this._physicsEngine) {
  24239. this.onBeforePhysicsObservable.notifyObservers(this);
  24240. this._physicsEngine._step(deltaTime / 1000.0);
  24241. this.onAfterPhysicsObservable.notifyObservers(this);
  24242. }
  24243. }
  24244. // update gamepad manager
  24245. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24246. this._gamepadManager._checkGamepadsStatus();
  24247. }
  24248. // Before render
  24249. this.onBeforeRenderObservable.notifyObservers(this);
  24250. // Update Cameras
  24251. if (this.activeCameras.length > 0) {
  24252. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24253. var camera = this.activeCameras[cameraIndex];
  24254. camera.update();
  24255. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24256. // rig cameras
  24257. for (var index = 0; index < camera._rigCameras.length; index++) {
  24258. camera._rigCameras[index].update();
  24259. }
  24260. }
  24261. }
  24262. }
  24263. else if (this.activeCamera) {
  24264. this.activeCamera.update();
  24265. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24266. // rig cameras
  24267. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24268. this.activeCamera._rigCameras[index].update();
  24269. }
  24270. }
  24271. }
  24272. // Customs render targets
  24273. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24274. var engine = this.getEngine();
  24275. var currentActiveCamera = this.activeCamera;
  24276. if (this.renderTargetsEnabled) {
  24277. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24278. this._intermediateRendering = true;
  24279. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24280. var renderTarget = this.customRenderTargets[customIndex];
  24281. if (renderTarget._shouldRender()) {
  24282. this._renderId++;
  24283. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24284. if (!this.activeCamera)
  24285. throw new Error("Active camera not set");
  24286. // Viewport
  24287. engine.setViewport(this.activeCamera.viewport);
  24288. // Camera
  24289. this.updateTransformMatrix();
  24290. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24291. }
  24292. }
  24293. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24294. this._intermediateRendering = false;
  24295. this._renderId++;
  24296. }
  24297. // Restore back buffer
  24298. if (this.customRenderTargets.length > 0) {
  24299. engine.restoreDefaultFramebuffer();
  24300. }
  24301. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24302. this.activeCamera = currentActiveCamera;
  24303. // Procedural textures
  24304. if (this.proceduralTexturesEnabled) {
  24305. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24306. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24307. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24308. if (proceduralTexture._shouldRender()) {
  24309. proceduralTexture.render();
  24310. }
  24311. }
  24312. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24313. }
  24314. // Clear
  24315. if (this.autoClearDepthAndStencil || this.autoClear) {
  24316. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24317. }
  24318. // Shadows
  24319. if (this.shadowsEnabled) {
  24320. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24321. var light = this.lights[lightIndex];
  24322. var shadowGenerator = light.getShadowGenerator();
  24323. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24324. var shadowMap = (shadowGenerator.getShadowMap());
  24325. if (this.textures.indexOf(shadowMap) !== -1) {
  24326. this._renderTargets.push(shadowMap);
  24327. }
  24328. }
  24329. }
  24330. }
  24331. // Depth renderer
  24332. for (var key in this._depthRenderer) {
  24333. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24334. }
  24335. // Geometry renderer
  24336. if (this._geometryBufferRenderer) {
  24337. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24338. }
  24339. // RenderPipeline
  24340. if (this._postProcessRenderPipelineManager) {
  24341. this._postProcessRenderPipelineManager.update();
  24342. }
  24343. // Multi-cameras?
  24344. if (this.activeCameras.length > 0) {
  24345. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24346. if (cameraIndex > 0) {
  24347. this._engine.clear(null, false, true, true);
  24348. }
  24349. this._processSubCameras(this.activeCameras[cameraIndex]);
  24350. }
  24351. }
  24352. else {
  24353. if (!this.activeCamera) {
  24354. throw new Error("No camera defined");
  24355. }
  24356. this._processSubCameras(this.activeCamera);
  24357. }
  24358. // Intersection checks
  24359. this._checkIntersections();
  24360. // Update the audio listener attached to the camera
  24361. if (BABYLON.AudioEngine) {
  24362. this._updateAudioParameters();
  24363. }
  24364. // After render
  24365. if (this.afterRender) {
  24366. this.afterRender();
  24367. }
  24368. this.onAfterRenderObservable.notifyObservers(this);
  24369. // Cleaning
  24370. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24371. var data = this._toBeDisposed.data[index];
  24372. if (data) {
  24373. data.dispose();
  24374. }
  24375. this._toBeDisposed[index] = null;
  24376. }
  24377. this._toBeDisposed.reset();
  24378. if (this.dumpNextRenderTargets) {
  24379. this.dumpNextRenderTargets = false;
  24380. }
  24381. this._activeBones.addCount(0, true);
  24382. this._activeIndices.addCount(0, true);
  24383. this._activeParticles.addCount(0, true);
  24384. };
  24385. Scene.prototype._updateAudioParameters = function () {
  24386. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24387. return;
  24388. }
  24389. var listeningCamera;
  24390. var audioEngine = BABYLON.Engine.audioEngine;
  24391. if (this.activeCameras.length > 0) {
  24392. listeningCamera = this.activeCameras[0];
  24393. }
  24394. else {
  24395. listeningCamera = this.activeCamera;
  24396. }
  24397. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24398. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24399. // for VR cameras
  24400. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24401. listeningCamera = listeningCamera.rigCameras[0];
  24402. }
  24403. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24404. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24405. cameraDirection.normalize();
  24406. // To avoid some errors on GearVR
  24407. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24408. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24409. }
  24410. var i;
  24411. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24412. var sound = this.mainSoundTrack.soundCollection[i];
  24413. if (sound.useCustomAttenuation) {
  24414. sound.updateDistanceFromListener();
  24415. }
  24416. }
  24417. for (i = 0; i < this.soundTracks.length; i++) {
  24418. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24419. sound = this.soundTracks[i].soundCollection[j];
  24420. if (sound.useCustomAttenuation) {
  24421. sound.updateDistanceFromListener();
  24422. }
  24423. }
  24424. }
  24425. }
  24426. };
  24427. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24428. // Audio
  24429. get: function () {
  24430. return this._audioEnabled;
  24431. },
  24432. set: function (value) {
  24433. this._audioEnabled = value;
  24434. if (BABYLON.AudioEngine) {
  24435. if (this._audioEnabled) {
  24436. this._enableAudio();
  24437. }
  24438. else {
  24439. this._disableAudio();
  24440. }
  24441. }
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Scene.prototype._disableAudio = function () {
  24447. var i;
  24448. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24449. this.mainSoundTrack.soundCollection[i].pause();
  24450. }
  24451. for (i = 0; i < this.soundTracks.length; i++) {
  24452. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24453. this.soundTracks[i].soundCollection[j].pause();
  24454. }
  24455. }
  24456. };
  24457. Scene.prototype._enableAudio = function () {
  24458. var i;
  24459. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24460. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24461. this.mainSoundTrack.soundCollection[i].play();
  24462. }
  24463. }
  24464. for (i = 0; i < this.soundTracks.length; i++) {
  24465. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24466. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24467. this.soundTracks[i].soundCollection[j].play();
  24468. }
  24469. }
  24470. }
  24471. };
  24472. Object.defineProperty(Scene.prototype, "headphone", {
  24473. get: function () {
  24474. return this._headphone;
  24475. },
  24476. set: function (value) {
  24477. this._headphone = value;
  24478. if (BABYLON.AudioEngine) {
  24479. if (this._headphone) {
  24480. this._switchAudioModeForHeadphones();
  24481. }
  24482. else {
  24483. this._switchAudioModeForNormalSpeakers();
  24484. }
  24485. }
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. Scene.prototype._switchAudioModeForHeadphones = function () {
  24491. this.mainSoundTrack.switchPanningModelToHRTF();
  24492. for (var i = 0; i < this.soundTracks.length; i++) {
  24493. this.soundTracks[i].switchPanningModelToHRTF();
  24494. }
  24495. };
  24496. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24497. this.mainSoundTrack.switchPanningModelToEqualPower();
  24498. for (var i = 0; i < this.soundTracks.length; i++) {
  24499. this.soundTracks[i].switchPanningModelToEqualPower();
  24500. }
  24501. };
  24502. /**
  24503. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24504. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24505. * @returns the created depth renderer
  24506. */
  24507. Scene.prototype.enableDepthRenderer = function (camera) {
  24508. camera = camera || this.activeCamera;
  24509. if (!camera) {
  24510. throw "No camera available to enable depth renderer";
  24511. }
  24512. if (!this._depthRenderer[camera.id]) {
  24513. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24514. }
  24515. return this._depthRenderer[camera.id];
  24516. };
  24517. /**
  24518. * Disables a depth renderer for a given camera
  24519. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24520. */
  24521. Scene.prototype.disableDepthRenderer = function (camera) {
  24522. camera = camera || this.activeCamera;
  24523. if (!camera || !this._depthRenderer[camera.id]) {
  24524. return;
  24525. }
  24526. this._depthRenderer[camera.id].dispose();
  24527. delete this._depthRenderer[camera.id];
  24528. };
  24529. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24530. if (ratio === void 0) { ratio = 1; }
  24531. if (this._geometryBufferRenderer) {
  24532. return this._geometryBufferRenderer;
  24533. }
  24534. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24535. if (!this._geometryBufferRenderer.isSupported) {
  24536. this._geometryBufferRenderer = null;
  24537. }
  24538. return this._geometryBufferRenderer;
  24539. };
  24540. Scene.prototype.disableGeometryBufferRenderer = function () {
  24541. if (!this._geometryBufferRenderer) {
  24542. return;
  24543. }
  24544. this._geometryBufferRenderer.dispose();
  24545. this._geometryBufferRenderer = null;
  24546. };
  24547. Scene.prototype.freezeMaterials = function () {
  24548. for (var i = 0; i < this.materials.length; i++) {
  24549. this.materials[i].freeze();
  24550. }
  24551. };
  24552. Scene.prototype.unfreezeMaterials = function () {
  24553. for (var i = 0; i < this.materials.length; i++) {
  24554. this.materials[i].unfreeze();
  24555. }
  24556. };
  24557. Scene.prototype.dispose = function () {
  24558. this.beforeRender = null;
  24559. this.afterRender = null;
  24560. this.skeletons = [];
  24561. this.morphTargetManagers = [];
  24562. this.importedMeshesFiles = new Array();
  24563. this.stopAllAnimations();
  24564. this.resetCachedMaterial();
  24565. for (var key in this._depthRenderer) {
  24566. this._depthRenderer[key].dispose();
  24567. }
  24568. if (this._gamepadManager) {
  24569. this._gamepadManager.dispose();
  24570. this._gamepadManager = null;
  24571. }
  24572. // Smart arrays
  24573. if (this.activeCamera) {
  24574. this.activeCamera._activeMeshes.dispose();
  24575. this.activeCamera = null;
  24576. }
  24577. this._activeMeshes.dispose();
  24578. this._renderingManager.dispose();
  24579. this._processedMaterials.dispose();
  24580. this._activeParticleSystems.dispose();
  24581. this._activeSkeletons.dispose();
  24582. this._softwareSkinnedMeshes.dispose();
  24583. this._renderTargets.dispose();
  24584. if (this._boundingBoxRenderer) {
  24585. this._boundingBoxRenderer.dispose();
  24586. }
  24587. this._meshesForIntersections.dispose();
  24588. this._toBeDisposed.dispose();
  24589. // Abort active requests
  24590. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24591. var request = _a[_i];
  24592. request.abort();
  24593. }
  24594. // Debug layer
  24595. if (this._debugLayer) {
  24596. this._debugLayer.hide();
  24597. }
  24598. // Events
  24599. this.onDisposeObservable.notifyObservers(this);
  24600. this.onDisposeObservable.clear();
  24601. this.onBeforeRenderObservable.clear();
  24602. this.onAfterRenderObservable.clear();
  24603. this.OnBeforeRenderTargetsRenderObservable.clear();
  24604. this.OnAfterRenderTargetsRenderObservable.clear();
  24605. this.onAfterStepObservable.clear();
  24606. this.onBeforeStepObservable.clear();
  24607. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24608. this.onAfterActiveMeshesEvaluationObservable.clear();
  24609. this.onBeforeParticlesRenderingObservable.clear();
  24610. this.onAfterParticlesRenderingObservable.clear();
  24611. this.onBeforeSpritesRenderingObservable.clear();
  24612. this.onAfterSpritesRenderingObservable.clear();
  24613. this.onBeforeDrawPhaseObservable.clear();
  24614. this.onAfterDrawPhaseObservable.clear();
  24615. this.onBeforePhysicsObservable.clear();
  24616. this.onAfterPhysicsObservable.clear();
  24617. this.onBeforeAnimationsObservable.clear();
  24618. this.onAfterAnimationsObservable.clear();
  24619. this.onDataLoadedObservable.clear();
  24620. this.detachControl();
  24621. // Release sounds & sounds tracks
  24622. if (BABYLON.AudioEngine) {
  24623. this.disposeSounds();
  24624. }
  24625. // VR Helper
  24626. if (this.VRHelper) {
  24627. this.VRHelper.dispose();
  24628. }
  24629. // Detach cameras
  24630. var canvas = this._engine.getRenderingCanvas();
  24631. if (canvas) {
  24632. var index;
  24633. for (index = 0; index < this.cameras.length; index++) {
  24634. this.cameras[index].detachControl(canvas);
  24635. }
  24636. }
  24637. // Release animation groups
  24638. while (this.animationGroups.length) {
  24639. this.animationGroups[0].dispose();
  24640. }
  24641. // Release lights
  24642. while (this.lights.length) {
  24643. this.lights[0].dispose();
  24644. }
  24645. // Release meshes
  24646. while (this.meshes.length) {
  24647. this.meshes[0].dispose(true);
  24648. }
  24649. while (this.transformNodes.length) {
  24650. this.removeTransformNode(this.transformNodes[0]);
  24651. }
  24652. // Release cameras
  24653. while (this.cameras.length) {
  24654. this.cameras[0].dispose();
  24655. }
  24656. // Release materials
  24657. if (this.defaultMaterial) {
  24658. this.defaultMaterial.dispose();
  24659. }
  24660. while (this.multiMaterials.length) {
  24661. this.multiMaterials[0].dispose();
  24662. }
  24663. while (this.materials.length) {
  24664. this.materials[0].dispose();
  24665. }
  24666. // Release particles
  24667. while (this.particleSystems.length) {
  24668. this.particleSystems[0].dispose();
  24669. }
  24670. // Release sprites
  24671. while (this.spriteManagers.length) {
  24672. this.spriteManagers[0].dispose();
  24673. }
  24674. // Release postProcesses
  24675. while (this.postProcesses.length) {
  24676. this.postProcesses[0].dispose();
  24677. }
  24678. // Release layers
  24679. while (this.layers.length) {
  24680. this.layers[0].dispose();
  24681. }
  24682. while (this.effectLayers.length) {
  24683. this.effectLayers[0].dispose();
  24684. }
  24685. // Release textures
  24686. while (this.textures.length) {
  24687. this.textures[0].dispose();
  24688. }
  24689. // Release UBO
  24690. this._sceneUbo.dispose();
  24691. if (this._alternateSceneUbo) {
  24692. this._alternateSceneUbo.dispose();
  24693. }
  24694. // Post-processes
  24695. this.postProcessManager.dispose();
  24696. if (this._postProcessRenderPipelineManager) {
  24697. this._postProcessRenderPipelineManager.dispose();
  24698. }
  24699. // Physics
  24700. if (this._physicsEngine) {
  24701. this.disablePhysicsEngine();
  24702. }
  24703. // Remove from engine
  24704. index = this._engine.scenes.indexOf(this);
  24705. if (index > -1) {
  24706. this._engine.scenes.splice(index, 1);
  24707. }
  24708. this._engine.wipeCaches(true);
  24709. this._isDisposed = true;
  24710. };
  24711. Object.defineProperty(Scene.prototype, "isDisposed", {
  24712. get: function () {
  24713. return this._isDisposed;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. // Release sounds & sounds tracks
  24719. Scene.prototype.disposeSounds = function () {
  24720. if (!this._mainSoundTrack) {
  24721. return;
  24722. }
  24723. this.mainSoundTrack.dispose();
  24724. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24725. this.soundTracks[scIndex].dispose();
  24726. }
  24727. };
  24728. // Octrees
  24729. /**
  24730. * Get the world extend vectors with an optional filter
  24731. *
  24732. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24733. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24734. */
  24735. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24736. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24737. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24738. filterPredicate = filterPredicate || (function () { return true; });
  24739. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24740. mesh.computeWorldMatrix(true);
  24741. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24742. return;
  24743. }
  24744. var boundingInfo = mesh.getBoundingInfo();
  24745. var minBox = boundingInfo.boundingBox.minimumWorld;
  24746. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24747. BABYLON.Tools.CheckExtends(minBox, min, max);
  24748. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24749. });
  24750. return {
  24751. min: min,
  24752. max: max
  24753. };
  24754. };
  24755. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24756. if (maxCapacity === void 0) { maxCapacity = 64; }
  24757. if (maxDepth === void 0) { maxDepth = 2; }
  24758. if (!this._selectionOctree) {
  24759. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24760. }
  24761. var worldExtends = this.getWorldExtends();
  24762. // Update octree
  24763. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24764. return this._selectionOctree;
  24765. };
  24766. // Picking
  24767. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24768. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24769. var result = BABYLON.Ray.Zero();
  24770. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24771. return result;
  24772. };
  24773. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24774. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24775. var engine = this._engine;
  24776. if (!camera) {
  24777. if (!this.activeCamera)
  24778. throw new Error("Active camera not set");
  24779. camera = this.activeCamera;
  24780. }
  24781. var cameraViewport = camera.viewport;
  24782. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24783. // Moving coordinates to local viewport world
  24784. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24785. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24786. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24787. return this;
  24788. };
  24789. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24790. var result = BABYLON.Ray.Zero();
  24791. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24792. return result;
  24793. };
  24794. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24795. if (!BABYLON.PickingInfo) {
  24796. return this;
  24797. }
  24798. var engine = this._engine;
  24799. if (!camera) {
  24800. if (!this.activeCamera)
  24801. throw new Error("Active camera not set");
  24802. camera = this.activeCamera;
  24803. }
  24804. var cameraViewport = camera.viewport;
  24805. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24806. var identity = BABYLON.Matrix.Identity();
  24807. // Moving coordinates to local viewport world
  24808. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24809. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24810. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24811. return this;
  24812. };
  24813. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24814. if (!BABYLON.PickingInfo) {
  24815. return null;
  24816. }
  24817. var pickingInfo = null;
  24818. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24819. var mesh = this.meshes[meshIndex];
  24820. if (predicate) {
  24821. if (!predicate(mesh)) {
  24822. continue;
  24823. }
  24824. }
  24825. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24826. continue;
  24827. }
  24828. var world = mesh.getWorldMatrix();
  24829. var ray = rayFunction(world);
  24830. var result = mesh.intersects(ray, fastCheck);
  24831. if (!result || !result.hit)
  24832. continue;
  24833. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24834. continue;
  24835. pickingInfo = result;
  24836. if (fastCheck) {
  24837. break;
  24838. }
  24839. }
  24840. return pickingInfo || new BABYLON.PickingInfo();
  24841. };
  24842. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24843. if (!BABYLON.PickingInfo) {
  24844. return null;
  24845. }
  24846. var pickingInfos = new Array();
  24847. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24848. var mesh = this.meshes[meshIndex];
  24849. if (predicate) {
  24850. if (!predicate(mesh)) {
  24851. continue;
  24852. }
  24853. }
  24854. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24855. continue;
  24856. }
  24857. var world = mesh.getWorldMatrix();
  24858. var ray = rayFunction(world);
  24859. var result = mesh.intersects(ray, false);
  24860. if (!result || !result.hit)
  24861. continue;
  24862. pickingInfos.push(result);
  24863. }
  24864. return pickingInfos;
  24865. };
  24866. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24867. if (!BABYLON.PickingInfo) {
  24868. return null;
  24869. }
  24870. var pickingInfo = null;
  24871. if (!camera) {
  24872. if (!this.activeCamera) {
  24873. return null;
  24874. }
  24875. camera = this.activeCamera;
  24876. }
  24877. if (this.spriteManagers.length > 0) {
  24878. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24879. var spriteManager = this.spriteManagers[spriteIndex];
  24880. if (!spriteManager.isPickable) {
  24881. continue;
  24882. }
  24883. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24884. if (!result || !result.hit)
  24885. continue;
  24886. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24887. continue;
  24888. pickingInfo = result;
  24889. if (fastCheck) {
  24890. break;
  24891. }
  24892. }
  24893. }
  24894. return pickingInfo || new BABYLON.PickingInfo();
  24895. };
  24896. /** Launch a ray to try to pick a mesh in the scene
  24897. * @param x position on screen
  24898. * @param y position on screen
  24899. * @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
  24900. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24901. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24902. */
  24903. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24904. var _this = this;
  24905. if (!BABYLON.PickingInfo) {
  24906. return null;
  24907. }
  24908. return this._internalPick(function (world) {
  24909. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24910. return _this._tempPickingRay;
  24911. }, predicate, fastCheck);
  24912. };
  24913. /** Launch a ray to try to pick a sprite in the scene
  24914. * @param x position on screen
  24915. * @param y position on screen
  24916. * @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
  24917. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24918. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24919. */
  24920. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24921. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24922. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24923. };
  24924. /** Use the given ray to pick a mesh in the scene
  24925. * @param ray The ray to use to pick meshes
  24926. * @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
  24927. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24928. */
  24929. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24930. var _this = this;
  24931. return this._internalPick(function (world) {
  24932. if (!_this._pickWithRayInverseMatrix) {
  24933. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24934. }
  24935. world.invertToRef(_this._pickWithRayInverseMatrix);
  24936. if (!_this._cachedRayForTransform) {
  24937. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24938. }
  24939. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24940. return _this._cachedRayForTransform;
  24941. }, predicate, fastCheck);
  24942. };
  24943. /**
  24944. * Launch a ray to try to pick a mesh in the scene
  24945. * @param x X position on screen
  24946. * @param y Y position on screen
  24947. * @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
  24948. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24949. */
  24950. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24951. var _this = this;
  24952. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24953. };
  24954. /**
  24955. * Launch a ray to try to pick a mesh in the scene
  24956. * @param ray Ray to use
  24957. * @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
  24958. */
  24959. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24960. var _this = this;
  24961. return this._internalMultiPick(function (world) {
  24962. if (!_this._pickWithRayInverseMatrix) {
  24963. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24964. }
  24965. world.invertToRef(_this._pickWithRayInverseMatrix);
  24966. if (!_this._cachedRayForTransform) {
  24967. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24968. }
  24969. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24970. return _this._cachedRayForTransform;
  24971. }, predicate);
  24972. };
  24973. Scene.prototype.setPointerOverMesh = function (mesh) {
  24974. if (this._pointerOverMesh === mesh) {
  24975. return;
  24976. }
  24977. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24978. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24979. }
  24980. this._pointerOverMesh = mesh;
  24981. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24982. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24983. }
  24984. };
  24985. Scene.prototype.getPointerOverMesh = function () {
  24986. return this._pointerOverMesh;
  24987. };
  24988. Scene.prototype.setPointerOverSprite = function (sprite) {
  24989. if (this._pointerOverSprite === sprite) {
  24990. return;
  24991. }
  24992. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24993. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24994. }
  24995. this._pointerOverSprite = sprite;
  24996. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24997. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24998. }
  24999. };
  25000. Scene.prototype.getPointerOverSprite = function () {
  25001. return this._pointerOverSprite;
  25002. };
  25003. // Physics
  25004. Scene.prototype.getPhysicsEngine = function () {
  25005. return this._physicsEngine;
  25006. };
  25007. /**
  25008. * Enables physics to the current scene
  25009. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25010. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25011. * @return {boolean} was the physics engine initialized
  25012. */
  25013. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25014. if (gravity === void 0) { gravity = null; }
  25015. if (this._physicsEngine) {
  25016. return true;
  25017. }
  25018. try {
  25019. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25020. return true;
  25021. }
  25022. catch (e) {
  25023. BABYLON.Tools.Error(e.message);
  25024. return false;
  25025. }
  25026. };
  25027. Scene.prototype.disablePhysicsEngine = function () {
  25028. if (!this._physicsEngine) {
  25029. return;
  25030. }
  25031. this._physicsEngine.dispose();
  25032. this._physicsEngine = null;
  25033. };
  25034. Scene.prototype.isPhysicsEnabled = function () {
  25035. return this._physicsEngine !== undefined;
  25036. };
  25037. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25038. var mesh = compound.parts[0].mesh;
  25039. if (mesh.physicsImpostor) {
  25040. mesh.physicsImpostor.dispose();
  25041. mesh.physicsImpostor = null;
  25042. }
  25043. };
  25044. // Misc.
  25045. Scene.prototype._rebuildGeometries = function () {
  25046. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25047. var geometry = _a[_i];
  25048. geometry._rebuild();
  25049. }
  25050. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25051. var mesh = _c[_b];
  25052. mesh._rebuild();
  25053. }
  25054. if (this.postProcessManager) {
  25055. this.postProcessManager._rebuild();
  25056. }
  25057. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25058. var layer = _e[_d];
  25059. layer._rebuild();
  25060. }
  25061. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25062. var effectLayer = _g[_f];
  25063. effectLayer._rebuild();
  25064. }
  25065. if (this._boundingBoxRenderer) {
  25066. this._boundingBoxRenderer._rebuild();
  25067. }
  25068. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25069. var system = _j[_h];
  25070. system.rebuild();
  25071. }
  25072. if (this._postProcessRenderPipelineManager) {
  25073. this._postProcessRenderPipelineManager._rebuild();
  25074. }
  25075. };
  25076. Scene.prototype._rebuildTextures = function () {
  25077. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25078. var texture = _a[_i];
  25079. texture._rebuild();
  25080. }
  25081. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25082. };
  25083. /**
  25084. * Creates a default light for the scene.
  25085. * @param replace Whether to replace the existing lights in the scene.
  25086. */
  25087. Scene.prototype.createDefaultLight = function (replace) {
  25088. if (replace === void 0) { replace = false; }
  25089. // Dispose existing light in replace mode.
  25090. if (replace) {
  25091. if (this.lights) {
  25092. for (var i = 0; i < this.lights.length; i++) {
  25093. this.lights[i].dispose();
  25094. }
  25095. }
  25096. }
  25097. // Light
  25098. if (this.lights.length === 0) {
  25099. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25100. }
  25101. };
  25102. /**
  25103. * Creates a default camera for the scene.
  25104. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25105. * @param replace Whether to replace the existing active camera in the scene.
  25106. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25107. */
  25108. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25109. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25110. if (replace === void 0) { replace = false; }
  25111. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25112. // Dispose existing camera in replace mode.
  25113. if (replace) {
  25114. if (this.activeCamera) {
  25115. this.activeCamera.dispose();
  25116. this.activeCamera = null;
  25117. }
  25118. }
  25119. // Camera
  25120. if (!this.activeCamera) {
  25121. var worldExtends = this.getWorldExtends();
  25122. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25123. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25124. var camera;
  25125. var radius = worldSize.length() * 1.5;
  25126. // empty scene scenario!
  25127. if (!isFinite(radius)) {
  25128. radius = 1;
  25129. worldCenter.copyFromFloats(0, 0, 0);
  25130. }
  25131. if (createArcRotateCamera) {
  25132. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25133. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25134. arcRotateCamera.wheelPrecision = 100 / radius;
  25135. camera = arcRotateCamera;
  25136. }
  25137. else {
  25138. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25139. freeCamera.setTarget(worldCenter);
  25140. camera = freeCamera;
  25141. }
  25142. camera.minZ = radius * 0.01;
  25143. camera.maxZ = radius * 1000;
  25144. camera.speed = radius * 0.2;
  25145. this.activeCamera = camera;
  25146. var canvas = this.getEngine().getRenderingCanvas();
  25147. if (attachCameraControls && canvas) {
  25148. camera.attachControl(canvas);
  25149. }
  25150. }
  25151. };
  25152. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25153. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25154. if (replace === void 0) { replace = false; }
  25155. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25156. this.createDefaultLight(replace);
  25157. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25158. };
  25159. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25160. if (pbr === void 0) { pbr = false; }
  25161. if (scale === void 0) { scale = 1000; }
  25162. if (blur === void 0) { blur = 0; }
  25163. if (environmentTexture) {
  25164. this.environmentTexture = environmentTexture;
  25165. }
  25166. if (!this.environmentTexture) {
  25167. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25168. return null;
  25169. }
  25170. // Skybox
  25171. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25172. if (pbr) {
  25173. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25174. hdrSkyboxMaterial.backFaceCulling = false;
  25175. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25176. if (hdrSkyboxMaterial.reflectionTexture) {
  25177. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25178. }
  25179. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25180. hdrSkyboxMaterial.disableLighting = true;
  25181. hdrSkyboxMaterial.twoSidedLighting = true;
  25182. hdrSkybox.infiniteDistance = true;
  25183. hdrSkybox.material = hdrSkyboxMaterial;
  25184. }
  25185. else {
  25186. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25187. skyboxMaterial.backFaceCulling = false;
  25188. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25189. if (skyboxMaterial.reflectionTexture) {
  25190. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25191. }
  25192. skyboxMaterial.disableLighting = true;
  25193. hdrSkybox.infiniteDistance = true;
  25194. hdrSkybox.material = skyboxMaterial;
  25195. }
  25196. return hdrSkybox;
  25197. };
  25198. Scene.prototype.createDefaultEnvironment = function (options) {
  25199. if (BABYLON.EnvironmentHelper) {
  25200. return new BABYLON.EnvironmentHelper(options, this);
  25201. }
  25202. return null;
  25203. };
  25204. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25205. if (webVROptions === void 0) { webVROptions = {}; }
  25206. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25207. };
  25208. // Tags
  25209. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25210. if (tagsQuery === undefined) {
  25211. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25212. return list;
  25213. }
  25214. var listByTags = [];
  25215. forEach = forEach || (function (item) { return; });
  25216. for (var i in list) {
  25217. var item = list[i];
  25218. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25219. listByTags.push(item);
  25220. forEach(item);
  25221. }
  25222. }
  25223. return listByTags;
  25224. };
  25225. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25226. return this._getByTags(this.meshes, tagsQuery, forEach);
  25227. };
  25228. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25229. return this._getByTags(this.cameras, tagsQuery, forEach);
  25230. };
  25231. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25232. return this._getByTags(this.lights, tagsQuery, forEach);
  25233. };
  25234. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25235. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25236. };
  25237. /**
  25238. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25239. * This allowed control for front to back rendering or reversly depending of the special needs.
  25240. *
  25241. * @param renderingGroupId The rendering group id corresponding to its index
  25242. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25243. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25244. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25245. */
  25246. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25247. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25248. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25249. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25250. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25251. };
  25252. /**
  25253. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25254. *
  25255. * @param renderingGroupId The rendering group id corresponding to its index
  25256. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25257. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25258. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25259. */
  25260. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25261. if (depth === void 0) { depth = true; }
  25262. if (stencil === void 0) { stencil = true; }
  25263. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25264. };
  25265. /**
  25266. * Will flag all materials as dirty to trigger new shader compilation
  25267. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25268. */
  25269. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25270. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25271. var material = _a[_i];
  25272. if (predicate && !predicate(material)) {
  25273. continue;
  25274. }
  25275. material.markAsDirty(flag);
  25276. }
  25277. };
  25278. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25279. var _this = this;
  25280. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25281. this._activeRequests.push(request);
  25282. request.onCompleteObservable.add(function (request) {
  25283. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25284. });
  25285. return request;
  25286. };
  25287. /** @ignore */
  25288. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25289. var _this = this;
  25290. return new Promise(function (resolve, reject) {
  25291. _this._loadFile(url, function (data) {
  25292. resolve(data);
  25293. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25294. reject(exception);
  25295. });
  25296. });
  25297. };
  25298. // Statics
  25299. Scene._FOGMODE_NONE = 0;
  25300. Scene._FOGMODE_EXP = 1;
  25301. Scene._FOGMODE_EXP2 = 2;
  25302. Scene._FOGMODE_LINEAR = 3;
  25303. Scene._uniqueIdCounter = 0;
  25304. Scene.MinDeltaTime = 1.0;
  25305. Scene.MaxDeltaTime = 1000.0;
  25306. /** The distance in pixel that you have to move to prevent some events */
  25307. Scene.DragMovementThreshold = 10; // in pixels
  25308. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25309. Scene.LongPressDelay = 500; // in milliseconds
  25310. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25311. Scene.DoubleClickDelay = 300; // in milliseconds
  25312. /** If you need to check double click without raising a single click at first click, enable this flag */
  25313. Scene.ExclusiveDoubleClickMode = false;
  25314. return Scene;
  25315. }());
  25316. BABYLON.Scene = Scene;
  25317. })(BABYLON || (BABYLON = {}));
  25318. //# sourceMappingURL=babylon.scene.js.map
  25319. var BABYLON;
  25320. (function (BABYLON) {
  25321. /**
  25322. * Set of assets to keep when moving a scene into an asset container.
  25323. */
  25324. var KeepAssets = /** @class */ (function () {
  25325. function KeepAssets() {
  25326. /**
  25327. * Cameras to keep.
  25328. */
  25329. this.cameras = new Array();
  25330. /**
  25331. * Lights to keep.
  25332. */
  25333. this.lights = new Array();
  25334. /**
  25335. * Meshes to keep.
  25336. */
  25337. this.meshes = new Array();
  25338. /**
  25339. * Skeletons to keep.
  25340. */
  25341. this.skeletons = new Array();
  25342. /**
  25343. * ParticleSystems to keep.
  25344. */
  25345. this.particleSystems = new Array();
  25346. /**
  25347. * Animations to keep.
  25348. */
  25349. this.animations = new Array();
  25350. /**
  25351. * MultiMaterials to keep.
  25352. */
  25353. this.multiMaterials = new Array();
  25354. /**
  25355. * Materials to keep.
  25356. */
  25357. this.materials = new Array();
  25358. /**
  25359. * MorphTargetManagers to keep.
  25360. */
  25361. this.morphTargetManagers = new Array();
  25362. /**
  25363. * Geometries to keep.
  25364. */
  25365. this.geometries = new Array();
  25366. /**
  25367. * TransformNodes to keep.
  25368. */
  25369. this.transformNodes = new Array();
  25370. /**
  25371. * LensFlareSystems to keep.
  25372. */
  25373. this.lensFlareSystems = new Array();
  25374. /**
  25375. * ShadowGenerators to keep.
  25376. */
  25377. this.shadowGenerators = new Array();
  25378. /**
  25379. * ActionManagers to keep.
  25380. */
  25381. this.actionManagers = new Array();
  25382. /**
  25383. * Sounds to keep.
  25384. */
  25385. this.sounds = new Array();
  25386. }
  25387. return KeepAssets;
  25388. }());
  25389. BABYLON.KeepAssets = KeepAssets;
  25390. /**
  25391. * Container with a set of assets that can be added or removed from a scene.
  25392. */
  25393. var AssetContainer = /** @class */ (function () {
  25394. /**
  25395. * Instantiates an AssetContainer.
  25396. * @param scene The scene the AssetContainer belongs to.
  25397. */
  25398. function AssetContainer(scene) {
  25399. // Objects
  25400. /**
  25401. * Cameras populated in the container.
  25402. */
  25403. this.cameras = new Array();
  25404. /**
  25405. * Lights populated in the container.
  25406. */
  25407. this.lights = new Array();
  25408. /**
  25409. * Meshes populated in the container.
  25410. */
  25411. this.meshes = new Array();
  25412. /**
  25413. * Skeletons populated in the container.
  25414. */
  25415. this.skeletons = new Array();
  25416. /**
  25417. * ParticleSystems populated in the container.
  25418. */
  25419. this.particleSystems = new Array();
  25420. /**
  25421. * Animations populated in the container.
  25422. */
  25423. this.animations = new Array();
  25424. /**
  25425. * MultiMaterials populated in the container.
  25426. */
  25427. this.multiMaterials = new Array();
  25428. /**
  25429. * Materials populated in the container.
  25430. */
  25431. this.materials = new Array();
  25432. /**
  25433. * MorphTargetManagers populated in the container.
  25434. */
  25435. this.morphTargetManagers = new Array();
  25436. /**
  25437. * Geometries populated in the container.
  25438. */
  25439. this.geometries = new Array();
  25440. /**
  25441. * TransformNodes populated in the container.
  25442. */
  25443. this.transformNodes = new Array();
  25444. /**
  25445. * LensFlareSystems populated in the container.
  25446. */
  25447. this.lensFlareSystems = new Array();
  25448. /**
  25449. * ShadowGenerators populated in the container.
  25450. */
  25451. this.shadowGenerators = new Array();
  25452. /**
  25453. * ActionManagers populated in the container.
  25454. */
  25455. this.actionManagers = new Array();
  25456. /**
  25457. * Sounds populated in the container.
  25458. */
  25459. this.sounds = new Array();
  25460. this.scene = scene;
  25461. }
  25462. /**
  25463. * Adds all the assets from the container to the scene.
  25464. */
  25465. AssetContainer.prototype.addAllToScene = function () {
  25466. var _this = this;
  25467. this.cameras.forEach(function (o) {
  25468. _this.scene.addCamera(o);
  25469. });
  25470. this.lights.forEach(function (o) {
  25471. _this.scene.addLight(o);
  25472. });
  25473. this.meshes.forEach(function (o) {
  25474. _this.scene.addMesh(o);
  25475. });
  25476. this.skeletons.forEach(function (o) {
  25477. _this.scene.addSkeleton(o);
  25478. });
  25479. this.particleSystems.forEach(function (o) {
  25480. _this.scene.addParticleSystem(o);
  25481. });
  25482. this.animations.forEach(function (o) {
  25483. _this.scene.addAnimation(o);
  25484. });
  25485. this.multiMaterials.forEach(function (o) {
  25486. _this.scene.addMultiMaterial(o);
  25487. });
  25488. this.materials.forEach(function (o) {
  25489. _this.scene.addMaterial(o);
  25490. });
  25491. this.morphTargetManagers.forEach(function (o) {
  25492. _this.scene.addMorphTargetManager(o);
  25493. });
  25494. this.geometries.forEach(function (o) {
  25495. _this.scene.addGeometry(o);
  25496. });
  25497. this.transformNodes.forEach(function (o) {
  25498. _this.scene.addTransformNode(o);
  25499. });
  25500. this.lensFlareSystems.forEach(function (o) {
  25501. _this.scene.addLensFlareSystem(o);
  25502. });
  25503. this.actionManagers.forEach(function (o) {
  25504. _this.scene.addActionManager(o);
  25505. });
  25506. this.sounds.forEach(function (o) {
  25507. o.play();
  25508. o.autoplay = true;
  25509. _this.scene.mainSoundTrack.AddSound(o);
  25510. });
  25511. };
  25512. /**
  25513. * Removes all the assets in the container from the scene
  25514. */
  25515. AssetContainer.prototype.removeAllFromScene = function () {
  25516. var _this = this;
  25517. this.cameras.forEach(function (o) {
  25518. _this.scene.removeCamera(o);
  25519. });
  25520. this.lights.forEach(function (o) {
  25521. _this.scene.removeLight(o);
  25522. });
  25523. this.meshes.forEach(function (o) {
  25524. _this.scene.removeMesh(o);
  25525. });
  25526. this.skeletons.forEach(function (o) {
  25527. _this.scene.removeSkeleton(o);
  25528. });
  25529. this.particleSystems.forEach(function (o) {
  25530. _this.scene.removeParticleSystem(o);
  25531. });
  25532. this.animations.forEach(function (o) {
  25533. _this.scene.removeAnimation(o);
  25534. });
  25535. this.multiMaterials.forEach(function (o) {
  25536. _this.scene.removeMultiMaterial(o);
  25537. });
  25538. this.materials.forEach(function (o) {
  25539. _this.scene.removeMaterial(o);
  25540. });
  25541. this.morphTargetManagers.forEach(function (o) {
  25542. _this.scene.removeMorphTargetManager(o);
  25543. });
  25544. this.geometries.forEach(function (o) {
  25545. _this.scene.removeGeometry(o);
  25546. });
  25547. this.transformNodes.forEach(function (o) {
  25548. _this.scene.removeTransformNode(o);
  25549. });
  25550. this.lensFlareSystems.forEach(function (o) {
  25551. _this.scene.removeLensFlareSystem(o);
  25552. });
  25553. this.actionManagers.forEach(function (o) {
  25554. _this.scene.removeActionManager(o);
  25555. });
  25556. this.sounds.forEach(function (o) {
  25557. o.stop();
  25558. o.autoplay = false;
  25559. _this.scene.mainSoundTrack.RemoveSound(o);
  25560. });
  25561. };
  25562. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25563. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25564. var asset = sourceAssets_1[_i];
  25565. var move = true;
  25566. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25567. var keepAsset = keepAssets_1[_a];
  25568. if (asset === keepAsset) {
  25569. move = false;
  25570. break;
  25571. }
  25572. }
  25573. if (move) {
  25574. targetAssets.push(asset);
  25575. }
  25576. }
  25577. };
  25578. /**
  25579. * Removes all the assets contained in the scene and adds them to the container.
  25580. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25581. */
  25582. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25583. if (keepAssets === undefined) {
  25584. keepAssets = new KeepAssets();
  25585. }
  25586. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25587. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25588. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25589. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25590. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25591. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25592. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25593. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25594. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25595. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25596. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25597. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25598. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25599. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25600. this.removeAllFromScene();
  25601. };
  25602. return AssetContainer;
  25603. }());
  25604. BABYLON.AssetContainer = AssetContainer;
  25605. })(BABYLON || (BABYLON = {}));
  25606. //# sourceMappingURL=babylon.assetContainer.js.map
  25607. var BABYLON;
  25608. (function (BABYLON) {
  25609. var Buffer = /** @class */ (function () {
  25610. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25611. if (instanced === void 0) { instanced = false; }
  25612. if (engine instanceof BABYLON.Mesh) {
  25613. this._engine = engine.getScene().getEngine();
  25614. }
  25615. else {
  25616. this._engine = engine;
  25617. }
  25618. this._updatable = updatable;
  25619. this._instanced = instanced;
  25620. this._data = data;
  25621. this._strideSize = stride;
  25622. if (!postponeInternalCreation) {
  25623. this.create();
  25624. }
  25625. }
  25626. /**
  25627. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25628. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25629. * @param offset defines offset in the buffer (0 by default)
  25630. * @param size defines the size in floats of attributes (position is 3 for instance)
  25631. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25632. * @param instanced defines if the vertex buffer contains indexed data
  25633. * @returns the new vertex buffer
  25634. */
  25635. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25636. // a lot of these parameters are ignored as they are overriden by the buffer
  25637. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25638. };
  25639. // Properties
  25640. Buffer.prototype.isUpdatable = function () {
  25641. return this._updatable;
  25642. };
  25643. Buffer.prototype.getData = function () {
  25644. return this._data;
  25645. };
  25646. Buffer.prototype.getBuffer = function () {
  25647. return this._buffer;
  25648. };
  25649. Buffer.prototype.getStrideSize = function () {
  25650. return this._strideSize;
  25651. };
  25652. // public getIsInstanced(): boolean {
  25653. // return this._instanced;
  25654. // }
  25655. // public get instanceDivisor(): number {
  25656. // return this._instanceDivisor;
  25657. // }
  25658. // public set instanceDivisor(value: number) {
  25659. // this._instanceDivisor = value;
  25660. // if (value == 0) {
  25661. // this._instanced = false;
  25662. // } else {
  25663. // this._instanced = true;
  25664. // }
  25665. // }
  25666. // Methods
  25667. Buffer.prototype.create = function (data) {
  25668. if (data === void 0) { data = null; }
  25669. if (!data && this._buffer) {
  25670. return; // nothing to do
  25671. }
  25672. data = data || this._data;
  25673. if (!data) {
  25674. return;
  25675. }
  25676. if (!this._buffer) {
  25677. if (this._updatable) {
  25678. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25679. this._data = data;
  25680. }
  25681. else {
  25682. this._buffer = this._engine.createVertexBuffer(data);
  25683. }
  25684. }
  25685. else if (this._updatable) {
  25686. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25687. this._data = data;
  25688. }
  25689. };
  25690. Buffer.prototype._rebuild = function () {
  25691. this._buffer = null;
  25692. this.create(this._data);
  25693. };
  25694. Buffer.prototype.update = function (data) {
  25695. this.create(data);
  25696. };
  25697. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25698. if (!this._buffer) {
  25699. return;
  25700. }
  25701. if (this._updatable) {
  25702. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25703. this._data = null;
  25704. }
  25705. };
  25706. Buffer.prototype.dispose = function () {
  25707. if (!this._buffer) {
  25708. return;
  25709. }
  25710. if (this._engine._releaseBuffer(this._buffer)) {
  25711. this._buffer = null;
  25712. }
  25713. };
  25714. return Buffer;
  25715. }());
  25716. BABYLON.Buffer = Buffer;
  25717. })(BABYLON || (BABYLON = {}));
  25718. //# sourceMappingURL=babylon.buffer.js.map
  25719. var BABYLON;
  25720. (function (BABYLON) {
  25721. var VertexBuffer = /** @class */ (function () {
  25722. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25723. if (data instanceof BABYLON.Buffer) {
  25724. if (!stride) {
  25725. stride = data.getStrideSize();
  25726. }
  25727. this._buffer = data;
  25728. this._ownsBuffer = false;
  25729. }
  25730. else {
  25731. if (!stride) {
  25732. stride = VertexBuffer.DeduceStride(kind);
  25733. }
  25734. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25735. this._ownsBuffer = true;
  25736. }
  25737. this._stride = stride;
  25738. this._instanced = instanced !== undefined ? instanced : false;
  25739. this._instanceDivisor = instanced ? 1 : 0;
  25740. this._offset = offset ? offset : 0;
  25741. this._size = size ? size : stride;
  25742. this._kind = kind;
  25743. }
  25744. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25745. /**
  25746. * Gets or sets the instance divisor when in instanced mode
  25747. */
  25748. get: function () {
  25749. return this._instanceDivisor;
  25750. },
  25751. set: function (value) {
  25752. this._instanceDivisor = value;
  25753. if (value == 0) {
  25754. this._instanced = false;
  25755. }
  25756. else {
  25757. this._instanced = true;
  25758. }
  25759. },
  25760. enumerable: true,
  25761. configurable: true
  25762. });
  25763. VertexBuffer.prototype._rebuild = function () {
  25764. if (!this._buffer) {
  25765. return;
  25766. }
  25767. this._buffer._rebuild();
  25768. };
  25769. /**
  25770. * Returns the kind of the VertexBuffer (string).
  25771. */
  25772. VertexBuffer.prototype.getKind = function () {
  25773. return this._kind;
  25774. };
  25775. // Properties
  25776. /**
  25777. * Boolean : is the VertexBuffer updatable ?
  25778. */
  25779. VertexBuffer.prototype.isUpdatable = function () {
  25780. return this._buffer.isUpdatable();
  25781. };
  25782. /**
  25783. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25784. */
  25785. VertexBuffer.prototype.getData = function () {
  25786. return this._buffer.getData();
  25787. };
  25788. /**
  25789. * Returns the WebGLBuffer associated to the VertexBuffer.
  25790. */
  25791. VertexBuffer.prototype.getBuffer = function () {
  25792. return this._buffer.getBuffer();
  25793. };
  25794. /**
  25795. * Returns the stride of the VertexBuffer (integer).
  25796. */
  25797. VertexBuffer.prototype.getStrideSize = function () {
  25798. return this._stride;
  25799. };
  25800. /**
  25801. * Returns the offset (integer).
  25802. */
  25803. VertexBuffer.prototype.getOffset = function () {
  25804. return this._offset;
  25805. };
  25806. /**
  25807. * Returns the VertexBuffer total size (integer).
  25808. */
  25809. VertexBuffer.prototype.getSize = function () {
  25810. return this._size;
  25811. };
  25812. /**
  25813. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25814. */
  25815. VertexBuffer.prototype.getIsInstanced = function () {
  25816. return this._instanced;
  25817. };
  25818. /**
  25819. * Returns the instancing divisor, zero for non-instanced (integer).
  25820. */
  25821. VertexBuffer.prototype.getInstanceDivisor = function () {
  25822. return this._instanceDivisor;
  25823. };
  25824. // Methods
  25825. /**
  25826. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25827. * Returns the created WebGLBuffer.
  25828. */
  25829. VertexBuffer.prototype.create = function (data) {
  25830. return this._buffer.create(data);
  25831. };
  25832. /**
  25833. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25834. * This function will create a new buffer if the current one is not updatable
  25835. * Returns the updated WebGLBuffer.
  25836. */
  25837. VertexBuffer.prototype.update = function (data) {
  25838. return this._buffer.update(data);
  25839. };
  25840. /**
  25841. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25842. * Returns the directly updated WebGLBuffer.
  25843. */
  25844. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25845. return this._buffer.updateDirectly(data, offset);
  25846. };
  25847. /**
  25848. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25849. */
  25850. VertexBuffer.prototype.dispose = function () {
  25851. if (this._ownsBuffer) {
  25852. this._buffer.dispose();
  25853. }
  25854. };
  25855. Object.defineProperty(VertexBuffer, "PositionKind", {
  25856. get: function () {
  25857. return VertexBuffer._PositionKind;
  25858. },
  25859. enumerable: true,
  25860. configurable: true
  25861. });
  25862. Object.defineProperty(VertexBuffer, "NormalKind", {
  25863. get: function () {
  25864. return VertexBuffer._NormalKind;
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(VertexBuffer, "TangentKind", {
  25870. get: function () {
  25871. return VertexBuffer._TangentKind;
  25872. },
  25873. enumerable: true,
  25874. configurable: true
  25875. });
  25876. Object.defineProperty(VertexBuffer, "UVKind", {
  25877. get: function () {
  25878. return VertexBuffer._UVKind;
  25879. },
  25880. enumerable: true,
  25881. configurable: true
  25882. });
  25883. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25884. get: function () {
  25885. return VertexBuffer._UV2Kind;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25891. get: function () {
  25892. return VertexBuffer._UV3Kind;
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25898. get: function () {
  25899. return VertexBuffer._UV4Kind;
  25900. },
  25901. enumerable: true,
  25902. configurable: true
  25903. });
  25904. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25905. get: function () {
  25906. return VertexBuffer._UV5Kind;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25912. get: function () {
  25913. return VertexBuffer._UV6Kind;
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(VertexBuffer, "ColorKind", {
  25919. get: function () {
  25920. return VertexBuffer._ColorKind;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25926. get: function () {
  25927. return VertexBuffer._MatricesIndicesKind;
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25933. get: function () {
  25934. return VertexBuffer._MatricesWeightsKind;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25940. get: function () {
  25941. return VertexBuffer._MatricesIndicesExtraKind;
  25942. },
  25943. enumerable: true,
  25944. configurable: true
  25945. });
  25946. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25947. get: function () {
  25948. return VertexBuffer._MatricesWeightsExtraKind;
  25949. },
  25950. enumerable: true,
  25951. configurable: true
  25952. });
  25953. /**
  25954. * Deduces the stride given a kind.
  25955. * @param kind The kind string to deduce
  25956. * @returns The deduced stride
  25957. */
  25958. VertexBuffer.DeduceStride = function (kind) {
  25959. switch (kind) {
  25960. case VertexBuffer.UVKind:
  25961. case VertexBuffer.UV2Kind:
  25962. case VertexBuffer.UV3Kind:
  25963. case VertexBuffer.UV4Kind:
  25964. case VertexBuffer.UV5Kind:
  25965. case VertexBuffer.UV6Kind:
  25966. return 2;
  25967. case VertexBuffer.NormalKind:
  25968. case VertexBuffer.PositionKind:
  25969. return 3;
  25970. case VertexBuffer.ColorKind:
  25971. case VertexBuffer.MatricesIndicesKind:
  25972. case VertexBuffer.MatricesIndicesExtraKind:
  25973. case VertexBuffer.MatricesWeightsKind:
  25974. case VertexBuffer.MatricesWeightsExtraKind:
  25975. case VertexBuffer.TangentKind:
  25976. return 4;
  25977. default:
  25978. throw new Error("Invalid kind '" + kind + "'");
  25979. }
  25980. };
  25981. // Enums
  25982. VertexBuffer._PositionKind = "position";
  25983. VertexBuffer._NormalKind = "normal";
  25984. VertexBuffer._TangentKind = "tangent";
  25985. VertexBuffer._UVKind = "uv";
  25986. VertexBuffer._UV2Kind = "uv2";
  25987. VertexBuffer._UV3Kind = "uv3";
  25988. VertexBuffer._UV4Kind = "uv4";
  25989. VertexBuffer._UV5Kind = "uv5";
  25990. VertexBuffer._UV6Kind = "uv6";
  25991. VertexBuffer._ColorKind = "color";
  25992. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25993. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25994. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25995. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25996. return VertexBuffer;
  25997. }());
  25998. BABYLON.VertexBuffer = VertexBuffer;
  25999. })(BABYLON || (BABYLON = {}));
  26000. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26001. var BABYLON;
  26002. (function (BABYLON) {
  26003. /**
  26004. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26005. */
  26006. var DummyInternalTextureTracker = /** @class */ (function () {
  26007. function DummyInternalTextureTracker() {
  26008. /**
  26009. * Gets or set the previous tracker in the list
  26010. */
  26011. this.previous = null;
  26012. /**
  26013. * Gets or set the next tracker in the list
  26014. */
  26015. this.next = null;
  26016. }
  26017. return DummyInternalTextureTracker;
  26018. }());
  26019. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26020. })(BABYLON || (BABYLON = {}));
  26021. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26022. var BABYLON;
  26023. (function (BABYLON) {
  26024. /**
  26025. * Class used to store data associated with WebGL texture data for the engine
  26026. * This class should not be used directly
  26027. */
  26028. var InternalTexture = /** @class */ (function () {
  26029. /**
  26030. * Creates a new InternalTexture
  26031. * @param engine defines the engine to use
  26032. * @param dataSource defines the type of data that will be used
  26033. */
  26034. function InternalTexture(engine, dataSource) {
  26035. /**
  26036. * Observable called when the texture is loaded
  26037. */
  26038. this.onLoadedObservable = new BABYLON.Observable();
  26039. /**
  26040. * Gets or set the previous tracker in the list
  26041. */
  26042. this.previous = null;
  26043. /**
  26044. * Gets or set the next tracker in the list
  26045. */
  26046. this.next = null;
  26047. // Private
  26048. /** @ignore */
  26049. this._initialSlot = -1;
  26050. /** @ignore */
  26051. this._designatedSlot = -1;
  26052. /** @ignore */
  26053. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26054. /** @ignore */
  26055. this._comparisonFunction = 0;
  26056. /** @ignore */
  26057. this._references = 1;
  26058. this._engine = engine;
  26059. this._dataSource = dataSource;
  26060. this._webGLTexture = engine._createTexture();
  26061. }
  26062. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26063. /**
  26064. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26065. */
  26066. get: function () {
  26067. return this._dataSource;
  26068. },
  26069. enumerable: true,
  26070. configurable: true
  26071. });
  26072. /**
  26073. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26074. */
  26075. InternalTexture.prototype.incrementReferences = function () {
  26076. this._references++;
  26077. };
  26078. /**
  26079. * Change the size of the texture (not the size of the content)
  26080. * @param width defines the new width
  26081. * @param height defines the new height
  26082. * @param depth defines the new depth (1 by default)
  26083. */
  26084. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26085. if (depth === void 0) { depth = 1; }
  26086. this.width = width;
  26087. this.height = height;
  26088. this.depth = depth;
  26089. this.baseWidth = width;
  26090. this.baseHeight = height;
  26091. this.baseDepth = depth;
  26092. this._size = width * height * depth;
  26093. };
  26094. /** @ignore */
  26095. InternalTexture.prototype._rebuild = function () {
  26096. var _this = this;
  26097. var proxy;
  26098. this.isReady = false;
  26099. this._cachedCoordinatesMode = null;
  26100. this._cachedWrapU = null;
  26101. this._cachedWrapV = null;
  26102. this._cachedAnisotropicFilteringLevel = null;
  26103. switch (this._dataSource) {
  26104. case InternalTexture.DATASOURCE_TEMP:
  26105. return;
  26106. case InternalTexture.DATASOURCE_URL:
  26107. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26108. _this.isReady = true;
  26109. }, null, this._buffer, undefined, this.format);
  26110. proxy._swapAndDie(this);
  26111. return;
  26112. case InternalTexture.DATASOURCE_RAW:
  26113. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26114. proxy._swapAndDie(this);
  26115. this.isReady = true;
  26116. return;
  26117. case InternalTexture.DATASOURCE_RAW3D:
  26118. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26119. proxy._swapAndDie(this);
  26120. this.isReady = true;
  26121. return;
  26122. case InternalTexture.DATASOURCE_DYNAMIC:
  26123. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26124. proxy._swapAndDie(this);
  26125. // The engine will make sure to update content so no need to flag it as isReady = true
  26126. return;
  26127. case InternalTexture.DATASOURCE_RENDERTARGET:
  26128. var options = new BABYLON.RenderTargetCreationOptions();
  26129. options.generateDepthBuffer = this._generateDepthBuffer;
  26130. options.generateMipMaps = this.generateMipMaps;
  26131. options.generateStencilBuffer = this._generateStencilBuffer;
  26132. options.samplingMode = this.samplingMode;
  26133. options.type = this.type;
  26134. if (this.isCube) {
  26135. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26136. }
  26137. else {
  26138. var size = {
  26139. width: this.width,
  26140. height: this.height
  26141. };
  26142. proxy = this._engine.createRenderTargetTexture(size, options);
  26143. }
  26144. proxy._swapAndDie(this);
  26145. this.isReady = true;
  26146. return;
  26147. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26148. var depthTextureOptions = {
  26149. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26150. comparisonFunction: this._comparisonFunction,
  26151. generateStencil: this._generateStencilBuffer,
  26152. };
  26153. if (this.isCube) {
  26154. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26155. }
  26156. else {
  26157. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26158. }
  26159. proxy._swapAndDie(this);
  26160. this.isReady = true;
  26161. return;
  26162. case InternalTexture.DATASOURCE_CUBE:
  26163. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26164. _this.isReady = true;
  26165. }, null, this.format, this._extension);
  26166. proxy._swapAndDie(this);
  26167. return;
  26168. case InternalTexture.DATASOURCE_CUBERAW:
  26169. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26170. proxy._swapAndDie(this);
  26171. this.isReady = true;
  26172. return;
  26173. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26174. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26175. if (proxy) {
  26176. proxy._swapAndDie(_this);
  26177. }
  26178. _this.isReady = true;
  26179. }, null, this.format, this._extension);
  26180. return;
  26181. }
  26182. };
  26183. InternalTexture.prototype._swapAndDie = function (target) {
  26184. target._webGLTexture = this._webGLTexture;
  26185. if (this._framebuffer) {
  26186. target._framebuffer = this._framebuffer;
  26187. }
  26188. if (this._depthStencilBuffer) {
  26189. target._depthStencilBuffer = this._depthStencilBuffer;
  26190. }
  26191. if (this._lodTextureHigh) {
  26192. if (target._lodTextureHigh) {
  26193. target._lodTextureHigh.dispose();
  26194. }
  26195. target._lodTextureHigh = this._lodTextureHigh;
  26196. }
  26197. if (this._lodTextureMid) {
  26198. if (target._lodTextureMid) {
  26199. target._lodTextureMid.dispose();
  26200. }
  26201. target._lodTextureMid = this._lodTextureMid;
  26202. }
  26203. if (this._lodTextureLow) {
  26204. if (target._lodTextureLow) {
  26205. target._lodTextureLow.dispose();
  26206. }
  26207. target._lodTextureLow = this._lodTextureLow;
  26208. }
  26209. var cache = this._engine.getLoadedTexturesCache();
  26210. var index = cache.indexOf(this);
  26211. if (index !== -1) {
  26212. cache.splice(index, 1);
  26213. }
  26214. };
  26215. /**
  26216. * Dispose the current allocated resources
  26217. */
  26218. InternalTexture.prototype.dispose = function () {
  26219. if (!this._webGLTexture) {
  26220. return;
  26221. }
  26222. this._references--;
  26223. if (this._references === 0) {
  26224. this._engine._releaseTexture(this);
  26225. this._webGLTexture = null;
  26226. this.previous = null;
  26227. this.next = null;
  26228. }
  26229. };
  26230. /**
  26231. * The source of the texture data is unknown
  26232. */
  26233. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26234. /**
  26235. * Texture data comes from an URL
  26236. */
  26237. InternalTexture.DATASOURCE_URL = 1;
  26238. /**
  26239. * Texture data is only used for temporary storage
  26240. */
  26241. InternalTexture.DATASOURCE_TEMP = 2;
  26242. /**
  26243. * Texture data comes from raw data (ArrayBuffer)
  26244. */
  26245. InternalTexture.DATASOURCE_RAW = 3;
  26246. /**
  26247. * Texture content is dynamic (video or dynamic texture)
  26248. */
  26249. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26250. /**
  26251. * Texture content is generated by rendering to it
  26252. */
  26253. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26254. /**
  26255. * Texture content is part of a multi render target process
  26256. */
  26257. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26258. /**
  26259. * Texture data comes from a cube data file
  26260. */
  26261. InternalTexture.DATASOURCE_CUBE = 7;
  26262. /**
  26263. * Texture data comes from a raw cube data
  26264. */
  26265. InternalTexture.DATASOURCE_CUBERAW = 8;
  26266. /**
  26267. * Texture data come from a prefiltered cube data file
  26268. */
  26269. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26270. /**
  26271. * Texture content is raw 3D data
  26272. */
  26273. InternalTexture.DATASOURCE_RAW3D = 10;
  26274. /**
  26275. * Texture content is a depth texture
  26276. */
  26277. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26278. return InternalTexture;
  26279. }());
  26280. BABYLON.InternalTexture = InternalTexture;
  26281. })(BABYLON || (BABYLON = {}));
  26282. //# sourceMappingURL=babylon.internalTexture.js.map
  26283. var BABYLON;
  26284. (function (BABYLON) {
  26285. var BaseTexture = /** @class */ (function () {
  26286. function BaseTexture(scene) {
  26287. this._hasAlpha = false;
  26288. this.getAlphaFromRGB = false;
  26289. this.level = 1;
  26290. this.coordinatesIndex = 0;
  26291. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26292. /**
  26293. * | Value | Type | Description |
  26294. * | ----- | ------------------ | ----------- |
  26295. * | 0 | CLAMP_ADDRESSMODE | |
  26296. * | 1 | WRAP_ADDRESSMODE | |
  26297. * | 2 | MIRROR_ADDRESSMODE | |
  26298. */
  26299. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26300. /**
  26301. * | Value | Type | Description |
  26302. * | ----- | ------------------ | ----------- |
  26303. * | 0 | CLAMP_ADDRESSMODE | |
  26304. * | 1 | WRAP_ADDRESSMODE | |
  26305. * | 2 | MIRROR_ADDRESSMODE | |
  26306. */
  26307. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26308. /**
  26309. * | Value | Type | Description |
  26310. * | ----- | ------------------ | ----------- |
  26311. * | 0 | CLAMP_ADDRESSMODE | |
  26312. * | 1 | WRAP_ADDRESSMODE | |
  26313. * | 2 | MIRROR_ADDRESSMODE | |
  26314. */
  26315. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26316. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26317. this.isCube = false;
  26318. this.is3D = false;
  26319. this.gammaSpace = true;
  26320. this.invertZ = false;
  26321. this.lodLevelInAlpha = false;
  26322. this.lodGenerationOffset = 0.0;
  26323. this.lodGenerationScale = 0.8;
  26324. this.isRenderTarget = false;
  26325. this.animations = new Array();
  26326. /**
  26327. * An event triggered when the texture is disposed.
  26328. * @type {BABYLON.Observable}
  26329. */
  26330. this.onDisposeObservable = new BABYLON.Observable();
  26331. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26332. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26333. if (this._scene) {
  26334. this._scene.textures.push(this);
  26335. }
  26336. this._uid = null;
  26337. }
  26338. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26339. get: function () {
  26340. return this._hasAlpha;
  26341. },
  26342. set: function (value) {
  26343. if (this._hasAlpha === value) {
  26344. return;
  26345. }
  26346. this._hasAlpha = value;
  26347. if (this._scene) {
  26348. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26349. }
  26350. },
  26351. enumerable: true,
  26352. configurable: true
  26353. });
  26354. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26355. get: function () {
  26356. return this._coordinatesMode;
  26357. },
  26358. /**
  26359. * How a texture is mapped.
  26360. *
  26361. * | Value | Type | Description |
  26362. * | ----- | ----------------------------------- | ----------- |
  26363. * | 0 | EXPLICIT_MODE | |
  26364. * | 1 | SPHERICAL_MODE | |
  26365. * | 2 | PLANAR_MODE | |
  26366. * | 3 | CUBIC_MODE | |
  26367. * | 4 | PROJECTION_MODE | |
  26368. * | 5 | SKYBOX_MODE | |
  26369. * | 6 | INVCUBIC_MODE | |
  26370. * | 7 | EQUIRECTANGULAR_MODE | |
  26371. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26372. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26373. */
  26374. set: function (value) {
  26375. if (this._coordinatesMode === value) {
  26376. return;
  26377. }
  26378. this._coordinatesMode = value;
  26379. if (this._scene) {
  26380. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26381. }
  26382. },
  26383. enumerable: true,
  26384. configurable: true
  26385. });
  26386. Object.defineProperty(BaseTexture.prototype, "uid", {
  26387. get: function () {
  26388. if (!this._uid) {
  26389. this._uid = BABYLON.Tools.RandomId();
  26390. }
  26391. return this._uid;
  26392. },
  26393. enumerable: true,
  26394. configurable: true
  26395. });
  26396. BaseTexture.prototype.toString = function () {
  26397. return this.name;
  26398. };
  26399. BaseTexture.prototype.getClassName = function () {
  26400. return "BaseTexture";
  26401. };
  26402. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26403. set: function (callback) {
  26404. if (this._onDisposeObserver) {
  26405. this.onDisposeObservable.remove(this._onDisposeObserver);
  26406. }
  26407. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26408. },
  26409. enumerable: true,
  26410. configurable: true
  26411. });
  26412. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26413. get: function () {
  26414. return true;
  26415. },
  26416. enumerable: true,
  26417. configurable: true
  26418. });
  26419. BaseTexture.prototype.getScene = function () {
  26420. return this._scene;
  26421. };
  26422. BaseTexture.prototype.getTextureMatrix = function () {
  26423. return BABYLON.Matrix.IdentityReadOnly;
  26424. };
  26425. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26426. return BABYLON.Matrix.IdentityReadOnly;
  26427. };
  26428. BaseTexture.prototype.getInternalTexture = function () {
  26429. return this._texture;
  26430. };
  26431. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26432. return !this.isBlocking || this.isReady();
  26433. };
  26434. BaseTexture.prototype.isReady = function () {
  26435. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26436. this.delayLoad();
  26437. return false;
  26438. }
  26439. if (this._texture) {
  26440. return this._texture.isReady;
  26441. }
  26442. return false;
  26443. };
  26444. BaseTexture.prototype.getSize = function () {
  26445. if (this._texture && this._texture.width) {
  26446. return new BABYLON.Size(this._texture.width, this._texture.height);
  26447. }
  26448. if (this._texture && this._texture._size) {
  26449. return new BABYLON.Size(this._texture._size, this._texture._size);
  26450. }
  26451. return BABYLON.Size.Zero();
  26452. };
  26453. BaseTexture.prototype.getBaseSize = function () {
  26454. if (!this.isReady() || !this._texture)
  26455. return BABYLON.Size.Zero();
  26456. if (this._texture._size) {
  26457. return new BABYLON.Size(this._texture._size, this._texture._size);
  26458. }
  26459. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26460. };
  26461. BaseTexture.prototype.scale = function (ratio) {
  26462. };
  26463. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26464. get: function () {
  26465. return false;
  26466. },
  26467. enumerable: true,
  26468. configurable: true
  26469. });
  26470. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26471. if (!this._scene) {
  26472. return null;
  26473. }
  26474. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26475. for (var index = 0; index < texturesCache.length; index++) {
  26476. var texturesCacheEntry = texturesCache[index];
  26477. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26478. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26479. texturesCacheEntry.incrementReferences();
  26480. return texturesCacheEntry;
  26481. }
  26482. }
  26483. }
  26484. return null;
  26485. };
  26486. BaseTexture.prototype._rebuild = function () {
  26487. };
  26488. BaseTexture.prototype.delayLoad = function () {
  26489. };
  26490. BaseTexture.prototype.clone = function () {
  26491. return null;
  26492. };
  26493. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26494. get: function () {
  26495. if (!this._texture) {
  26496. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26497. }
  26498. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26499. },
  26500. enumerable: true,
  26501. configurable: true
  26502. });
  26503. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26504. get: function () {
  26505. if (!this._texture) {
  26506. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26507. }
  26508. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26509. },
  26510. enumerable: true,
  26511. configurable: true
  26512. });
  26513. BaseTexture.prototype.readPixels = function (faceIndex) {
  26514. if (faceIndex === void 0) { faceIndex = 0; }
  26515. if (!this._texture) {
  26516. return null;
  26517. }
  26518. var size = this.getSize();
  26519. var scene = this.getScene();
  26520. if (!scene) {
  26521. return null;
  26522. }
  26523. var engine = scene.getEngine();
  26524. if (this._texture.isCube) {
  26525. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26526. }
  26527. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26528. };
  26529. BaseTexture.prototype.releaseInternalTexture = function () {
  26530. if (this._texture) {
  26531. this._texture.dispose();
  26532. this._texture = null;
  26533. }
  26534. };
  26535. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26536. get: function () {
  26537. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26538. return null;
  26539. }
  26540. if (!this._texture._sphericalPolynomial) {
  26541. this._texture._sphericalPolynomial =
  26542. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26543. }
  26544. return this._texture._sphericalPolynomial;
  26545. },
  26546. set: function (value) {
  26547. if (this._texture) {
  26548. this._texture._sphericalPolynomial = value;
  26549. }
  26550. },
  26551. enumerable: true,
  26552. configurable: true
  26553. });
  26554. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26555. get: function () {
  26556. if (this._texture) {
  26557. return this._texture._lodTextureHigh;
  26558. }
  26559. return null;
  26560. },
  26561. enumerable: true,
  26562. configurable: true
  26563. });
  26564. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26565. get: function () {
  26566. if (this._texture) {
  26567. return this._texture._lodTextureMid;
  26568. }
  26569. return null;
  26570. },
  26571. enumerable: true,
  26572. configurable: true
  26573. });
  26574. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26575. get: function () {
  26576. if (this._texture) {
  26577. return this._texture._lodTextureLow;
  26578. }
  26579. return null;
  26580. },
  26581. enumerable: true,
  26582. configurable: true
  26583. });
  26584. BaseTexture.prototype.dispose = function () {
  26585. if (!this._scene) {
  26586. return;
  26587. }
  26588. // Animations
  26589. this._scene.stopAnimation(this);
  26590. // Remove from scene
  26591. this._scene._removePendingData(this);
  26592. var index = this._scene.textures.indexOf(this);
  26593. if (index >= 0) {
  26594. this._scene.textures.splice(index, 1);
  26595. }
  26596. if (this._texture === undefined) {
  26597. return;
  26598. }
  26599. // Release
  26600. this.releaseInternalTexture();
  26601. // Callback
  26602. this.onDisposeObservable.notifyObservers(this);
  26603. this.onDisposeObservable.clear();
  26604. };
  26605. BaseTexture.prototype.serialize = function () {
  26606. if (!this.name) {
  26607. return null;
  26608. }
  26609. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26610. // Animations
  26611. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26612. return serializationObject;
  26613. };
  26614. BaseTexture.WhenAllReady = function (textures, callback) {
  26615. var numRemaining = textures.length;
  26616. if (numRemaining === 0) {
  26617. callback();
  26618. return;
  26619. }
  26620. var _loop_1 = function () {
  26621. texture = textures[i];
  26622. if (texture.isReady()) {
  26623. if (--numRemaining === 0) {
  26624. callback();
  26625. }
  26626. }
  26627. else {
  26628. onLoadObservable = texture.onLoadObservable;
  26629. var onLoadCallback_1 = function () {
  26630. onLoadObservable.removeCallback(onLoadCallback_1);
  26631. if (--numRemaining === 0) {
  26632. callback();
  26633. }
  26634. };
  26635. onLoadObservable.add(onLoadCallback_1);
  26636. }
  26637. };
  26638. var texture, onLoadObservable;
  26639. for (var i = 0; i < textures.length; i++) {
  26640. _loop_1();
  26641. }
  26642. };
  26643. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26644. __decorate([
  26645. BABYLON.serialize()
  26646. ], BaseTexture.prototype, "name", void 0);
  26647. __decorate([
  26648. BABYLON.serialize("hasAlpha")
  26649. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26650. __decorate([
  26651. BABYLON.serialize()
  26652. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26653. __decorate([
  26654. BABYLON.serialize()
  26655. ], BaseTexture.prototype, "level", void 0);
  26656. __decorate([
  26657. BABYLON.serialize()
  26658. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26659. __decorate([
  26660. BABYLON.serialize("coordinatesMode")
  26661. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26662. __decorate([
  26663. BABYLON.serialize()
  26664. ], BaseTexture.prototype, "wrapU", void 0);
  26665. __decorate([
  26666. BABYLON.serialize()
  26667. ], BaseTexture.prototype, "wrapV", void 0);
  26668. __decorate([
  26669. BABYLON.serialize()
  26670. ], BaseTexture.prototype, "wrapR", void 0);
  26671. __decorate([
  26672. BABYLON.serialize()
  26673. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26674. __decorate([
  26675. BABYLON.serialize()
  26676. ], BaseTexture.prototype, "isCube", void 0);
  26677. __decorate([
  26678. BABYLON.serialize()
  26679. ], BaseTexture.prototype, "is3D", void 0);
  26680. __decorate([
  26681. BABYLON.serialize()
  26682. ], BaseTexture.prototype, "gammaSpace", void 0);
  26683. __decorate([
  26684. BABYLON.serialize()
  26685. ], BaseTexture.prototype, "invertZ", void 0);
  26686. __decorate([
  26687. BABYLON.serialize()
  26688. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26689. __decorate([
  26690. BABYLON.serialize()
  26691. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26692. __decorate([
  26693. BABYLON.serialize()
  26694. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26695. __decorate([
  26696. BABYLON.serialize()
  26697. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26698. return BaseTexture;
  26699. }());
  26700. BABYLON.BaseTexture = BaseTexture;
  26701. })(BABYLON || (BABYLON = {}));
  26702. //# sourceMappingURL=babylon.baseTexture.js.map
  26703. var BABYLON;
  26704. (function (BABYLON) {
  26705. var Texture = /** @class */ (function (_super) {
  26706. __extends(Texture, _super);
  26707. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26708. if (noMipmap === void 0) { noMipmap = false; }
  26709. if (invertY === void 0) { invertY = true; }
  26710. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26711. if (onLoad === void 0) { onLoad = null; }
  26712. if (onError === void 0) { onError = null; }
  26713. if (buffer === void 0) { buffer = null; }
  26714. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26715. var _this = _super.call(this, scene) || this;
  26716. _this.uOffset = 0;
  26717. _this.vOffset = 0;
  26718. _this.uScale = 1.0;
  26719. _this.vScale = 1.0;
  26720. _this.uAng = 0;
  26721. _this.vAng = 0;
  26722. _this.wAng = 0;
  26723. _this._isBlocking = true;
  26724. _this.name = url || "";
  26725. _this.url = url;
  26726. _this._noMipmap = noMipmap;
  26727. _this._invertY = invertY;
  26728. _this._samplingMode = samplingMode;
  26729. _this._buffer = buffer;
  26730. _this._deleteBuffer = deleteBuffer;
  26731. if (format) {
  26732. _this._format = format;
  26733. }
  26734. scene = _this.getScene();
  26735. if (!scene) {
  26736. return _this;
  26737. }
  26738. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26739. var load = function () {
  26740. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26741. _this.onLoadObservable.notifyObservers(_this);
  26742. }
  26743. if (onLoad) {
  26744. onLoad();
  26745. }
  26746. if (!_this.isBlocking && scene) {
  26747. scene.resetCachedMaterial();
  26748. }
  26749. };
  26750. if (!_this.url) {
  26751. _this._delayedOnLoad = load;
  26752. _this._delayedOnError = onError;
  26753. return _this;
  26754. }
  26755. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26756. if (!_this._texture) {
  26757. if (!scene.useDelayedTextureLoading) {
  26758. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26759. if (deleteBuffer) {
  26760. delete _this._buffer;
  26761. }
  26762. }
  26763. else {
  26764. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26765. _this._delayedOnLoad = load;
  26766. _this._delayedOnError = onError;
  26767. }
  26768. }
  26769. else {
  26770. if (_this._texture.isReady) {
  26771. BABYLON.Tools.SetImmediate(function () { return load(); });
  26772. }
  26773. else {
  26774. _this._texture.onLoadedObservable.add(load);
  26775. }
  26776. }
  26777. return _this;
  26778. }
  26779. Object.defineProperty(Texture.prototype, "noMipmap", {
  26780. get: function () {
  26781. return this._noMipmap;
  26782. },
  26783. enumerable: true,
  26784. configurable: true
  26785. });
  26786. Object.defineProperty(Texture.prototype, "isBlocking", {
  26787. get: function () {
  26788. return this._isBlocking;
  26789. },
  26790. set: function (value) {
  26791. this._isBlocking = value;
  26792. },
  26793. enumerable: true,
  26794. configurable: true
  26795. });
  26796. Object.defineProperty(Texture.prototype, "samplingMode", {
  26797. get: function () {
  26798. return this._samplingMode;
  26799. },
  26800. enumerable: true,
  26801. configurable: true
  26802. });
  26803. Texture.prototype.updateURL = function (url) {
  26804. this.url = url;
  26805. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26806. this.delayLoad();
  26807. };
  26808. Texture.prototype.delayLoad = function () {
  26809. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26810. return;
  26811. }
  26812. var scene = this.getScene();
  26813. if (!scene) {
  26814. return;
  26815. }
  26816. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26817. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26818. if (!this._texture) {
  26819. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26820. if (this._deleteBuffer) {
  26821. delete this._buffer;
  26822. }
  26823. }
  26824. else {
  26825. if (this._delayedOnLoad) {
  26826. if (this._texture.isReady) {
  26827. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26828. }
  26829. else {
  26830. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26831. }
  26832. }
  26833. }
  26834. this._delayedOnLoad = null;
  26835. this._delayedOnError = null;
  26836. };
  26837. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26838. if (!this._texture) {
  26839. return;
  26840. }
  26841. var scene = this.getScene();
  26842. if (!scene) {
  26843. return;
  26844. }
  26845. this._samplingMode = samplingMode;
  26846. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26847. };
  26848. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26849. x *= this.uScale;
  26850. y *= this.vScale;
  26851. x -= 0.5 * this.uScale;
  26852. y -= 0.5 * this.vScale;
  26853. z -= 0.5;
  26854. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26855. t.x += 0.5 * this.uScale + this.uOffset;
  26856. t.y += 0.5 * this.vScale + this.vOffset;
  26857. t.z += 0.5;
  26858. };
  26859. Texture.prototype.getTextureMatrix = function () {
  26860. var _this = this;
  26861. if (this.uOffset === this._cachedUOffset &&
  26862. this.vOffset === this._cachedVOffset &&
  26863. this.uScale === this._cachedUScale &&
  26864. this.vScale === this._cachedVScale &&
  26865. this.uAng === this._cachedUAng &&
  26866. this.vAng === this._cachedVAng &&
  26867. this.wAng === this._cachedWAng) {
  26868. return this._cachedTextureMatrix;
  26869. }
  26870. this._cachedUOffset = this.uOffset;
  26871. this._cachedVOffset = this.vOffset;
  26872. this._cachedUScale = this.uScale;
  26873. this._cachedVScale = this.vScale;
  26874. this._cachedUAng = this.uAng;
  26875. this._cachedVAng = this.vAng;
  26876. this._cachedWAng = this.wAng;
  26877. if (!this._cachedTextureMatrix) {
  26878. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26879. this._rowGenerationMatrix = new BABYLON.Matrix();
  26880. this._t0 = BABYLON.Vector3.Zero();
  26881. this._t1 = BABYLON.Vector3.Zero();
  26882. this._t2 = BABYLON.Vector3.Zero();
  26883. }
  26884. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26885. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26886. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26887. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26888. this._t1.subtractInPlace(this._t0);
  26889. this._t2.subtractInPlace(this._t0);
  26890. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26891. this._cachedTextureMatrix.m[0] = this._t1.x;
  26892. this._cachedTextureMatrix.m[1] = this._t1.y;
  26893. this._cachedTextureMatrix.m[2] = this._t1.z;
  26894. this._cachedTextureMatrix.m[4] = this._t2.x;
  26895. this._cachedTextureMatrix.m[5] = this._t2.y;
  26896. this._cachedTextureMatrix.m[6] = this._t2.z;
  26897. this._cachedTextureMatrix.m[8] = this._t0.x;
  26898. this._cachedTextureMatrix.m[9] = this._t0.y;
  26899. this._cachedTextureMatrix.m[10] = this._t0.z;
  26900. var scene = this.getScene();
  26901. if (!scene) {
  26902. return this._cachedTextureMatrix;
  26903. }
  26904. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26905. return mat.hasTexture(_this);
  26906. });
  26907. return this._cachedTextureMatrix;
  26908. };
  26909. Texture.prototype.getReflectionTextureMatrix = function () {
  26910. var _this = this;
  26911. var scene = this.getScene();
  26912. if (!scene) {
  26913. return this._cachedTextureMatrix;
  26914. }
  26915. if (this.uOffset === this._cachedUOffset &&
  26916. this.vOffset === this._cachedVOffset &&
  26917. this.uScale === this._cachedUScale &&
  26918. this.vScale === this._cachedVScale &&
  26919. this.coordinatesMode === this._cachedCoordinatesMode) {
  26920. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26921. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26922. return this._cachedTextureMatrix;
  26923. }
  26924. }
  26925. else {
  26926. return this._cachedTextureMatrix;
  26927. }
  26928. }
  26929. if (!this._cachedTextureMatrix) {
  26930. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26931. }
  26932. if (!this._projectionModeMatrix) {
  26933. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26934. }
  26935. this._cachedUOffset = this.uOffset;
  26936. this._cachedVOffset = this.vOffset;
  26937. this._cachedUScale = this.uScale;
  26938. this._cachedVScale = this.vScale;
  26939. this._cachedCoordinatesMode = this.coordinatesMode;
  26940. switch (this.coordinatesMode) {
  26941. case Texture.PLANAR_MODE:
  26942. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26943. this._cachedTextureMatrix[0] = this.uScale;
  26944. this._cachedTextureMatrix[5] = this.vScale;
  26945. this._cachedTextureMatrix[12] = this.uOffset;
  26946. this._cachedTextureMatrix[13] = this.vOffset;
  26947. break;
  26948. case Texture.PROJECTION_MODE:
  26949. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26950. this._projectionModeMatrix.m[0] = 0.5;
  26951. this._projectionModeMatrix.m[5] = -0.5;
  26952. this._projectionModeMatrix.m[10] = 0.0;
  26953. this._projectionModeMatrix.m[12] = 0.5;
  26954. this._projectionModeMatrix.m[13] = 0.5;
  26955. this._projectionModeMatrix.m[14] = 1.0;
  26956. this._projectionModeMatrix.m[15] = 1.0;
  26957. var projectionMatrix = scene.getProjectionMatrix();
  26958. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26959. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26960. break;
  26961. default:
  26962. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26963. break;
  26964. }
  26965. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26966. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26967. });
  26968. return this._cachedTextureMatrix;
  26969. };
  26970. Texture.prototype.clone = function () {
  26971. var _this = this;
  26972. return BABYLON.SerializationHelper.Clone(function () {
  26973. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26974. }, this);
  26975. };
  26976. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26977. get: function () {
  26978. if (!this._onLoadObservable) {
  26979. this._onLoadObservable = new BABYLON.Observable();
  26980. }
  26981. return this._onLoadObservable;
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. Texture.prototype.serialize = function () {
  26987. var serializationObject = _super.prototype.serialize.call(this);
  26988. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26989. serializationObject.base64String = this._buffer;
  26990. serializationObject.name = serializationObject.name.replace("data:", "");
  26991. }
  26992. return serializationObject;
  26993. };
  26994. Texture.prototype.getClassName = function () {
  26995. return "Texture";
  26996. };
  26997. Texture.prototype.dispose = function () {
  26998. _super.prototype.dispose.call(this);
  26999. if (this.onLoadObservable) {
  27000. this.onLoadObservable.clear();
  27001. this._onLoadObservable = null;
  27002. }
  27003. this._delayedOnLoad = null;
  27004. this._delayedOnError = null;
  27005. };
  27006. // Statics
  27007. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27008. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27009. if (onLoad === void 0) { onLoad = null; }
  27010. if (onError === void 0) { onError = null; }
  27011. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27012. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27013. };
  27014. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27015. if (parsedTexture.customType) {
  27016. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27017. // Update Sampling Mode
  27018. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27019. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27020. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27021. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27022. }
  27023. }
  27024. return parsedCustomTexture;
  27025. }
  27026. if (parsedTexture.isCube) {
  27027. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27028. }
  27029. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27030. return null;
  27031. }
  27032. var texture = BABYLON.SerializationHelper.Parse(function () {
  27033. var generateMipMaps = true;
  27034. if (parsedTexture.noMipmap) {
  27035. generateMipMaps = false;
  27036. }
  27037. if (parsedTexture.mirrorPlane) {
  27038. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27039. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27040. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27041. return mirrorTexture;
  27042. }
  27043. else if (parsedTexture.isRenderTarget) {
  27044. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27045. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27046. return renderTargetTexture;
  27047. }
  27048. else {
  27049. var texture;
  27050. if (parsedTexture.base64String) {
  27051. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27052. }
  27053. else {
  27054. var url = rootUrl + parsedTexture.name;
  27055. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27056. url = parsedTexture.url;
  27057. }
  27058. texture = new Texture(url, scene, !generateMipMaps);
  27059. }
  27060. return texture;
  27061. }
  27062. }, parsedTexture, scene);
  27063. // Update Sampling Mode
  27064. if (parsedTexture.samplingMode) {
  27065. var sampling = parsedTexture.samplingMode;
  27066. if (texture._samplingMode !== sampling) {
  27067. texture.updateSamplingMode(sampling);
  27068. }
  27069. }
  27070. // Animations
  27071. if (parsedTexture.animations) {
  27072. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27073. var parsedAnimation = parsedTexture.animations[animationIndex];
  27074. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27075. }
  27076. }
  27077. return texture;
  27078. };
  27079. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27080. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27081. if (noMipmap === void 0) { noMipmap = false; }
  27082. if (invertY === void 0) { invertY = true; }
  27083. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27084. if (onLoad === void 0) { onLoad = null; }
  27085. if (onError === void 0) { onError = null; }
  27086. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27087. if (name.substr(0, 5) !== "data:") {
  27088. name = "data:" + name;
  27089. }
  27090. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27091. };
  27092. // Constants
  27093. Texture.NEAREST_SAMPLINGMODE = 1;
  27094. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27095. Texture.BILINEAR_SAMPLINGMODE = 2;
  27096. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27097. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27098. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27099. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27100. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27101. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27102. Texture.NEAREST_LINEAR = 7;
  27103. Texture.NEAREST_NEAREST = 8;
  27104. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27105. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27106. Texture.LINEAR_LINEAR = 11;
  27107. Texture.LINEAR_NEAREST = 12;
  27108. Texture.EXPLICIT_MODE = 0;
  27109. Texture.SPHERICAL_MODE = 1;
  27110. Texture.PLANAR_MODE = 2;
  27111. Texture.CUBIC_MODE = 3;
  27112. Texture.PROJECTION_MODE = 4;
  27113. Texture.SKYBOX_MODE = 5;
  27114. Texture.INVCUBIC_MODE = 6;
  27115. Texture.EQUIRECTANGULAR_MODE = 7;
  27116. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27117. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27118. Texture.CLAMP_ADDRESSMODE = 0;
  27119. Texture.WRAP_ADDRESSMODE = 1;
  27120. Texture.MIRROR_ADDRESSMODE = 2;
  27121. /**
  27122. * 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
  27123. */
  27124. Texture.UseSerializedUrlIfAny = false;
  27125. __decorate([
  27126. BABYLON.serialize()
  27127. ], Texture.prototype, "url", void 0);
  27128. __decorate([
  27129. BABYLON.serialize()
  27130. ], Texture.prototype, "uOffset", void 0);
  27131. __decorate([
  27132. BABYLON.serialize()
  27133. ], Texture.prototype, "vOffset", void 0);
  27134. __decorate([
  27135. BABYLON.serialize()
  27136. ], Texture.prototype, "uScale", void 0);
  27137. __decorate([
  27138. BABYLON.serialize()
  27139. ], Texture.prototype, "vScale", void 0);
  27140. __decorate([
  27141. BABYLON.serialize()
  27142. ], Texture.prototype, "uAng", void 0);
  27143. __decorate([
  27144. BABYLON.serialize()
  27145. ], Texture.prototype, "vAng", void 0);
  27146. __decorate([
  27147. BABYLON.serialize()
  27148. ], Texture.prototype, "wAng", void 0);
  27149. __decorate([
  27150. BABYLON.serialize()
  27151. ], Texture.prototype, "isBlocking", null);
  27152. return Texture;
  27153. }(BABYLON.BaseTexture));
  27154. BABYLON.Texture = Texture;
  27155. })(BABYLON || (BABYLON = {}));
  27156. //# sourceMappingURL=babylon.texture.js.map
  27157. var BABYLON;
  27158. (function (BABYLON) {
  27159. var _InstancesBatch = /** @class */ (function () {
  27160. function _InstancesBatch() {
  27161. this.mustReturn = false;
  27162. this.visibleInstances = new Array();
  27163. this.renderSelf = new Array();
  27164. }
  27165. return _InstancesBatch;
  27166. }());
  27167. BABYLON._InstancesBatch = _InstancesBatch;
  27168. var Mesh = /** @class */ (function (_super) {
  27169. __extends(Mesh, _super);
  27170. /**
  27171. * @constructor
  27172. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27173. * @param {Scene} scene The scene to add this mesh to.
  27174. * @param {Node} parent The parent of this mesh, if it has one
  27175. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27176. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27177. * When false, achieved by calling a clone(), also passing False.
  27178. * This will make creation of children, recursive.
  27179. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27180. */
  27181. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27182. if (scene === void 0) { scene = null; }
  27183. if (parent === void 0) { parent = null; }
  27184. if (source === void 0) { source = null; }
  27185. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27186. var _this = _super.call(this, name, scene) || this;
  27187. // Events
  27188. /**
  27189. * An event triggered before rendering the mesh
  27190. * @type {BABYLON.Observable}
  27191. */
  27192. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27193. /**
  27194. * An event triggered after rendering the mesh
  27195. * @type {BABYLON.Observable}
  27196. */
  27197. _this.onAfterRenderObservable = new BABYLON.Observable();
  27198. /**
  27199. * An event triggered before drawing the mesh
  27200. * @type {BABYLON.Observable}
  27201. */
  27202. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27203. // Members
  27204. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27205. _this.instances = new Array();
  27206. _this._LODLevels = new Array();
  27207. _this._visibleInstances = {};
  27208. _this._renderIdForInstances = new Array();
  27209. _this._batchCache = new _InstancesBatch();
  27210. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27211. // Use by builder only to know what orientation were the mesh build in.
  27212. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27213. _this.overrideMaterialSideOrientation = null;
  27214. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27215. // Will be used to save a source mesh reference, If any
  27216. _this._source = null;
  27217. scene = _this.getScene();
  27218. if (source) {
  27219. // Source mesh
  27220. _this._source = source;
  27221. // Geometry
  27222. if (source._geometry) {
  27223. source._geometry.applyToMesh(_this);
  27224. }
  27225. // Deep copy
  27226. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27227. // Metadata
  27228. if (source.metadata && source.metadata.clone) {
  27229. _this.metadata = source.metadata.clone();
  27230. }
  27231. else {
  27232. _this.metadata = source.metadata;
  27233. }
  27234. // Tags
  27235. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27236. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27237. }
  27238. // Parent
  27239. _this.parent = source.parent;
  27240. // Pivot
  27241. _this.setPivotMatrix(source.getPivotMatrix());
  27242. _this.id = name + "." + source.id;
  27243. // Material
  27244. _this.material = source.material;
  27245. var index;
  27246. if (!doNotCloneChildren) {
  27247. // Children
  27248. var directDescendants = source.getDescendants(true);
  27249. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27250. var child = directDescendants[index_1];
  27251. if (child.clone) {
  27252. child.clone(name + "." + child.name, _this);
  27253. }
  27254. }
  27255. }
  27256. // Physics clone
  27257. var physicsEngine = _this.getScene().getPhysicsEngine();
  27258. if (clonePhysicsImpostor && physicsEngine) {
  27259. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27260. if (impostor) {
  27261. _this.physicsImpostor = impostor.clone(_this);
  27262. }
  27263. }
  27264. // Particles
  27265. for (index = 0; index < scene.particleSystems.length; index++) {
  27266. var system = scene.particleSystems[index];
  27267. if (system.emitter === source) {
  27268. system.clone(system.name, _this);
  27269. }
  27270. }
  27271. _this.computeWorldMatrix(true);
  27272. }
  27273. // Parent
  27274. if (parent !== null) {
  27275. _this.parent = parent;
  27276. }
  27277. return _this;
  27278. }
  27279. Object.defineProperty(Mesh, "FRONTSIDE", {
  27280. /**
  27281. * Mesh side orientation : usually the external or front surface
  27282. */
  27283. get: function () {
  27284. return Mesh._FRONTSIDE;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. Object.defineProperty(Mesh, "BACKSIDE", {
  27290. /**
  27291. * Mesh side orientation : usually the internal or back surface
  27292. */
  27293. get: function () {
  27294. return Mesh._BACKSIDE;
  27295. },
  27296. enumerable: true,
  27297. configurable: true
  27298. });
  27299. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27300. /**
  27301. * Mesh side orientation : both internal and external or front and back surfaces
  27302. */
  27303. get: function () {
  27304. return Mesh._DOUBLESIDE;
  27305. },
  27306. enumerable: true,
  27307. configurable: true
  27308. });
  27309. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27310. /**
  27311. * Mesh side orientation : by default, `FRONTSIDE`
  27312. */
  27313. get: function () {
  27314. return Mesh._DEFAULTSIDE;
  27315. },
  27316. enumerable: true,
  27317. configurable: true
  27318. });
  27319. Object.defineProperty(Mesh, "NO_CAP", {
  27320. /**
  27321. * Mesh cap setting : no cap
  27322. */
  27323. get: function () {
  27324. return Mesh._NO_CAP;
  27325. },
  27326. enumerable: true,
  27327. configurable: true
  27328. });
  27329. Object.defineProperty(Mesh, "CAP_START", {
  27330. /**
  27331. * Mesh cap setting : one cap at the beginning of the mesh
  27332. */
  27333. get: function () {
  27334. return Mesh._CAP_START;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(Mesh, "CAP_END", {
  27340. /**
  27341. * Mesh cap setting : one cap at the end of the mesh
  27342. */
  27343. get: function () {
  27344. return Mesh._CAP_END;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. Object.defineProperty(Mesh, "CAP_ALL", {
  27350. /**
  27351. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27352. */
  27353. get: function () {
  27354. return Mesh._CAP_ALL;
  27355. },
  27356. enumerable: true,
  27357. configurable: true
  27358. });
  27359. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27360. set: function (callback) {
  27361. if (this._onBeforeDrawObserver) {
  27362. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27363. }
  27364. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27365. },
  27366. enumerable: true,
  27367. configurable: true
  27368. });
  27369. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27370. get: function () {
  27371. return this._morphTargetManager;
  27372. },
  27373. set: function (value) {
  27374. if (this._morphTargetManager === value) {
  27375. return;
  27376. }
  27377. this._morphTargetManager = value;
  27378. this._syncGeometryWithMorphTargetManager();
  27379. },
  27380. enumerable: true,
  27381. configurable: true
  27382. });
  27383. Object.defineProperty(Mesh.prototype, "source", {
  27384. get: function () {
  27385. return this._source;
  27386. },
  27387. enumerable: true,
  27388. configurable: true
  27389. });
  27390. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27391. get: function () {
  27392. return this._unIndexed;
  27393. },
  27394. set: function (value) {
  27395. if (this._unIndexed !== value) {
  27396. this._unIndexed = value;
  27397. this._markSubMeshesAsAttributesDirty();
  27398. }
  27399. },
  27400. enumerable: true,
  27401. configurable: true
  27402. });
  27403. // Methods
  27404. /**
  27405. * Returns the string "Mesh".
  27406. */
  27407. Mesh.prototype.getClassName = function () {
  27408. return "Mesh";
  27409. };
  27410. /**
  27411. * Returns a string.
  27412. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27413. */
  27414. Mesh.prototype.toString = function (fullDetails) {
  27415. var ret = _super.prototype.toString.call(this, fullDetails);
  27416. ret += ", n vertices: " + this.getTotalVertices();
  27417. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27418. if (this.animations) {
  27419. for (var i = 0; i < this.animations.length; i++) {
  27420. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27421. }
  27422. }
  27423. if (fullDetails) {
  27424. if (this._geometry) {
  27425. var ib = this.getIndices();
  27426. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27427. if (vb && ib) {
  27428. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27429. }
  27430. }
  27431. else {
  27432. ret += ", flat shading: UNKNOWN";
  27433. }
  27434. }
  27435. return ret;
  27436. };
  27437. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27438. /**
  27439. * True if the mesh has some Levels Of Details (LOD).
  27440. * Returns a boolean.
  27441. */
  27442. get: function () {
  27443. return this._LODLevels.length > 0;
  27444. },
  27445. enumerable: true,
  27446. configurable: true
  27447. });
  27448. /**
  27449. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27450. * @returns an array of {BABYLON.MeshLODLevel}
  27451. */
  27452. Mesh.prototype.getLODLevels = function () {
  27453. return this._LODLevels;
  27454. };
  27455. Mesh.prototype._sortLODLevels = function () {
  27456. this._LODLevels.sort(function (a, b) {
  27457. if (a.distance < b.distance) {
  27458. return 1;
  27459. }
  27460. if (a.distance > b.distance) {
  27461. return -1;
  27462. }
  27463. return 0;
  27464. });
  27465. };
  27466. /**
  27467. * Add a mesh as LOD level triggered at the given distance.
  27468. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27469. * @param {number} distance The distance from the center of the object to show this level
  27470. * @param {Mesh} mesh The mesh to be added as LOD level
  27471. * @return {Mesh} This mesh (for chaining)
  27472. */
  27473. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27474. if (mesh && mesh._masterMesh) {
  27475. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27476. return this;
  27477. }
  27478. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27479. this._LODLevels.push(level);
  27480. if (mesh) {
  27481. mesh._masterMesh = this;
  27482. }
  27483. this._sortLODLevels();
  27484. return this;
  27485. };
  27486. /**
  27487. * Returns the LOD level mesh at the passed distance or null if not found.
  27488. * It is related to the method `addLODLevel(distance, mesh)`.
  27489. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27490. * Returns an object Mesh or `null`.
  27491. */
  27492. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27493. for (var index = 0; index < this._LODLevels.length; index++) {
  27494. var level = this._LODLevels[index];
  27495. if (level.distance === distance) {
  27496. return level.mesh;
  27497. }
  27498. }
  27499. return null;
  27500. };
  27501. /**
  27502. * Remove a mesh from the LOD array
  27503. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27504. * @param {Mesh} mesh The mesh to be removed.
  27505. * @return {Mesh} This mesh (for chaining)
  27506. */
  27507. Mesh.prototype.removeLODLevel = function (mesh) {
  27508. for (var index = 0; index < this._LODLevels.length; index++) {
  27509. if (this._LODLevels[index].mesh === mesh) {
  27510. this._LODLevels.splice(index, 1);
  27511. if (mesh) {
  27512. mesh._masterMesh = null;
  27513. }
  27514. }
  27515. }
  27516. this._sortLODLevels();
  27517. return this;
  27518. };
  27519. /**
  27520. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27521. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27522. */
  27523. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27524. if (!this._LODLevels || this._LODLevels.length === 0) {
  27525. return this;
  27526. }
  27527. var bSphere;
  27528. if (boundingSphere) {
  27529. bSphere = boundingSphere;
  27530. }
  27531. else {
  27532. var boundingInfo = this.getBoundingInfo();
  27533. bSphere = boundingInfo.boundingSphere;
  27534. }
  27535. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27536. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27537. if (this.onLODLevelSelection) {
  27538. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27539. }
  27540. return this;
  27541. }
  27542. for (var index = 0; index < this._LODLevels.length; index++) {
  27543. var level = this._LODLevels[index];
  27544. if (level.distance < distanceToCamera) {
  27545. if (level.mesh) {
  27546. level.mesh._preActivate();
  27547. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27548. }
  27549. if (this.onLODLevelSelection) {
  27550. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27551. }
  27552. return level.mesh;
  27553. }
  27554. }
  27555. if (this.onLODLevelSelection) {
  27556. this.onLODLevelSelection(distanceToCamera, this, this);
  27557. }
  27558. return this;
  27559. };
  27560. Object.defineProperty(Mesh.prototype, "geometry", {
  27561. /**
  27562. * Returns the mesh internal Geometry object.
  27563. */
  27564. get: function () {
  27565. return this._geometry;
  27566. },
  27567. enumerable: true,
  27568. configurable: true
  27569. });
  27570. /**
  27571. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27572. */
  27573. Mesh.prototype.getTotalVertices = function () {
  27574. if (this._geometry === null || this._geometry === undefined) {
  27575. return 0;
  27576. }
  27577. return this._geometry.getTotalVertices();
  27578. };
  27579. /**
  27580. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27581. * 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.
  27582. * You can force the copy with forceCopy === true
  27583. * Returns null if the mesh has no geometry or no vertex buffer.
  27584. * Possible `kind` values :
  27585. * - BABYLON.VertexBuffer.PositionKind
  27586. * - BABYLON.VertexBuffer.UVKind
  27587. * - BABYLON.VertexBuffer.UV2Kind
  27588. * - BABYLON.VertexBuffer.UV3Kind
  27589. * - BABYLON.VertexBuffer.UV4Kind
  27590. * - BABYLON.VertexBuffer.UV5Kind
  27591. * - BABYLON.VertexBuffer.UV6Kind
  27592. * - BABYLON.VertexBuffer.ColorKind
  27593. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27594. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27595. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27596. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27597. */
  27598. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27599. if (!this._geometry) {
  27600. return null;
  27601. }
  27602. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27603. };
  27604. /**
  27605. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27606. * Returns `null` if the mesh has no geometry.
  27607. * Possible `kind` values :
  27608. * - BABYLON.VertexBuffer.PositionKind
  27609. * - BABYLON.VertexBuffer.UVKind
  27610. * - BABYLON.VertexBuffer.UV2Kind
  27611. * - BABYLON.VertexBuffer.UV3Kind
  27612. * - BABYLON.VertexBuffer.UV4Kind
  27613. * - BABYLON.VertexBuffer.UV5Kind
  27614. * - BABYLON.VertexBuffer.UV6Kind
  27615. * - BABYLON.VertexBuffer.ColorKind
  27616. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27617. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27618. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27619. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27620. */
  27621. Mesh.prototype.getVertexBuffer = function (kind) {
  27622. if (!this._geometry) {
  27623. return null;
  27624. }
  27625. return this._geometry.getVertexBuffer(kind);
  27626. };
  27627. /**
  27628. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27629. * Possible `kind` values :
  27630. * - BABYLON.VertexBuffer.PositionKind
  27631. * - BABYLON.VertexBuffer.UVKind
  27632. * - BABYLON.VertexBuffer.UV2Kind
  27633. * - BABYLON.VertexBuffer.UV3Kind
  27634. * - BABYLON.VertexBuffer.UV4Kind
  27635. * - BABYLON.VertexBuffer.UV5Kind
  27636. * - BABYLON.VertexBuffer.UV6Kind
  27637. * - BABYLON.VertexBuffer.ColorKind
  27638. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27639. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27640. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27641. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27642. */
  27643. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27644. if (!this._geometry) {
  27645. if (this._delayInfo) {
  27646. return this._delayInfo.indexOf(kind) !== -1;
  27647. }
  27648. return false;
  27649. }
  27650. return this._geometry.isVerticesDataPresent(kind);
  27651. };
  27652. /**
  27653. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27654. * Possible `kind` values :
  27655. * - BABYLON.VertexBuffer.PositionKind
  27656. * - BABYLON.VertexBuffer.UVKind
  27657. * - BABYLON.VertexBuffer.UV2Kind
  27658. * - BABYLON.VertexBuffer.UV3Kind
  27659. * - BABYLON.VertexBuffer.UV4Kind
  27660. * - BABYLON.VertexBuffer.UV5Kind
  27661. * - BABYLON.VertexBuffer.UV6Kind
  27662. * - BABYLON.VertexBuffer.ColorKind
  27663. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27664. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27665. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27666. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27667. */
  27668. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27669. if (!this._geometry) {
  27670. if (this._delayInfo) {
  27671. return this._delayInfo.indexOf(kind) !== -1;
  27672. }
  27673. return false;
  27674. }
  27675. return this._geometry.isVertexBufferUpdatable(kind);
  27676. };
  27677. /**
  27678. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27679. * Possible `kind` values :
  27680. * - BABYLON.VertexBuffer.PositionKind
  27681. * - BABYLON.VertexBuffer.UVKind
  27682. * - BABYLON.VertexBuffer.UV2Kind
  27683. * - BABYLON.VertexBuffer.UV3Kind
  27684. * - BABYLON.VertexBuffer.UV4Kind
  27685. * - BABYLON.VertexBuffer.UV5Kind
  27686. * - BABYLON.VertexBuffer.UV6Kind
  27687. * - BABYLON.VertexBuffer.ColorKind
  27688. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27689. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27690. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27691. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27692. */
  27693. Mesh.prototype.getVerticesDataKinds = function () {
  27694. if (!this._geometry) {
  27695. var result = new Array();
  27696. if (this._delayInfo) {
  27697. this._delayInfo.forEach(function (kind, index, array) {
  27698. result.push(kind);
  27699. });
  27700. }
  27701. return result;
  27702. }
  27703. return this._geometry.getVerticesDataKinds();
  27704. };
  27705. /**
  27706. * Returns a positive integer : the total number of indices in this mesh geometry.
  27707. * Returns zero if the mesh has no geometry.
  27708. */
  27709. Mesh.prototype.getTotalIndices = function () {
  27710. if (!this._geometry) {
  27711. return 0;
  27712. }
  27713. return this._geometry.getTotalIndices();
  27714. };
  27715. /**
  27716. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27717. * 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.
  27718. * Returns an empty array if the mesh has no geometry.
  27719. */
  27720. Mesh.prototype.getIndices = function (copyWhenShared) {
  27721. if (!this._geometry) {
  27722. return [];
  27723. }
  27724. return this._geometry.getIndices(copyWhenShared);
  27725. };
  27726. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27727. get: function () {
  27728. return this._masterMesh !== null && this._masterMesh !== undefined;
  27729. },
  27730. enumerable: true,
  27731. configurable: true
  27732. });
  27733. /**
  27734. * Determine if the current mesh is ready to be rendered
  27735. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27736. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27737. * @returns true if all associated assets are ready (material, textures, shaders)
  27738. */
  27739. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27740. if (completeCheck === void 0) { completeCheck = false; }
  27741. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27742. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27743. return false;
  27744. }
  27745. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27746. return false;
  27747. }
  27748. if (!this.subMeshes || this.subMeshes.length === 0) {
  27749. return true;
  27750. }
  27751. if (!completeCheck) {
  27752. return true;
  27753. }
  27754. var engine = this.getEngine();
  27755. var scene = this.getScene();
  27756. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27757. this.computeWorldMatrix();
  27758. var mat = this.material || scene.defaultMaterial;
  27759. if (mat) {
  27760. if (mat.storeEffectOnSubMeshes) {
  27761. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27762. var subMesh = _a[_i];
  27763. var effectiveMaterial = subMesh.getMaterial();
  27764. if (effectiveMaterial) {
  27765. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27766. return false;
  27767. }
  27768. }
  27769. }
  27770. }
  27771. else {
  27772. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27773. return false;
  27774. }
  27775. }
  27776. }
  27777. // Shadows
  27778. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27779. var light = _c[_b];
  27780. var generator = light.getShadowGenerator();
  27781. if (generator) {
  27782. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27783. var subMesh = _e[_d];
  27784. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27785. return false;
  27786. }
  27787. }
  27788. }
  27789. }
  27790. // LOD
  27791. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27792. var lod = _g[_f];
  27793. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27794. return false;
  27795. }
  27796. }
  27797. return true;
  27798. };
  27799. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27800. /**
  27801. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27802. * This property is pertinent only for updatable parametric shapes.
  27803. */
  27804. get: function () {
  27805. return this._areNormalsFrozen;
  27806. },
  27807. enumerable: true,
  27808. configurable: true
  27809. });
  27810. /**
  27811. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27812. * It has no effect at all on other shapes.
  27813. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27814. * Returns the Mesh.
  27815. */
  27816. Mesh.prototype.freezeNormals = function () {
  27817. this._areNormalsFrozen = true;
  27818. return this;
  27819. };
  27820. /**
  27821. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27822. * It has no effect at all on other shapes.
  27823. * It reactivates the mesh normals computation if it was previously frozen.
  27824. * Returns the Mesh.
  27825. */
  27826. Mesh.prototype.unfreezeNormals = function () {
  27827. this._areNormalsFrozen = false;
  27828. return this;
  27829. };
  27830. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27831. /**
  27832. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27833. */
  27834. set: function (count) {
  27835. this._overridenInstanceCount = count;
  27836. },
  27837. enumerable: true,
  27838. configurable: true
  27839. });
  27840. // Methods
  27841. Mesh.prototype._preActivate = function () {
  27842. var sceneRenderId = this.getScene().getRenderId();
  27843. if (this._preActivateId === sceneRenderId) {
  27844. return this;
  27845. }
  27846. this._preActivateId = sceneRenderId;
  27847. this._visibleInstances = null;
  27848. return this;
  27849. };
  27850. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27851. if (this._visibleInstances) {
  27852. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27853. }
  27854. return this;
  27855. };
  27856. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27857. if (!this._visibleInstances) {
  27858. this._visibleInstances = {};
  27859. this._visibleInstances.defaultRenderId = renderId;
  27860. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27861. }
  27862. if (!this._visibleInstances[renderId]) {
  27863. this._visibleInstances[renderId] = new Array();
  27864. }
  27865. this._visibleInstances[renderId].push(instance);
  27866. return this;
  27867. };
  27868. /**
  27869. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27870. * This means the mesh underlying bounding box and sphere are recomputed.
  27871. * Returns the Mesh.
  27872. */
  27873. Mesh.prototype.refreshBoundingInfo = function () {
  27874. return this._refreshBoundingInfo(false);
  27875. };
  27876. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27877. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27878. return this;
  27879. }
  27880. var data = this._getPositionData(applySkeleton);
  27881. if (data) {
  27882. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27883. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27884. }
  27885. if (this.subMeshes) {
  27886. for (var index = 0; index < this.subMeshes.length; index++) {
  27887. this.subMeshes[index].refreshBoundingInfo();
  27888. }
  27889. }
  27890. this._updateBoundingInfo();
  27891. return this;
  27892. };
  27893. Mesh.prototype._getPositionData = function (applySkeleton) {
  27894. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27895. if (data && applySkeleton && this.skeleton) {
  27896. data = BABYLON.Tools.Slice(data);
  27897. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27898. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27899. if (matricesWeightsData && matricesIndicesData) {
  27900. var needExtras = this.numBoneInfluencers > 4;
  27901. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27902. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27903. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27904. var tempVector = BABYLON.Tmp.Vector3[0];
  27905. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27906. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27907. var matWeightIdx = 0;
  27908. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27909. finalMatrix.reset();
  27910. var inf;
  27911. var weight;
  27912. for (inf = 0; inf < 4; inf++) {
  27913. weight = matricesWeightsData[matWeightIdx + inf];
  27914. if (weight <= 0)
  27915. break;
  27916. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27917. finalMatrix.addToSelf(tempMatrix);
  27918. }
  27919. if (needExtras) {
  27920. for (inf = 0; inf < 4; inf++) {
  27921. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27922. if (weight <= 0)
  27923. break;
  27924. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27925. finalMatrix.addToSelf(tempMatrix);
  27926. }
  27927. }
  27928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27929. tempVector.toArray(data, index);
  27930. }
  27931. }
  27932. }
  27933. return data;
  27934. };
  27935. Mesh.prototype._createGlobalSubMesh = function (force) {
  27936. var totalVertices = this.getTotalVertices();
  27937. if (!totalVertices || !this.getIndices()) {
  27938. return null;
  27939. }
  27940. // Check if we need to recreate the submeshes
  27941. if (this.subMeshes && this.subMeshes.length > 0) {
  27942. var ib = this.getIndices();
  27943. if (!ib) {
  27944. return null;
  27945. }
  27946. var totalIndices = ib.length;
  27947. var needToRecreate = false;
  27948. if (force) {
  27949. needToRecreate = true;
  27950. }
  27951. else {
  27952. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27953. var submesh = _a[_i];
  27954. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27955. needToRecreate = true;
  27956. break;
  27957. }
  27958. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27959. needToRecreate = true;
  27960. break;
  27961. }
  27962. }
  27963. }
  27964. if (!needToRecreate) {
  27965. return this.subMeshes[0];
  27966. }
  27967. }
  27968. this.releaseSubMeshes();
  27969. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27970. };
  27971. Mesh.prototype.subdivide = function (count) {
  27972. if (count < 1) {
  27973. return;
  27974. }
  27975. var totalIndices = this.getTotalIndices();
  27976. var subdivisionSize = (totalIndices / count) | 0;
  27977. var offset = 0;
  27978. // Ensure that subdivisionSize is a multiple of 3
  27979. while (subdivisionSize % 3 !== 0) {
  27980. subdivisionSize++;
  27981. }
  27982. this.releaseSubMeshes();
  27983. for (var index = 0; index < count; index++) {
  27984. if (offset >= totalIndices) {
  27985. break;
  27986. }
  27987. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27988. offset += subdivisionSize;
  27989. }
  27990. this.synchronizeInstances();
  27991. };
  27992. /**
  27993. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27994. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27995. * The `data` are either a numeric array either a Float32Array.
  27996. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27997. * 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).
  27998. * Note that a new underlying VertexBuffer object is created each call.
  27999. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28000. *
  28001. * Possible `kind` values :
  28002. * - BABYLON.VertexBuffer.PositionKind
  28003. * - BABYLON.VertexBuffer.UVKind
  28004. * - BABYLON.VertexBuffer.UV2Kind
  28005. * - BABYLON.VertexBuffer.UV3Kind
  28006. * - BABYLON.VertexBuffer.UV4Kind
  28007. * - BABYLON.VertexBuffer.UV5Kind
  28008. * - BABYLON.VertexBuffer.UV6Kind
  28009. * - BABYLON.VertexBuffer.ColorKind
  28010. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28011. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28012. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28013. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28014. *
  28015. * Returns the Mesh.
  28016. */
  28017. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28018. if (updatable === void 0) { updatable = false; }
  28019. if (!this._geometry) {
  28020. var vertexData = new BABYLON.VertexData();
  28021. vertexData.set(data, kind);
  28022. var scene = this.getScene();
  28023. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28024. }
  28025. else {
  28026. this._geometry.setVerticesData(kind, data, updatable, stride);
  28027. }
  28028. return this;
  28029. };
  28030. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28031. if (updatable === void 0) { updatable = true; }
  28032. var vb = this.getVertexBuffer(kind);
  28033. if (!vb || vb.isUpdatable() === updatable) {
  28034. return;
  28035. }
  28036. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28037. };
  28038. /**
  28039. * Sets the mesh VertexBuffer.
  28040. * Returns the Mesh.
  28041. */
  28042. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28043. if (!this._geometry) {
  28044. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28045. }
  28046. this._geometry.setVerticesBuffer(buffer);
  28047. return this;
  28048. };
  28049. /**
  28050. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28051. * If the mesh has no geometry, it is simply returned as it is.
  28052. * The `data` are either a numeric array either a Float32Array.
  28053. * No new underlying VertexBuffer object is created.
  28054. * 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.
  28055. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28056. *
  28057. * Possible `kind` values :
  28058. * - BABYLON.VertexBuffer.PositionKind
  28059. * - BABYLON.VertexBuffer.UVKind
  28060. * - BABYLON.VertexBuffer.UV2Kind
  28061. * - BABYLON.VertexBuffer.UV3Kind
  28062. * - BABYLON.VertexBuffer.UV4Kind
  28063. * - BABYLON.VertexBuffer.UV5Kind
  28064. * - BABYLON.VertexBuffer.UV6Kind
  28065. * - BABYLON.VertexBuffer.ColorKind
  28066. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28067. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28068. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28069. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28070. *
  28071. * Returns the Mesh.
  28072. */
  28073. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28074. if (!this._geometry) {
  28075. return this;
  28076. }
  28077. if (!makeItUnique) {
  28078. this._geometry.updateVerticesData(kind, data, updateExtends);
  28079. }
  28080. else {
  28081. this.makeGeometryUnique();
  28082. this.updateVerticesData(kind, data, updateExtends, false);
  28083. }
  28084. return this;
  28085. };
  28086. /**
  28087. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28088. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28089. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28090. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28091. * Returns the Mesh.
  28092. */
  28093. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28094. if (computeNormals === void 0) { computeNormals = true; }
  28095. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28096. if (!positions) {
  28097. return this;
  28098. }
  28099. positionFunction(positions);
  28100. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28101. if (computeNormals) {
  28102. var indices = this.getIndices();
  28103. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28104. if (!normals) {
  28105. return this;
  28106. }
  28107. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28108. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28109. }
  28110. return this;
  28111. };
  28112. /**
  28113. * Creates a un-shared specific occurence of the geometry for the mesh.
  28114. * Returns the Mesh.
  28115. */
  28116. Mesh.prototype.makeGeometryUnique = function () {
  28117. if (!this._geometry) {
  28118. return this;
  28119. }
  28120. var oldGeometry = this._geometry;
  28121. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28122. oldGeometry.releaseForMesh(this, true);
  28123. geometry.applyToMesh(this);
  28124. return this;
  28125. };
  28126. /**
  28127. * Sets the mesh indices.
  28128. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28129. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28130. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28131. * This method creates a new index buffer each call.
  28132. * Returns the Mesh.
  28133. */
  28134. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28135. if (totalVertices === void 0) { totalVertices = null; }
  28136. if (updatable === void 0) { updatable = false; }
  28137. if (!this._geometry) {
  28138. var vertexData = new BABYLON.VertexData();
  28139. vertexData.indices = indices;
  28140. var scene = this.getScene();
  28141. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28142. }
  28143. else {
  28144. this._geometry.setIndices(indices, totalVertices, updatable);
  28145. }
  28146. return this;
  28147. };
  28148. /**
  28149. * Update the current index buffer
  28150. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28151. * Returns the Mesh.
  28152. */
  28153. Mesh.prototype.updateIndices = function (indices, offset) {
  28154. if (!this._geometry) {
  28155. return this;
  28156. }
  28157. this._geometry.updateIndices(indices, offset);
  28158. return this;
  28159. };
  28160. /**
  28161. * Invert the geometry to move from a right handed system to a left handed one.
  28162. * Returns the Mesh.
  28163. */
  28164. Mesh.prototype.toLeftHanded = function () {
  28165. if (!this._geometry) {
  28166. return this;
  28167. }
  28168. this._geometry.toLeftHanded();
  28169. return this;
  28170. };
  28171. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28172. if (!this._geometry) {
  28173. return this;
  28174. }
  28175. var engine = this.getScene().getEngine();
  28176. // Wireframe
  28177. var indexToBind;
  28178. if (this._unIndexed) {
  28179. indexToBind = null;
  28180. }
  28181. else {
  28182. switch (fillMode) {
  28183. case BABYLON.Material.PointFillMode:
  28184. indexToBind = null;
  28185. break;
  28186. case BABYLON.Material.WireFrameFillMode:
  28187. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28188. break;
  28189. default:
  28190. case BABYLON.Material.TriangleFillMode:
  28191. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28192. break;
  28193. }
  28194. }
  28195. // VBOs
  28196. this._geometry._bind(effect, indexToBind);
  28197. return this;
  28198. };
  28199. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28200. if (alternate === void 0) { alternate = false; }
  28201. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28202. return this;
  28203. }
  28204. this.onBeforeDrawObservable.notifyObservers(this);
  28205. var scene = this.getScene();
  28206. var engine = scene.getEngine();
  28207. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28208. // or triangles as points
  28209. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28210. }
  28211. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28212. // Triangles as wireframe
  28213. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28214. }
  28215. else {
  28216. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28217. }
  28218. if (scene._isAlternateRenderingEnabled && !alternate) {
  28219. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28220. if (!effect || !scene.activeCamera) {
  28221. return this;
  28222. }
  28223. scene._switchToAlternateCameraConfiguration(true);
  28224. this._effectiveMaterial.bindView(effect);
  28225. this._effectiveMaterial.bindViewProjection(effect);
  28226. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28227. this._draw(subMesh, fillMode, instancesCount, true);
  28228. engine.setViewport(scene.activeCamera.viewport);
  28229. scene._switchToAlternateCameraConfiguration(false);
  28230. this._effectiveMaterial.bindView(effect);
  28231. this._effectiveMaterial.bindViewProjection(effect);
  28232. }
  28233. return this;
  28234. };
  28235. /**
  28236. * Registers for this mesh a javascript function called just before the rendering process.
  28237. * This function is passed the current mesh.
  28238. * Return the Mesh.
  28239. */
  28240. Mesh.prototype.registerBeforeRender = function (func) {
  28241. this.onBeforeRenderObservable.add(func);
  28242. return this;
  28243. };
  28244. /**
  28245. * Disposes a previously registered javascript function called before the rendering.
  28246. * This function is passed the current mesh.
  28247. * Returns the Mesh.
  28248. */
  28249. Mesh.prototype.unregisterBeforeRender = function (func) {
  28250. this.onBeforeRenderObservable.removeCallback(func);
  28251. return this;
  28252. };
  28253. /**
  28254. * Registers for this mesh a javascript function called just after the rendering is complete.
  28255. * This function is passed the current mesh.
  28256. * Returns the Mesh.
  28257. */
  28258. Mesh.prototype.registerAfterRender = function (func) {
  28259. this.onAfterRenderObservable.add(func);
  28260. return this;
  28261. };
  28262. /**
  28263. * Disposes a previously registered javascript function called after the rendering.
  28264. * This function is passed the current mesh.
  28265. * Return the Mesh.
  28266. */
  28267. Mesh.prototype.unregisterAfterRender = function (func) {
  28268. this.onAfterRenderObservable.removeCallback(func);
  28269. return this;
  28270. };
  28271. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28272. var scene = this.getScene();
  28273. this._batchCache.mustReturn = false;
  28274. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28275. this._batchCache.visibleInstances[subMeshId] = null;
  28276. if (this._visibleInstances) {
  28277. var currentRenderId = scene.getRenderId();
  28278. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28279. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28280. var selfRenderId = this._renderId;
  28281. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28282. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28283. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28284. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28285. }
  28286. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28287. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28288. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28289. this._batchCache.mustReturn = true;
  28290. return this._batchCache;
  28291. }
  28292. if (currentRenderId !== selfRenderId) {
  28293. this._batchCache.renderSelf[subMeshId] = false;
  28294. }
  28295. }
  28296. this._renderIdForInstances[subMeshId] = currentRenderId;
  28297. }
  28298. return this._batchCache;
  28299. };
  28300. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28301. var visibleInstances = batch.visibleInstances[subMesh._id];
  28302. if (!visibleInstances) {
  28303. return this;
  28304. }
  28305. var matricesCount = visibleInstances.length + 1;
  28306. var bufferSize = matricesCount * 16 * 4;
  28307. var currentInstancesBufferSize = this._instancesBufferSize;
  28308. var instancesBuffer = this._instancesBuffer;
  28309. while (this._instancesBufferSize < bufferSize) {
  28310. this._instancesBufferSize *= 2;
  28311. }
  28312. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28313. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28314. }
  28315. var offset = 0;
  28316. var instancesCount = 0;
  28317. var world = this.getWorldMatrix();
  28318. if (batch.renderSelf[subMesh._id]) {
  28319. world.copyToArray(this._instancesData, offset);
  28320. offset += 16;
  28321. instancesCount++;
  28322. }
  28323. if (visibleInstances) {
  28324. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28325. var instance = visibleInstances[instanceIndex];
  28326. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28327. offset += 16;
  28328. instancesCount++;
  28329. }
  28330. }
  28331. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28332. if (instancesBuffer) {
  28333. instancesBuffer.dispose();
  28334. }
  28335. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28336. this._instancesBuffer = instancesBuffer;
  28337. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28338. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28339. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28340. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28341. }
  28342. else {
  28343. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28344. }
  28345. this._bind(subMesh, effect, fillMode);
  28346. this._draw(subMesh, fillMode, instancesCount);
  28347. engine.unbindInstanceAttributes();
  28348. return this;
  28349. };
  28350. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28351. var scene = this.getScene();
  28352. var engine = scene.getEngine();
  28353. if (hardwareInstancedRendering) {
  28354. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28355. }
  28356. else {
  28357. if (batch.renderSelf[subMesh._id]) {
  28358. // Draw
  28359. if (onBeforeDraw) {
  28360. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28361. }
  28362. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28363. }
  28364. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28365. if (visibleInstancesForSubMesh) {
  28366. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28367. var instance = visibleInstancesForSubMesh[instanceIndex];
  28368. // World
  28369. var world = instance.getWorldMatrix();
  28370. if (onBeforeDraw) {
  28371. onBeforeDraw(true, world, effectiveMaterial);
  28372. }
  28373. // Draw
  28374. this._draw(subMesh, fillMode);
  28375. }
  28376. }
  28377. }
  28378. return this;
  28379. };
  28380. /**
  28381. * Triggers the draw call for the mesh.
  28382. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28383. * Returns the Mesh.
  28384. */
  28385. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28386. this.checkOcclusionQuery();
  28387. if (this._isOccluded) {
  28388. return this;
  28389. }
  28390. var scene = this.getScene();
  28391. // Managing instances
  28392. var batch = this._getInstancesRenderList(subMesh._id);
  28393. if (batch.mustReturn) {
  28394. return this;
  28395. }
  28396. // Checking geometry state
  28397. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28398. return this;
  28399. }
  28400. this.onBeforeRenderObservable.notifyObservers(this);
  28401. var engine = scene.getEngine();
  28402. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28403. // Material
  28404. var material = subMesh.getMaterial();
  28405. if (!material) {
  28406. return this;
  28407. }
  28408. this._effectiveMaterial = material;
  28409. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28410. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28411. return this;
  28412. }
  28413. }
  28414. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28415. return this;
  28416. }
  28417. // Alpha mode
  28418. if (enableAlphaMode) {
  28419. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28420. }
  28421. // Outline - step 1
  28422. var savedDepthWrite = engine.getDepthWrite();
  28423. if (this.renderOutline) {
  28424. engine.setDepthWrite(false);
  28425. scene.getOutlineRenderer().render(subMesh, batch);
  28426. engine.setDepthWrite(savedDepthWrite);
  28427. }
  28428. var effect;
  28429. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28430. effect = subMesh.effect;
  28431. }
  28432. else {
  28433. effect = this._effectiveMaterial.getEffect();
  28434. }
  28435. if (!effect) {
  28436. return this;
  28437. }
  28438. var sideOrientation = this.overrideMaterialSideOrientation;
  28439. if (sideOrientation == null) {
  28440. sideOrientation = this._effectiveMaterial.sideOrientation;
  28441. if (this._getWorldMatrixDeterminant() < 0) {
  28442. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28443. }
  28444. }
  28445. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28446. if (this._effectiveMaterial.forceDepthWrite) {
  28447. engine.setDepthWrite(true);
  28448. }
  28449. // Bind
  28450. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28451. if (!hardwareInstancedRendering) {
  28452. this._bind(subMesh, effect, fillMode);
  28453. }
  28454. var world = this.getWorldMatrix();
  28455. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28456. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28457. }
  28458. else {
  28459. this._effectiveMaterial.bind(world, this);
  28460. }
  28461. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28462. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28463. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28464. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28465. }
  28466. // Draw
  28467. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28468. // Unbind
  28469. this._effectiveMaterial.unbind();
  28470. // Outline - step 2
  28471. if (this.renderOutline && savedDepthWrite) {
  28472. engine.setDepthWrite(true);
  28473. engine.setColorWrite(false);
  28474. scene.getOutlineRenderer().render(subMesh, batch);
  28475. engine.setColorWrite(true);
  28476. }
  28477. // Overlay
  28478. if (this.renderOverlay) {
  28479. var currentMode = engine.getAlphaMode();
  28480. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28481. scene.getOutlineRenderer().render(subMesh, batch, true);
  28482. engine.setAlphaMode(currentMode);
  28483. }
  28484. this.onAfterRenderObservable.notifyObservers(this);
  28485. return this;
  28486. };
  28487. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28488. if (isInstance && effectiveMaterial) {
  28489. effectiveMaterial.bindOnlyWorldMatrix(world);
  28490. }
  28491. };
  28492. /**
  28493. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28494. */
  28495. Mesh.prototype.getEmittedParticleSystems = function () {
  28496. var results = new Array();
  28497. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28498. var particleSystem = this.getScene().particleSystems[index];
  28499. if (particleSystem.emitter === this) {
  28500. results.push(particleSystem);
  28501. }
  28502. }
  28503. return results;
  28504. };
  28505. /**
  28506. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28507. */
  28508. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28509. var results = new Array();
  28510. var descendants = this.getDescendants();
  28511. descendants.push(this);
  28512. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28513. var particleSystem = this.getScene().particleSystems[index];
  28514. var emitter = particleSystem.emitter;
  28515. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28516. results.push(particleSystem);
  28517. }
  28518. }
  28519. return results;
  28520. };
  28521. Mesh.prototype._checkDelayState = function () {
  28522. var scene = this.getScene();
  28523. if (this._geometry) {
  28524. this._geometry.load(scene);
  28525. }
  28526. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28527. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28528. this._queueLoad(scene);
  28529. }
  28530. return this;
  28531. };
  28532. Mesh.prototype._queueLoad = function (scene) {
  28533. var _this = this;
  28534. scene._addPendingData(this);
  28535. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28536. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28537. if (data instanceof ArrayBuffer) {
  28538. _this._delayLoadingFunction(data, _this);
  28539. }
  28540. else {
  28541. _this._delayLoadingFunction(JSON.parse(data), _this);
  28542. }
  28543. _this.instances.forEach(function (instance) {
  28544. instance._syncSubMeshes();
  28545. });
  28546. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28547. scene._removePendingData(_this);
  28548. }, function () { }, scene.database, getBinaryData);
  28549. return this;
  28550. };
  28551. /**
  28552. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28553. */
  28554. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28555. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28556. return false;
  28557. }
  28558. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28559. return false;
  28560. }
  28561. this._checkDelayState();
  28562. return true;
  28563. };
  28564. /**
  28565. * Sets the mesh material by the material or multiMaterial `id` property.
  28566. * The material `id` is a string identifying the material or the multiMaterial.
  28567. * This method returns the Mesh.
  28568. */
  28569. Mesh.prototype.setMaterialByID = function (id) {
  28570. var materials = this.getScene().materials;
  28571. var index;
  28572. for (index = materials.length - 1; index > -1; index--) {
  28573. if (materials[index].id === id) {
  28574. this.material = materials[index];
  28575. return this;
  28576. }
  28577. }
  28578. // Multi
  28579. var multiMaterials = this.getScene().multiMaterials;
  28580. for (index = multiMaterials.length - 1; index > -1; index--) {
  28581. if (multiMaterials[index].id === id) {
  28582. this.material = multiMaterials[index];
  28583. return this;
  28584. }
  28585. }
  28586. return this;
  28587. };
  28588. /**
  28589. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28590. */
  28591. Mesh.prototype.getAnimatables = function () {
  28592. var results = new Array();
  28593. if (this.material) {
  28594. results.push(this.material);
  28595. }
  28596. if (this.skeleton) {
  28597. results.push(this.skeleton);
  28598. }
  28599. return results;
  28600. };
  28601. /**
  28602. * Modifies the mesh geometry according to the passed transformation matrix.
  28603. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28604. * The mesh normals are modified accordingly the same transformation.
  28605. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28606. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28607. * Returns the Mesh.
  28608. */
  28609. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28610. // Position
  28611. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28612. return this;
  28613. }
  28614. var submeshes = this.subMeshes.splice(0);
  28615. this._resetPointsArrayCache();
  28616. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28617. var temp = new Array();
  28618. var index;
  28619. for (index = 0; index < data.length; index += 3) {
  28620. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28621. }
  28622. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28623. // Normals
  28624. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28625. return this;
  28626. }
  28627. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28628. temp = [];
  28629. for (index = 0; index < data.length; index += 3) {
  28630. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28631. }
  28632. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28633. // flip faces?
  28634. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28635. this.flipFaces();
  28636. }
  28637. // Restore submeshes
  28638. this.releaseSubMeshes();
  28639. this.subMeshes = submeshes;
  28640. return this;
  28641. };
  28642. /**
  28643. * Modifies the mesh geometry according to its own current World Matrix.
  28644. * The mesh World Matrix is then reset.
  28645. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28646. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28647. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28648. * Returns the Mesh.
  28649. */
  28650. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28651. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28652. this.scaling.copyFromFloats(1, 1, 1);
  28653. this.position.copyFromFloats(0, 0, 0);
  28654. this.rotation.copyFromFloats(0, 0, 0);
  28655. //only if quaternion is already set
  28656. if (this.rotationQuaternion) {
  28657. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28658. }
  28659. this._worldMatrix = BABYLON.Matrix.Identity();
  28660. return this;
  28661. };
  28662. Object.defineProperty(Mesh.prototype, "_positions", {
  28663. // Cache
  28664. get: function () {
  28665. if (this._geometry) {
  28666. return this._geometry._positions;
  28667. }
  28668. return null;
  28669. },
  28670. enumerable: true,
  28671. configurable: true
  28672. });
  28673. Mesh.prototype._resetPointsArrayCache = function () {
  28674. if (this._geometry) {
  28675. this._geometry._resetPointsArrayCache();
  28676. }
  28677. return this;
  28678. };
  28679. Mesh.prototype._generatePointsArray = function () {
  28680. if (this._geometry) {
  28681. return this._geometry._generatePointsArray();
  28682. }
  28683. return false;
  28684. };
  28685. /**
  28686. * Returns a new Mesh object generated from the current mesh properties.
  28687. * This method must not get confused with createInstance().
  28688. * The parameter `name` is a string, the name given to the new mesh.
  28689. * The optional parameter `newParent` can be any Node object (default `null`).
  28690. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28691. * 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.
  28692. */
  28693. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28694. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28695. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28696. };
  28697. /**
  28698. * Disposes the Mesh.
  28699. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28700. * Returns nothing.
  28701. */
  28702. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28703. var _this = this;
  28704. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28705. this.morphTargetManager = null;
  28706. if (this._geometry) {
  28707. this._geometry.releaseForMesh(this, true);
  28708. }
  28709. // Sources
  28710. var meshes = this.getScene().meshes;
  28711. meshes.forEach(function (abstractMesh) {
  28712. var mesh = abstractMesh;
  28713. if (mesh._source && mesh._source === _this) {
  28714. mesh._source = null;
  28715. }
  28716. });
  28717. this._source = null;
  28718. // Instances
  28719. if (this._instancesBuffer) {
  28720. this._instancesBuffer.dispose();
  28721. this._instancesBuffer = null;
  28722. }
  28723. while (this.instances.length) {
  28724. this.instances[0].dispose();
  28725. }
  28726. // Effect layers.
  28727. var effectLayers = this.getScene().effectLayers;
  28728. for (var i = 0; i < effectLayers.length; i++) {
  28729. var effectLayer = effectLayers[i];
  28730. if (effectLayer) {
  28731. effectLayer._disposeMesh(this);
  28732. }
  28733. }
  28734. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28735. };
  28736. /**
  28737. * Modifies the mesh geometry according to a displacement map.
  28738. * 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.
  28739. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28740. * This method returns nothing.
  28741. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28742. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28743. * 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.
  28744. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28745. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28746. *
  28747. * Returns the Mesh.
  28748. */
  28749. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28750. var _this = this;
  28751. var scene = this.getScene();
  28752. var onload = function (img) {
  28753. // Getting height map data
  28754. var canvas = document.createElement("canvas");
  28755. var context = canvas.getContext("2d");
  28756. var heightMapWidth = img.width;
  28757. var heightMapHeight = img.height;
  28758. canvas.width = heightMapWidth;
  28759. canvas.height = heightMapHeight;
  28760. context.drawImage(img, 0, 0);
  28761. // Create VertexData from map data
  28762. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28763. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28764. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28765. //execute success callback, if set
  28766. if (onSuccess) {
  28767. onSuccess(_this);
  28768. }
  28769. };
  28770. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28771. return this;
  28772. };
  28773. /**
  28774. * Modifies the mesh geometry according to a displacementMap buffer.
  28775. * 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.
  28776. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28777. * This method returns nothing.
  28778. * 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.
  28779. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28780. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28781. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28782. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28783. *
  28784. * Returns the Mesh.
  28785. */
  28786. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28787. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28788. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28789. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28790. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28791. return this;
  28792. }
  28793. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28794. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28795. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28796. var position = BABYLON.Vector3.Zero();
  28797. var normal = BABYLON.Vector3.Zero();
  28798. var uv = BABYLON.Vector2.Zero();
  28799. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28800. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28801. for (var index = 0; index < positions.length; index += 3) {
  28802. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28803. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28804. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28805. // Compute height
  28806. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28807. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28808. var pos = (u + v * heightMapWidth) * 4;
  28809. var r = buffer[pos] / 255.0;
  28810. var g = buffer[pos + 1] / 255.0;
  28811. var b = buffer[pos + 2] / 255.0;
  28812. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28813. normal.normalize();
  28814. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28815. position = position.add(normal);
  28816. position.toArray(positions, index);
  28817. }
  28818. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28819. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28820. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28821. return this;
  28822. };
  28823. /**
  28824. * Modify the mesh to get a flat shading rendering.
  28825. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28826. * This method returns the Mesh.
  28827. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28828. */
  28829. Mesh.prototype.convertToFlatShadedMesh = function () {
  28830. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28831. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28832. var kinds = this.getVerticesDataKinds();
  28833. var vbs = {};
  28834. var data = {};
  28835. var newdata = {};
  28836. var updatableNormals = false;
  28837. var kindIndex;
  28838. var kind;
  28839. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28840. kind = kinds[kindIndex];
  28841. var vertexBuffer = this.getVertexBuffer(kind);
  28842. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28843. updatableNormals = vertexBuffer.isUpdatable();
  28844. kinds.splice(kindIndex, 1);
  28845. kindIndex--;
  28846. continue;
  28847. }
  28848. vbs[kind] = vertexBuffer;
  28849. data[kind] = vbs[kind].getData();
  28850. newdata[kind] = [];
  28851. }
  28852. // Save previous submeshes
  28853. var previousSubmeshes = this.subMeshes.slice(0);
  28854. var indices = this.getIndices();
  28855. var totalIndices = this.getTotalIndices();
  28856. // Generating unique vertices per face
  28857. var index;
  28858. for (index = 0; index < totalIndices; index++) {
  28859. var vertexIndex = indices[index];
  28860. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28861. kind = kinds[kindIndex];
  28862. var stride = vbs[kind].getStrideSize();
  28863. for (var offset = 0; offset < stride; offset++) {
  28864. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28865. }
  28866. }
  28867. }
  28868. // Updating faces & normal
  28869. var normals = [];
  28870. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28871. for (index = 0; index < totalIndices; index += 3) {
  28872. indices[index] = index;
  28873. indices[index + 1] = index + 1;
  28874. indices[index + 2] = index + 2;
  28875. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28876. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28877. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28878. var p1p2 = p1.subtract(p2);
  28879. var p3p2 = p3.subtract(p2);
  28880. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28881. // Store same normals for every vertex
  28882. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28883. normals.push(normal.x);
  28884. normals.push(normal.y);
  28885. normals.push(normal.z);
  28886. }
  28887. }
  28888. this.setIndices(indices);
  28889. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28890. // Updating vertex buffers
  28891. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28892. kind = kinds[kindIndex];
  28893. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28894. }
  28895. // Updating submeshes
  28896. this.releaseSubMeshes();
  28897. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28898. var previousOne = previousSubmeshes[submeshIndex];
  28899. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28900. }
  28901. this.synchronizeInstances();
  28902. return this;
  28903. };
  28904. /**
  28905. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28906. * In other words, more vertices, no more indices and a single bigger VBO.
  28907. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28908. * Returns the Mesh.
  28909. */
  28910. Mesh.prototype.convertToUnIndexedMesh = function () {
  28911. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28912. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28913. var kinds = this.getVerticesDataKinds();
  28914. var vbs = {};
  28915. var data = {};
  28916. var newdata = {};
  28917. var kindIndex;
  28918. var kind;
  28919. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28920. kind = kinds[kindIndex];
  28921. var vertexBuffer = this.getVertexBuffer(kind);
  28922. vbs[kind] = vertexBuffer;
  28923. data[kind] = vbs[kind].getData();
  28924. newdata[kind] = [];
  28925. }
  28926. // Save previous submeshes
  28927. var previousSubmeshes = this.subMeshes.slice(0);
  28928. var indices = this.getIndices();
  28929. var totalIndices = this.getTotalIndices();
  28930. // Generating unique vertices per face
  28931. var index;
  28932. for (index = 0; index < totalIndices; index++) {
  28933. var vertexIndex = indices[index];
  28934. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28935. kind = kinds[kindIndex];
  28936. var stride = vbs[kind].getStrideSize();
  28937. for (var offset = 0; offset < stride; offset++) {
  28938. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28939. }
  28940. }
  28941. }
  28942. // Updating indices
  28943. for (index = 0; index < totalIndices; index += 3) {
  28944. indices[index] = index;
  28945. indices[index + 1] = index + 1;
  28946. indices[index + 2] = index + 2;
  28947. }
  28948. this.setIndices(indices);
  28949. // Updating vertex buffers
  28950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28951. kind = kinds[kindIndex];
  28952. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28953. }
  28954. // Updating submeshes
  28955. this.releaseSubMeshes();
  28956. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28957. var previousOne = previousSubmeshes[submeshIndex];
  28958. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28959. }
  28960. this._unIndexed = true;
  28961. this.synchronizeInstances();
  28962. return this;
  28963. };
  28964. /**
  28965. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28966. * This method returns the Mesh.
  28967. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28968. */
  28969. Mesh.prototype.flipFaces = function (flipNormals) {
  28970. if (flipNormals === void 0) { flipNormals = false; }
  28971. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28972. var i;
  28973. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28974. for (i = 0; i < vertex_data.normals.length; i++) {
  28975. vertex_data.normals[i] *= -1;
  28976. }
  28977. }
  28978. if (vertex_data.indices) {
  28979. var temp;
  28980. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28981. // reassign indices
  28982. temp = vertex_data.indices[i + 1];
  28983. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28984. vertex_data.indices[i + 2] = temp;
  28985. }
  28986. }
  28987. vertex_data.applyToMesh(this);
  28988. return this;
  28989. };
  28990. // Instances
  28991. /**
  28992. * Creates a new InstancedMesh object from the mesh model.
  28993. * An instance shares the same properties and the same material than its model.
  28994. * Only these properties of each instance can then be set individually :
  28995. * - position
  28996. * - rotation
  28997. * - rotationQuaternion
  28998. * - setPivotMatrix
  28999. * - scaling
  29000. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29001. * Warning : this method is not supported for Line mesh and LineSystem
  29002. */
  29003. Mesh.prototype.createInstance = function (name) {
  29004. return new BABYLON.InstancedMesh(name, this);
  29005. };
  29006. /**
  29007. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29008. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29009. * This method returns the Mesh.
  29010. */
  29011. Mesh.prototype.synchronizeInstances = function () {
  29012. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29013. var instance = this.instances[instanceIndex];
  29014. instance._syncSubMeshes();
  29015. }
  29016. return this;
  29017. };
  29018. /**
  29019. * Simplify the mesh according to the given array of settings.
  29020. * Function will return immediately and will simplify async. It returns the Mesh.
  29021. * @param settings a collection of simplification settings.
  29022. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29023. * @param type the type of simplification to run.
  29024. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29025. */
  29026. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29027. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29028. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29029. this.getScene().simplificationQueue.addTask({
  29030. settings: settings,
  29031. parallelProcessing: parallelProcessing,
  29032. mesh: this,
  29033. simplificationType: simplificationType,
  29034. successCallback: successCallback
  29035. });
  29036. return this;
  29037. };
  29038. /**
  29039. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29040. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29041. * This should be used together with the simplification to avoid disappearing triangles.
  29042. * Returns the Mesh.
  29043. * @param successCallback an optional success callback to be called after the optimization finished.
  29044. */
  29045. Mesh.prototype.optimizeIndices = function (successCallback) {
  29046. var _this = this;
  29047. var indices = this.getIndices();
  29048. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29049. if (!positions || !indices) {
  29050. return this;
  29051. }
  29052. var vectorPositions = new Array();
  29053. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29054. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29055. }
  29056. var dupes = new Array();
  29057. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29058. var realPos = vectorPositions.length - 1 - iteration;
  29059. var testedPosition = vectorPositions[realPos];
  29060. for (var j = 0; j < realPos; ++j) {
  29061. var againstPosition = vectorPositions[j];
  29062. if (testedPosition.equals(againstPosition)) {
  29063. dupes[realPos] = j;
  29064. break;
  29065. }
  29066. }
  29067. }, function () {
  29068. for (var i = 0; i < indices.length; ++i) {
  29069. indices[i] = dupes[indices[i]] || indices[i];
  29070. }
  29071. //indices are now reordered
  29072. var originalSubMeshes = _this.subMeshes.slice(0);
  29073. _this.setIndices(indices);
  29074. _this.subMeshes = originalSubMeshes;
  29075. if (successCallback) {
  29076. successCallback(_this);
  29077. }
  29078. });
  29079. return this;
  29080. };
  29081. Mesh.prototype.serialize = function (serializationObject) {
  29082. serializationObject.name = this.name;
  29083. serializationObject.id = this.id;
  29084. serializationObject.type = this.getClassName();
  29085. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29086. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29087. }
  29088. serializationObject.position = this.position.asArray();
  29089. if (this.rotationQuaternion) {
  29090. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29091. }
  29092. else if (this.rotation) {
  29093. serializationObject.rotation = this.rotation.asArray();
  29094. }
  29095. serializationObject.scaling = this.scaling.asArray();
  29096. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29097. serializationObject.isEnabled = this.isEnabled(false);
  29098. serializationObject.isVisible = this.isVisible;
  29099. serializationObject.infiniteDistance = this.infiniteDistance;
  29100. serializationObject.pickable = this.isPickable;
  29101. serializationObject.receiveShadows = this.receiveShadows;
  29102. serializationObject.billboardMode = this.billboardMode;
  29103. serializationObject.visibility = this.visibility;
  29104. serializationObject.checkCollisions = this.checkCollisions;
  29105. serializationObject.isBlocker = this.isBlocker;
  29106. // Parent
  29107. if (this.parent) {
  29108. serializationObject.parentId = this.parent.id;
  29109. }
  29110. // Geometry
  29111. serializationObject.isUnIndexed = this.isUnIndexed;
  29112. var geometry = this._geometry;
  29113. if (geometry) {
  29114. var geometryId = geometry.id;
  29115. serializationObject.geometryId = geometryId;
  29116. // SubMeshes
  29117. serializationObject.subMeshes = [];
  29118. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29119. var subMesh = this.subMeshes[subIndex];
  29120. serializationObject.subMeshes.push({
  29121. materialIndex: subMesh.materialIndex,
  29122. verticesStart: subMesh.verticesStart,
  29123. verticesCount: subMesh.verticesCount,
  29124. indexStart: subMesh.indexStart,
  29125. indexCount: subMesh.indexCount
  29126. });
  29127. }
  29128. }
  29129. // Material
  29130. if (this.material) {
  29131. serializationObject.materialId = this.material.id;
  29132. }
  29133. else {
  29134. this.material = null;
  29135. }
  29136. // Morph targets
  29137. if (this.morphTargetManager) {
  29138. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29139. }
  29140. // Skeleton
  29141. if (this.skeleton) {
  29142. serializationObject.skeletonId = this.skeleton.id;
  29143. }
  29144. // Physics
  29145. //TODO implement correct serialization for physics impostors.
  29146. var impostor = this.getPhysicsImpostor();
  29147. if (impostor) {
  29148. serializationObject.physicsMass = impostor.getParam("mass");
  29149. serializationObject.physicsFriction = impostor.getParam("friction");
  29150. serializationObject.physicsRestitution = impostor.getParam("mass");
  29151. serializationObject.physicsImpostor = impostor.type;
  29152. }
  29153. // Metadata
  29154. if (this.metadata) {
  29155. serializationObject.metadata = this.metadata;
  29156. }
  29157. // Instances
  29158. serializationObject.instances = [];
  29159. for (var index = 0; index < this.instances.length; index++) {
  29160. var instance = this.instances[index];
  29161. var serializationInstance = {
  29162. name: instance.name,
  29163. id: instance.id,
  29164. position: instance.position.asArray(),
  29165. scaling: instance.scaling.asArray()
  29166. };
  29167. if (instance.rotationQuaternion) {
  29168. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29169. }
  29170. else if (instance.rotation) {
  29171. serializationInstance.rotation = instance.rotation.asArray();
  29172. }
  29173. serializationObject.instances.push(serializationInstance);
  29174. // Animations
  29175. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29176. serializationInstance.ranges = instance.serializeAnimationRanges();
  29177. }
  29178. //
  29179. // Animations
  29180. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29181. serializationObject.ranges = this.serializeAnimationRanges();
  29182. // Layer mask
  29183. serializationObject.layerMask = this.layerMask;
  29184. // Alpha
  29185. serializationObject.alphaIndex = this.alphaIndex;
  29186. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29187. // Overlay
  29188. serializationObject.overlayAlpha = this.overlayAlpha;
  29189. serializationObject.overlayColor = this.overlayColor.asArray();
  29190. serializationObject.renderOverlay = this.renderOverlay;
  29191. // Fog
  29192. serializationObject.applyFog = this.applyFog;
  29193. // Action Manager
  29194. if (this.actionManager) {
  29195. serializationObject.actions = this.actionManager.serialize(this.name);
  29196. }
  29197. };
  29198. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29199. if (!this.geometry) {
  29200. return;
  29201. }
  29202. this._markSubMeshesAsAttributesDirty();
  29203. var morphTargetManager = this._morphTargetManager;
  29204. if (morphTargetManager && morphTargetManager.vertexCount) {
  29205. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29206. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29207. this.morphTargetManager = null;
  29208. return;
  29209. }
  29210. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29211. var morphTarget = morphTargetManager.getActiveTarget(index);
  29212. var positions = morphTarget.getPositions();
  29213. if (!positions) {
  29214. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29215. return;
  29216. }
  29217. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29218. var normals = morphTarget.getNormals();
  29219. if (normals) {
  29220. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29221. }
  29222. var tangents = morphTarget.getTangents();
  29223. if (tangents) {
  29224. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29225. }
  29226. }
  29227. }
  29228. else {
  29229. var index = 0;
  29230. // Positions
  29231. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29232. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29233. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29234. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29235. }
  29236. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29237. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29238. }
  29239. index++;
  29240. }
  29241. }
  29242. };
  29243. // Statics
  29244. /**
  29245. * Returns a new Mesh object parsed from the source provided.
  29246. * The parameter `parsedMesh` is the source.
  29247. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29248. */
  29249. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29250. var mesh;
  29251. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29252. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29253. }
  29254. else {
  29255. mesh = new Mesh(parsedMesh.name, scene);
  29256. }
  29257. mesh.id = parsedMesh.id;
  29258. if (BABYLON.Tags) {
  29259. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29260. }
  29261. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29262. if (parsedMesh.metadata !== undefined) {
  29263. mesh.metadata = parsedMesh.metadata;
  29264. }
  29265. if (parsedMesh.rotationQuaternion) {
  29266. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29267. }
  29268. else if (parsedMesh.rotation) {
  29269. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29270. }
  29271. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29272. if (parsedMesh.localMatrix) {
  29273. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29274. }
  29275. else if (parsedMesh.pivotMatrix) {
  29276. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29277. }
  29278. mesh.setEnabled(parsedMesh.isEnabled);
  29279. mesh.isVisible = parsedMesh.isVisible;
  29280. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29281. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29282. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29283. if (parsedMesh.applyFog !== undefined) {
  29284. mesh.applyFog = parsedMesh.applyFog;
  29285. }
  29286. if (parsedMesh.pickable !== undefined) {
  29287. mesh.isPickable = parsedMesh.pickable;
  29288. }
  29289. if (parsedMesh.alphaIndex !== undefined) {
  29290. mesh.alphaIndex = parsedMesh.alphaIndex;
  29291. }
  29292. mesh.receiveShadows = parsedMesh.receiveShadows;
  29293. mesh.billboardMode = parsedMesh.billboardMode;
  29294. if (parsedMesh.visibility !== undefined) {
  29295. mesh.visibility = parsedMesh.visibility;
  29296. }
  29297. mesh.checkCollisions = parsedMesh.checkCollisions;
  29298. if (parsedMesh.isBlocker !== undefined) {
  29299. mesh.isBlocker = parsedMesh.isBlocker;
  29300. }
  29301. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29302. // freezeWorldMatrix
  29303. if (parsedMesh.freezeWorldMatrix) {
  29304. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29305. }
  29306. // Parent
  29307. if (parsedMesh.parentId) {
  29308. mesh._waitingParentId = parsedMesh.parentId;
  29309. }
  29310. // Actions
  29311. if (parsedMesh.actions !== undefined) {
  29312. mesh._waitingActions = parsedMesh.actions;
  29313. }
  29314. // Overlay
  29315. if (parsedMesh.overlayAlpha !== undefined) {
  29316. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29317. }
  29318. if (parsedMesh.overlayColor !== undefined) {
  29319. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29320. }
  29321. if (parsedMesh.renderOverlay !== undefined) {
  29322. mesh.renderOverlay = parsedMesh.renderOverlay;
  29323. }
  29324. // Geometry
  29325. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29326. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29327. if (parsedMesh.delayLoadingFile) {
  29328. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29329. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29330. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29331. if (parsedMesh._binaryInfo) {
  29332. mesh._binaryInfo = parsedMesh._binaryInfo;
  29333. }
  29334. mesh._delayInfo = [];
  29335. if (parsedMesh.hasUVs) {
  29336. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29337. }
  29338. if (parsedMesh.hasUVs2) {
  29339. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29340. }
  29341. if (parsedMesh.hasUVs3) {
  29342. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29343. }
  29344. if (parsedMesh.hasUVs4) {
  29345. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29346. }
  29347. if (parsedMesh.hasUVs5) {
  29348. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29349. }
  29350. if (parsedMesh.hasUVs6) {
  29351. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29352. }
  29353. if (parsedMesh.hasColors) {
  29354. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29355. }
  29356. if (parsedMesh.hasMatricesIndices) {
  29357. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29358. }
  29359. if (parsedMesh.hasMatricesWeights) {
  29360. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29361. }
  29362. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29363. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29364. mesh._checkDelayState();
  29365. }
  29366. }
  29367. else {
  29368. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29369. }
  29370. // Material
  29371. if (parsedMesh.materialId) {
  29372. mesh.setMaterialByID(parsedMesh.materialId);
  29373. }
  29374. else {
  29375. mesh.material = null;
  29376. }
  29377. // Morph targets
  29378. if (parsedMesh.morphTargetManagerId > -1) {
  29379. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29380. }
  29381. // Skeleton
  29382. if (parsedMesh.skeletonId > -1) {
  29383. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29384. if (parsedMesh.numBoneInfluencers) {
  29385. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29386. }
  29387. }
  29388. // Animations
  29389. if (parsedMesh.animations) {
  29390. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29391. var parsedAnimation = parsedMesh.animations[animationIndex];
  29392. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29393. }
  29394. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29395. }
  29396. if (parsedMesh.autoAnimate) {
  29397. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29398. }
  29399. // Layer Mask
  29400. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29401. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29402. }
  29403. else {
  29404. mesh.layerMask = 0x0FFFFFFF;
  29405. }
  29406. // Physics
  29407. if (parsedMesh.physicsImpostor) {
  29408. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29409. mass: parsedMesh.physicsMass,
  29410. friction: parsedMesh.physicsFriction,
  29411. restitution: parsedMesh.physicsRestitution
  29412. }, scene);
  29413. }
  29414. // Instances
  29415. if (parsedMesh.instances) {
  29416. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29417. var parsedInstance = parsedMesh.instances[index];
  29418. var instance = mesh.createInstance(parsedInstance.name);
  29419. if (parsedInstance.id) {
  29420. instance.id = parsedInstance.id;
  29421. }
  29422. if (BABYLON.Tags) {
  29423. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29424. }
  29425. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29426. if (parsedInstance.parentId) {
  29427. instance._waitingParentId = parsedInstance.parentId;
  29428. }
  29429. if (parsedInstance.rotationQuaternion) {
  29430. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29431. }
  29432. else if (parsedInstance.rotation) {
  29433. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29434. }
  29435. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29436. instance.checkCollisions = mesh.checkCollisions;
  29437. if (parsedMesh.animations) {
  29438. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29439. parsedAnimation = parsedMesh.animations[animationIndex];
  29440. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29441. }
  29442. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29443. }
  29444. }
  29445. }
  29446. return mesh;
  29447. };
  29448. /**
  29449. * Creates a ribbon mesh.
  29450. * Please consider using the same method from the MeshBuilder class instead.
  29451. * 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.
  29452. *
  29453. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29454. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29455. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29456. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29457. * 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.
  29458. * 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.
  29459. * 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
  29460. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29463. */
  29464. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29465. if (closeArray === void 0) { closeArray = false; }
  29466. if (updatable === void 0) { updatable = false; }
  29467. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29468. pathArray: pathArray,
  29469. closeArray: closeArray,
  29470. closePath: closePath,
  29471. offset: offset,
  29472. updatable: updatable,
  29473. sideOrientation: sideOrientation,
  29474. instance: instance
  29475. }, scene);
  29476. };
  29477. /**
  29478. * Creates a plane polygonal mesh. By default, this is a disc.
  29479. * Please consider using the same method from the MeshBuilder class instead.
  29480. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29481. * 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.
  29482. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29483. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29484. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29485. */
  29486. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29487. if (scene === void 0) { scene = null; }
  29488. var options = {
  29489. radius: radius,
  29490. tessellation: tessellation,
  29491. sideOrientation: sideOrientation,
  29492. updatable: updatable
  29493. };
  29494. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29495. };
  29496. /**
  29497. * Creates a box mesh.
  29498. * Please consider using the same method from the MeshBuilder class instead.
  29499. * The parameter `size` sets the size (float) of each box side (default 1).
  29500. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29501. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29503. */
  29504. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29505. if (scene === void 0) { scene = null; }
  29506. var options = {
  29507. size: size,
  29508. sideOrientation: sideOrientation,
  29509. updatable: updatable
  29510. };
  29511. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29512. };
  29513. /**
  29514. * Creates a sphere mesh.
  29515. * Please consider using the same method from the MeshBuilder class instead.
  29516. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29517. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29518. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29519. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29520. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29521. */
  29522. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29523. var options = {
  29524. segments: segments,
  29525. diameterX: diameter,
  29526. diameterY: diameter,
  29527. diameterZ: diameter,
  29528. sideOrientation: sideOrientation,
  29529. updatable: updatable
  29530. };
  29531. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29532. };
  29533. /**
  29534. * Creates a cylinder or a cone mesh.
  29535. * Please consider using the same method from the MeshBuilder class instead.
  29536. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29537. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29538. * 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.
  29539. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29540. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29544. */
  29545. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29546. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29547. if (scene !== undefined) {
  29548. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29549. updatable = scene;
  29550. }
  29551. scene = subdivisions;
  29552. subdivisions = 1;
  29553. }
  29554. var options = {
  29555. height: height,
  29556. diameterTop: diameterTop,
  29557. diameterBottom: diameterBottom,
  29558. tessellation: tessellation,
  29559. subdivisions: subdivisions,
  29560. sideOrientation: sideOrientation,
  29561. updatable: updatable
  29562. };
  29563. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29564. };
  29565. // Torus (Code from SharpDX.org)
  29566. /**
  29567. * Creates a torus mesh.
  29568. * Please consider using the same method from the MeshBuilder class instead.
  29569. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29570. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29571. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29572. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29573. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29575. */
  29576. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29577. var options = {
  29578. diameter: diameter,
  29579. thickness: thickness,
  29580. tessellation: tessellation,
  29581. sideOrientation: sideOrientation,
  29582. updatable: updatable
  29583. };
  29584. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29585. };
  29586. /**
  29587. * Creates a torus knot mesh.
  29588. * Please consider using the same method from the MeshBuilder class instead.
  29589. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29590. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29591. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29592. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29596. */
  29597. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29598. var options = {
  29599. radius: radius,
  29600. tube: tube,
  29601. radialSegments: radialSegments,
  29602. tubularSegments: tubularSegments,
  29603. p: p,
  29604. q: q,
  29605. sideOrientation: sideOrientation,
  29606. updatable: updatable
  29607. };
  29608. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29609. };
  29610. /**
  29611. * Creates a line mesh.
  29612. * Please consider using the same method from the MeshBuilder class instead.
  29613. * 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.
  29614. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29615. * The parameter `points` is an array successive Vector3.
  29616. * 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
  29617. * When updating an instance, remember that only point positions can change, not the number of points.
  29618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29619. */
  29620. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29621. if (scene === void 0) { scene = null; }
  29622. if (updatable === void 0) { updatable = false; }
  29623. if (instance === void 0) { instance = null; }
  29624. var options = {
  29625. points: points,
  29626. updatable: updatable,
  29627. instance: instance
  29628. };
  29629. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29630. };
  29631. /**
  29632. * Creates a dashed line mesh.
  29633. * Please consider using the same method from the MeshBuilder class instead.
  29634. * 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.
  29635. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29636. * The parameter `points` is an array successive Vector3.
  29637. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29638. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29639. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29640. * 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
  29641. * When updating an instance, remember that only point positions can change, not the number of points.
  29642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29643. */
  29644. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29645. if (scene === void 0) { scene = null; }
  29646. var options = {
  29647. points: points,
  29648. dashSize: dashSize,
  29649. gapSize: gapSize,
  29650. dashNb: dashNb,
  29651. updatable: updatable,
  29652. instance: instance
  29653. };
  29654. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29655. };
  29656. /**
  29657. * Creates a polygon mesh.
  29658. * Please consider using the same method from the MeshBuilder class instead.
  29659. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29660. * 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.
  29661. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29663. * Remember you can only change the shape positions, not their number when updating a polygon.
  29664. */
  29665. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29666. var options = {
  29667. shape: shape,
  29668. holes: holes,
  29669. updatable: updatable,
  29670. sideOrientation: sideOrientation
  29671. };
  29672. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29673. };
  29674. /**
  29675. * Creates an extruded polygon mesh, with depth in the Y direction.
  29676. * Please consider using the same method from the MeshBuilder class instead.
  29677. */
  29678. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29679. var options = {
  29680. shape: shape,
  29681. holes: holes,
  29682. depth: depth,
  29683. updatable: updatable,
  29684. sideOrientation: sideOrientation
  29685. };
  29686. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29687. };
  29688. /**
  29689. * Creates an extruded shape mesh.
  29690. * 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.
  29691. * Please consider using the same method from the MeshBuilder class instead.
  29692. *
  29693. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29694. * 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
  29695. * extruded along the Z axis.
  29696. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29697. * 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.
  29698. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29699. * 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
  29700. * 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
  29701. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29705. */
  29706. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29707. if (scene === void 0) { scene = null; }
  29708. var options = {
  29709. shape: shape,
  29710. path: path,
  29711. scale: scale,
  29712. rotation: rotation,
  29713. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29714. sideOrientation: sideOrientation,
  29715. instance: instance,
  29716. updatable: updatable
  29717. };
  29718. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29719. };
  29720. /**
  29721. * Creates an custom extruded shape mesh.
  29722. * 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.
  29723. * Please consider using the same method from the MeshBuilder class instead.
  29724. *
  29725. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29726. * 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
  29727. * extruded along the Z axis.
  29728. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29729. * 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
  29730. * and the distance of this point from the begining of the path :
  29731. * ```javascript
  29732. * var rotationFunction = function(i, distance) {
  29733. * // do things
  29734. * return rotationValue; }
  29735. * ```
  29736. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29737. * 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
  29738. * and the distance of this point from the begining of the path :
  29739. * ```javascript
  29740. * var scaleFunction = function(i, distance) {
  29741. * // do things
  29742. * return scaleValue;}
  29743. * ```
  29744. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29745. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29746. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29747. * 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
  29748. * 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
  29749. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29751. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29753. */
  29754. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29755. var options = {
  29756. shape: shape,
  29757. path: path,
  29758. scaleFunction: scaleFunction,
  29759. rotationFunction: rotationFunction,
  29760. ribbonCloseArray: ribbonCloseArray,
  29761. ribbonClosePath: ribbonClosePath,
  29762. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29763. sideOrientation: sideOrientation,
  29764. instance: instance,
  29765. updatable: updatable
  29766. };
  29767. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29768. };
  29769. /**
  29770. * Creates lathe mesh.
  29771. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29772. * Please consider using the same method from the MeshBuilder class instead.
  29773. * 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
  29774. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29775. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29776. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29780. */
  29781. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29782. var options = {
  29783. shape: shape,
  29784. radius: radius,
  29785. tessellation: tessellation,
  29786. sideOrientation: sideOrientation,
  29787. updatable: updatable
  29788. };
  29789. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29790. };
  29791. /**
  29792. * Creates a plane mesh.
  29793. * Please consider using the same method from the MeshBuilder class instead.
  29794. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29796. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29798. */
  29799. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29800. var options = {
  29801. size: size,
  29802. width: size,
  29803. height: size,
  29804. sideOrientation: sideOrientation,
  29805. updatable: updatable
  29806. };
  29807. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29808. };
  29809. /**
  29810. * Creates a ground mesh.
  29811. * Please consider using the same method from the MeshBuilder class instead.
  29812. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29813. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29815. */
  29816. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29817. var options = {
  29818. width: width,
  29819. height: height,
  29820. subdivisions: subdivisions,
  29821. updatable: updatable
  29822. };
  29823. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29824. };
  29825. /**
  29826. * Creates a tiled ground mesh.
  29827. * Please consider using the same method from the MeshBuilder class instead.
  29828. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29829. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29830. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29831. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29832. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29833. * numbers of subdivisions on the ground width and height of each tile.
  29834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29835. */
  29836. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29837. var options = {
  29838. xmin: xmin,
  29839. zmin: zmin,
  29840. xmax: xmax,
  29841. zmax: zmax,
  29842. subdivisions: subdivisions,
  29843. precision: precision,
  29844. updatable: updatable
  29845. };
  29846. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29847. };
  29848. /**
  29849. * Creates a ground mesh from a height map.
  29850. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29851. * Please consider using the same method from the MeshBuilder class instead.
  29852. * The parameter `url` sets the URL of the height map image resource.
  29853. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29854. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29855. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29856. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29857. * 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).
  29858. * This function is passed the newly built mesh :
  29859. * ```javascript
  29860. * function(mesh) { // do things
  29861. * return; }
  29862. * ```
  29863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29864. */
  29865. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29866. var options = {
  29867. width: width,
  29868. height: height,
  29869. subdivisions: subdivisions,
  29870. minHeight: minHeight,
  29871. maxHeight: maxHeight,
  29872. updatable: updatable,
  29873. onReady: onReady
  29874. };
  29875. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29876. };
  29877. /**
  29878. * Creates a tube mesh.
  29879. * 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.
  29880. * Please consider using the same method from the MeshBuilder class instead.
  29881. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29882. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29883. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29884. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29885. * 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.
  29886. * It must return a radius value (positive float) :
  29887. * ```javascript
  29888. * var radiusFunction = function(i, distance) {
  29889. * // do things
  29890. * return radius; }
  29891. * ```
  29892. * 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
  29893. * 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
  29894. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29895. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29897. */
  29898. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29899. var options = {
  29900. path: path,
  29901. radius: radius,
  29902. tessellation: tessellation,
  29903. radiusFunction: radiusFunction,
  29904. arc: 1,
  29905. cap: cap,
  29906. updatable: updatable,
  29907. sideOrientation: sideOrientation,
  29908. instance: instance
  29909. };
  29910. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29911. };
  29912. /**
  29913. * Creates a polyhedron mesh.
  29914. * Please consider using the same method from the MeshBuilder class instead.
  29915. * 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
  29916. * to choose the wanted type.
  29917. * The parameter `size` (positive float, default 1) sets the polygon size.
  29918. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29919. * 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`.
  29920. * 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
  29921. * 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)`).
  29922. * 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
  29923. * 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.
  29924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29925. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29926. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29927. */
  29928. Mesh.CreatePolyhedron = function (name, options, scene) {
  29929. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29930. };
  29931. /**
  29932. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29933. * Please consider using the same method from the MeshBuilder class instead.
  29934. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29935. * 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`).
  29936. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29937. * 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.
  29938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29941. */
  29942. Mesh.CreateIcoSphere = function (name, options, scene) {
  29943. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29944. };
  29945. /**
  29946. * Creates a decal mesh.
  29947. * Please consider using the same method from the MeshBuilder class instead.
  29948. * 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.
  29949. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29950. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29951. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29952. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29953. */
  29954. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29955. var options = {
  29956. position: position,
  29957. normal: normal,
  29958. size: size,
  29959. angle: angle
  29960. };
  29961. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29962. };
  29963. // Skeletons
  29964. /**
  29965. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29966. */
  29967. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29968. if (!this._sourcePositions) {
  29969. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29970. if (!source) {
  29971. return this._sourcePositions;
  29972. }
  29973. this._sourcePositions = new Float32Array(source);
  29974. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29975. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29976. }
  29977. }
  29978. return this._sourcePositions;
  29979. };
  29980. /**
  29981. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29982. */
  29983. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29984. if (!this._sourceNormals) {
  29985. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29986. if (!source) {
  29987. return this._sourceNormals;
  29988. }
  29989. this._sourceNormals = new Float32Array(source);
  29990. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29991. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29992. }
  29993. }
  29994. return this._sourceNormals;
  29995. };
  29996. /**
  29997. * Updates the vertex buffer by applying transformation from the bones.
  29998. * Returns the Mesh.
  29999. *
  30000. * @param {skeleton} skeleton to apply
  30001. */
  30002. Mesh.prototype.applySkeleton = function (skeleton) {
  30003. if (!this.geometry) {
  30004. return this;
  30005. }
  30006. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30007. return this;
  30008. }
  30009. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30010. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30011. return this;
  30012. }
  30013. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30014. return this;
  30015. }
  30016. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30017. return this;
  30018. }
  30019. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30020. return this;
  30021. }
  30022. if (!this._sourcePositions) {
  30023. var submeshes = this.subMeshes.slice();
  30024. this.setPositionsForCPUSkinning();
  30025. this.subMeshes = submeshes;
  30026. }
  30027. if (!this._sourceNormals) {
  30028. this.setNormalsForCPUSkinning();
  30029. }
  30030. // positionsData checks for not being Float32Array will only pass at most once
  30031. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30032. if (!positionsData) {
  30033. return this;
  30034. }
  30035. if (!(positionsData instanceof Float32Array)) {
  30036. positionsData = new Float32Array(positionsData);
  30037. }
  30038. // normalsData checks for not being Float32Array will only pass at most once
  30039. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30040. if (!normalsData) {
  30041. return this;
  30042. }
  30043. if (!(normalsData instanceof Float32Array)) {
  30044. normalsData = new Float32Array(normalsData);
  30045. }
  30046. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30047. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30048. if (!matricesWeightsData || !matricesIndicesData) {
  30049. return this;
  30050. }
  30051. var needExtras = this.numBoneInfluencers > 4;
  30052. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30053. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30054. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30055. var tempVector3 = BABYLON.Vector3.Zero();
  30056. var finalMatrix = new BABYLON.Matrix();
  30057. var tempMatrix = new BABYLON.Matrix();
  30058. var matWeightIdx = 0;
  30059. var inf;
  30060. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30061. var weight;
  30062. for (inf = 0; inf < 4; inf++) {
  30063. weight = matricesWeightsData[matWeightIdx + inf];
  30064. if (weight > 0) {
  30065. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30066. finalMatrix.addToSelf(tempMatrix);
  30067. }
  30068. else
  30069. break;
  30070. }
  30071. if (needExtras) {
  30072. for (inf = 0; inf < 4; inf++) {
  30073. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30074. if (weight > 0) {
  30075. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30076. finalMatrix.addToSelf(tempMatrix);
  30077. }
  30078. else
  30079. break;
  30080. }
  30081. }
  30082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30083. tempVector3.toArray(positionsData, index);
  30084. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30085. tempVector3.toArray(normalsData, index);
  30086. finalMatrix.reset();
  30087. }
  30088. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30089. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30090. return this;
  30091. };
  30092. // Tools
  30093. /**
  30094. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30095. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30096. */
  30097. Mesh.MinMax = function (meshes) {
  30098. var minVector = null;
  30099. var maxVector = null;
  30100. meshes.forEach(function (mesh, index, array) {
  30101. var boundingInfo = mesh.getBoundingInfo();
  30102. var boundingBox = boundingInfo.boundingBox;
  30103. if (!minVector || !maxVector) {
  30104. minVector = boundingBox.minimumWorld;
  30105. maxVector = boundingBox.maximumWorld;
  30106. }
  30107. else {
  30108. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30109. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30110. }
  30111. });
  30112. if (!minVector || !maxVector) {
  30113. return {
  30114. min: BABYLON.Vector3.Zero(),
  30115. max: BABYLON.Vector3.Zero()
  30116. };
  30117. }
  30118. return {
  30119. min: minVector,
  30120. max: maxVector
  30121. };
  30122. };
  30123. /**
  30124. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30125. */
  30126. Mesh.Center = function (meshesOrMinMaxVector) {
  30127. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30128. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30129. };
  30130. /**
  30131. * Merge the array of meshes into a single mesh for performance reasons.
  30132. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30133. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30134. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30135. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30136. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30137. */
  30138. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30139. if (disposeSource === void 0) { disposeSource = true; }
  30140. var index;
  30141. if (!allow32BitsIndices) {
  30142. var totalVertices = 0;
  30143. // Counting vertices
  30144. for (index = 0; index < meshes.length; index++) {
  30145. if (meshes[index]) {
  30146. totalVertices += meshes[index].getTotalVertices();
  30147. if (totalVertices > 65536) {
  30148. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30149. return null;
  30150. }
  30151. }
  30152. }
  30153. }
  30154. // Merge
  30155. var vertexData = null;
  30156. var otherVertexData;
  30157. var indiceArray = new Array();
  30158. var source = null;
  30159. for (index = 0; index < meshes.length; index++) {
  30160. if (meshes[index]) {
  30161. meshes[index].computeWorldMatrix(true);
  30162. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30163. otherVertexData.transform(meshes[index].getWorldMatrix());
  30164. if (vertexData) {
  30165. vertexData.merge(otherVertexData);
  30166. }
  30167. else {
  30168. vertexData = otherVertexData;
  30169. source = meshes[index];
  30170. }
  30171. if (subdivideWithSubMeshes) {
  30172. indiceArray.push(meshes[index].getTotalIndices());
  30173. }
  30174. }
  30175. }
  30176. source = source;
  30177. if (!meshSubclass) {
  30178. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30179. }
  30180. vertexData.applyToMesh(meshSubclass);
  30181. // Setting properties
  30182. meshSubclass.material = source.material;
  30183. meshSubclass.checkCollisions = source.checkCollisions;
  30184. // Cleaning
  30185. if (disposeSource) {
  30186. for (index = 0; index < meshes.length; index++) {
  30187. if (meshes[index]) {
  30188. meshes[index].dispose();
  30189. }
  30190. }
  30191. }
  30192. // Subdivide
  30193. if (subdivideWithSubMeshes) {
  30194. //-- Suppresions du submesh global
  30195. meshSubclass.releaseSubMeshes();
  30196. index = 0;
  30197. var offset = 0;
  30198. //-- aplique la subdivision en fonction du tableau d'indices
  30199. while (index < indiceArray.length) {
  30200. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30201. offset += indiceArray[index];
  30202. index++;
  30203. }
  30204. }
  30205. return meshSubclass;
  30206. };
  30207. // Consts
  30208. Mesh._FRONTSIDE = 0;
  30209. Mesh._BACKSIDE = 1;
  30210. Mesh._DOUBLESIDE = 2;
  30211. Mesh._DEFAULTSIDE = 0;
  30212. Mesh._NO_CAP = 0;
  30213. Mesh._CAP_START = 1;
  30214. Mesh._CAP_END = 2;
  30215. Mesh._CAP_ALL = 3;
  30216. return Mesh;
  30217. }(BABYLON.AbstractMesh));
  30218. BABYLON.Mesh = Mesh;
  30219. })(BABYLON || (BABYLON = {}));
  30220. //# sourceMappingURL=babylon.mesh.js.map
  30221. var BABYLON;
  30222. (function (BABYLON) {
  30223. var BaseSubMesh = /** @class */ (function () {
  30224. function BaseSubMesh() {
  30225. }
  30226. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30227. get: function () {
  30228. return this._materialEffect;
  30229. },
  30230. enumerable: true,
  30231. configurable: true
  30232. });
  30233. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30234. if (defines === void 0) { defines = null; }
  30235. if (this._materialEffect === effect) {
  30236. if (!effect) {
  30237. this._materialDefines = null;
  30238. }
  30239. return;
  30240. }
  30241. this._materialDefines = defines;
  30242. this._materialEffect = effect;
  30243. };
  30244. return BaseSubMesh;
  30245. }());
  30246. BABYLON.BaseSubMesh = BaseSubMesh;
  30247. var SubMesh = /** @class */ (function (_super) {
  30248. __extends(SubMesh, _super);
  30249. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30250. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30251. var _this = _super.call(this) || this;
  30252. _this.materialIndex = materialIndex;
  30253. _this.verticesStart = verticesStart;
  30254. _this.verticesCount = verticesCount;
  30255. _this.indexStart = indexStart;
  30256. _this.indexCount = indexCount;
  30257. _this._renderId = 0;
  30258. _this._mesh = mesh;
  30259. _this._renderingMesh = renderingMesh || mesh;
  30260. mesh.subMeshes.push(_this);
  30261. _this._trianglePlanes = [];
  30262. _this._id = mesh.subMeshes.length - 1;
  30263. if (createBoundingBox) {
  30264. _this.refreshBoundingInfo();
  30265. mesh.computeWorldMatrix(true);
  30266. }
  30267. return _this;
  30268. }
  30269. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30270. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30271. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30272. };
  30273. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30274. get: function () {
  30275. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30276. },
  30277. enumerable: true,
  30278. configurable: true
  30279. });
  30280. /**
  30281. * Returns the submesh BoudingInfo object.
  30282. */
  30283. SubMesh.prototype.getBoundingInfo = function () {
  30284. if (this.IsGlobal) {
  30285. return this._mesh.getBoundingInfo();
  30286. }
  30287. return this._boundingInfo;
  30288. };
  30289. /**
  30290. * Sets the submesh BoundingInfo.
  30291. * Return the SubMesh.
  30292. */
  30293. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30294. this._boundingInfo = boundingInfo;
  30295. return this;
  30296. };
  30297. /**
  30298. * Returns the mesh of the current submesh.
  30299. */
  30300. SubMesh.prototype.getMesh = function () {
  30301. return this._mesh;
  30302. };
  30303. /**
  30304. * Returns the rendering mesh of the submesh.
  30305. */
  30306. SubMesh.prototype.getRenderingMesh = function () {
  30307. return this._renderingMesh;
  30308. };
  30309. /**
  30310. * Returns the submesh material.
  30311. */
  30312. SubMesh.prototype.getMaterial = function () {
  30313. var rootMaterial = this._renderingMesh.material;
  30314. if (rootMaterial === null || rootMaterial === undefined) {
  30315. return this._mesh.getScene().defaultMaterial;
  30316. }
  30317. else if (rootMaterial.getSubMaterial) {
  30318. var multiMaterial = rootMaterial;
  30319. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30320. if (this._currentMaterial !== effectiveMaterial) {
  30321. this._currentMaterial = effectiveMaterial;
  30322. this._materialDefines = null;
  30323. }
  30324. return effectiveMaterial;
  30325. }
  30326. return rootMaterial;
  30327. };
  30328. // Methods
  30329. /**
  30330. * Sets a new updated BoundingInfo object to the submesh.
  30331. * Returns the SubMesh.
  30332. */
  30333. SubMesh.prototype.refreshBoundingInfo = function () {
  30334. this._lastColliderWorldVertices = null;
  30335. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30336. return this;
  30337. }
  30338. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30339. if (!data) {
  30340. this._boundingInfo = this._mesh.getBoundingInfo();
  30341. return this;
  30342. }
  30343. var indices = this._renderingMesh.getIndices();
  30344. var extend;
  30345. //is this the only submesh?
  30346. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30347. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30348. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30349. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30350. }
  30351. else {
  30352. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30353. }
  30354. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30355. return this;
  30356. };
  30357. SubMesh.prototype._checkCollision = function (collider) {
  30358. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30359. return boundingInfo._checkCollision(collider);
  30360. };
  30361. /**
  30362. * Updates the submesh BoundingInfo.
  30363. * Returns the Submesh.
  30364. */
  30365. SubMesh.prototype.updateBoundingInfo = function (world) {
  30366. var boundingInfo = this.getBoundingInfo();
  30367. if (!boundingInfo) {
  30368. this.refreshBoundingInfo();
  30369. boundingInfo = this.getBoundingInfo();
  30370. }
  30371. boundingInfo.update(world);
  30372. return this;
  30373. };
  30374. /**
  30375. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30376. * Boolean returned.
  30377. */
  30378. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30379. var boundingInfo = this.getBoundingInfo();
  30380. if (!boundingInfo) {
  30381. return false;
  30382. }
  30383. return boundingInfo.isInFrustum(frustumPlanes);
  30384. };
  30385. /**
  30386. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30387. * Boolean returned.
  30388. */
  30389. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30390. var boundingInfo = this.getBoundingInfo();
  30391. if (!boundingInfo) {
  30392. return false;
  30393. }
  30394. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30395. };
  30396. /**
  30397. * Renders the submesh.
  30398. * Returns it.
  30399. */
  30400. SubMesh.prototype.render = function (enableAlphaMode) {
  30401. this._renderingMesh.render(this, enableAlphaMode);
  30402. return this;
  30403. };
  30404. /**
  30405. * Returns a new Index Buffer.
  30406. * Type returned : WebGLBuffer.
  30407. */
  30408. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30409. if (!this._linesIndexBuffer) {
  30410. var linesIndices = [];
  30411. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30412. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30413. }
  30414. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30415. this.linesIndexCount = linesIndices.length;
  30416. }
  30417. return this._linesIndexBuffer;
  30418. };
  30419. /**
  30420. * True is the passed Ray intersects the submesh bounding box.
  30421. * Boolean returned.
  30422. */
  30423. SubMesh.prototype.canIntersects = function (ray) {
  30424. var boundingInfo = this.getBoundingInfo();
  30425. if (!boundingInfo) {
  30426. return false;
  30427. }
  30428. return ray.intersectsBox(boundingInfo.boundingBox);
  30429. };
  30430. /**
  30431. * Returns an object IntersectionInfo.
  30432. */
  30433. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30434. var intersectInfo = null;
  30435. // LineMesh first as it's also a Mesh...
  30436. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30437. var lineMesh = this._mesh;
  30438. // Line test
  30439. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30440. var p0 = positions[indices[index]];
  30441. var p1 = positions[indices[index + 1]];
  30442. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30443. if (length < 0) {
  30444. continue;
  30445. }
  30446. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30447. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30448. if (fastCheck) {
  30449. break;
  30450. }
  30451. }
  30452. }
  30453. }
  30454. else {
  30455. // Triangles test
  30456. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30457. var p0 = positions[indices[index]];
  30458. var p1 = positions[indices[index + 1]];
  30459. var p2 = positions[indices[index + 2]];
  30460. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30461. if (currentIntersectInfo) {
  30462. if (currentIntersectInfo.distance < 0) {
  30463. continue;
  30464. }
  30465. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30466. intersectInfo = currentIntersectInfo;
  30467. intersectInfo.faceId = index / 3;
  30468. if (fastCheck) {
  30469. break;
  30470. }
  30471. }
  30472. }
  30473. }
  30474. }
  30475. return intersectInfo;
  30476. };
  30477. SubMesh.prototype._rebuild = function () {
  30478. if (this._linesIndexBuffer) {
  30479. this._linesIndexBuffer = null;
  30480. }
  30481. };
  30482. // Clone
  30483. /**
  30484. * Creates a new Submesh from the passed Mesh.
  30485. */
  30486. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30487. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30488. if (!this.IsGlobal) {
  30489. var boundingInfo = this.getBoundingInfo();
  30490. if (!boundingInfo) {
  30491. return result;
  30492. }
  30493. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30494. }
  30495. return result;
  30496. };
  30497. // Dispose
  30498. /**
  30499. * Disposes the Submesh.
  30500. * Returns nothing.
  30501. */
  30502. SubMesh.prototype.dispose = function () {
  30503. if (this._linesIndexBuffer) {
  30504. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30505. this._linesIndexBuffer = null;
  30506. }
  30507. // Remove from mesh
  30508. var index = this._mesh.subMeshes.indexOf(this);
  30509. this._mesh.subMeshes.splice(index, 1);
  30510. };
  30511. // Statics
  30512. /**
  30513. * Creates a new Submesh from the passed parameters :
  30514. * - materialIndex (integer) : the index of the main mesh material.
  30515. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30516. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30517. * - mesh (Mesh) : the main mesh to create the submesh from.
  30518. * - renderingMesh (optional Mesh) : rendering mesh.
  30519. */
  30520. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30521. var minVertexIndex = Number.MAX_VALUE;
  30522. var maxVertexIndex = -Number.MAX_VALUE;
  30523. renderingMesh = (renderingMesh || mesh);
  30524. var indices = renderingMesh.getIndices();
  30525. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30526. var vertexIndex = indices[index];
  30527. if (vertexIndex < minVertexIndex)
  30528. minVertexIndex = vertexIndex;
  30529. if (vertexIndex > maxVertexIndex)
  30530. maxVertexIndex = vertexIndex;
  30531. }
  30532. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30533. };
  30534. return SubMesh;
  30535. }(BaseSubMesh));
  30536. BABYLON.SubMesh = SubMesh;
  30537. })(BABYLON || (BABYLON = {}));
  30538. //# sourceMappingURL=babylon.subMesh.js.map
  30539. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30540. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30541. s = arguments[i];
  30542. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30543. t[p] = s[p];
  30544. }
  30545. return t;
  30546. };
  30547. var BABYLON;
  30548. (function (BABYLON) {
  30549. /**
  30550. * Manages the defines for the Material.
  30551. */
  30552. var MaterialDefines = /** @class */ (function () {
  30553. function MaterialDefines() {
  30554. this._isDirty = true;
  30555. this._areLightsDirty = true;
  30556. this._areAttributesDirty = true;
  30557. this._areTexturesDirty = true;
  30558. this._areFresnelDirty = true;
  30559. this._areMiscDirty = true;
  30560. this._areImageProcessingDirty = true;
  30561. this._normals = false;
  30562. this._uvs = false;
  30563. this._needNormals = false;
  30564. this._needUVs = false;
  30565. }
  30566. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30567. /**
  30568. * Specifies if the material needs to be re-calculated.
  30569. */
  30570. get: function () {
  30571. return this._isDirty;
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. /**
  30577. * Marks the material to indicate that it has been re-calculated.
  30578. */
  30579. MaterialDefines.prototype.markAsProcessed = function () {
  30580. this._isDirty = false;
  30581. this._areAttributesDirty = false;
  30582. this._areTexturesDirty = false;
  30583. this._areFresnelDirty = false;
  30584. this._areLightsDirty = false;
  30585. this._areMiscDirty = false;
  30586. this._areImageProcessingDirty = false;
  30587. };
  30588. /**
  30589. * Marks the material to indicate that it needs to be re-calculated.
  30590. */
  30591. MaterialDefines.prototype.markAsUnprocessed = function () {
  30592. this._isDirty = true;
  30593. };
  30594. /**
  30595. * Marks the material to indicate all of its defines need to be re-calculated.
  30596. */
  30597. MaterialDefines.prototype.markAllAsDirty = function () {
  30598. this._areTexturesDirty = true;
  30599. this._areAttributesDirty = true;
  30600. this._areLightsDirty = true;
  30601. this._areFresnelDirty = true;
  30602. this._areMiscDirty = true;
  30603. this._areImageProcessingDirty = true;
  30604. this._isDirty = true;
  30605. };
  30606. /**
  30607. * Marks the material to indicate that image processing needs to be re-calculated.
  30608. */
  30609. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30610. this._areImageProcessingDirty = true;
  30611. this._isDirty = true;
  30612. };
  30613. /**
  30614. * Marks the material to indicate the lights need to be re-calculated.
  30615. */
  30616. MaterialDefines.prototype.markAsLightDirty = function () {
  30617. this._areLightsDirty = true;
  30618. this._isDirty = true;
  30619. };
  30620. /**
  30621. * Marks the attribute state as changed.
  30622. */
  30623. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30624. this._areAttributesDirty = true;
  30625. this._isDirty = true;
  30626. };
  30627. /**
  30628. * Marks the texture state as changed.
  30629. */
  30630. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30631. this._areTexturesDirty = true;
  30632. this._isDirty = true;
  30633. };
  30634. /**
  30635. * Marks the fresnel state as changed.
  30636. */
  30637. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30638. this._areFresnelDirty = true;
  30639. this._isDirty = true;
  30640. };
  30641. /**
  30642. * Marks the misc state as changed.
  30643. */
  30644. MaterialDefines.prototype.markAsMiscDirty = function () {
  30645. this._areMiscDirty = true;
  30646. this._isDirty = true;
  30647. };
  30648. /**
  30649. * Rebuilds the material defines.
  30650. */
  30651. MaterialDefines.prototype.rebuild = function () {
  30652. if (this._keys) {
  30653. delete this._keys;
  30654. }
  30655. this._keys = [];
  30656. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30657. var key = _a[_i];
  30658. if (key[0] === "_") {
  30659. continue;
  30660. }
  30661. this._keys.push(key);
  30662. }
  30663. };
  30664. /**
  30665. * Specifies if two material defines are equal.
  30666. * @param other - A material define instance to compare to.
  30667. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30668. */
  30669. MaterialDefines.prototype.isEqual = function (other) {
  30670. if (this._keys.length !== other._keys.length) {
  30671. return false;
  30672. }
  30673. for (var index = 0; index < this._keys.length; index++) {
  30674. var prop = this._keys[index];
  30675. if (this[prop] !== other[prop]) {
  30676. return false;
  30677. }
  30678. }
  30679. return true;
  30680. };
  30681. /**
  30682. * Clones this instance's defines to another instance.
  30683. * @param other - material defines to clone values to.
  30684. */
  30685. MaterialDefines.prototype.cloneTo = function (other) {
  30686. if (this._keys.length !== other._keys.length) {
  30687. other._keys = this._keys.slice(0);
  30688. }
  30689. for (var index = 0; index < this._keys.length; index++) {
  30690. var prop = this._keys[index];
  30691. other[prop] = this[prop];
  30692. }
  30693. };
  30694. /**
  30695. * Resets the material define values.
  30696. */
  30697. MaterialDefines.prototype.reset = function () {
  30698. for (var index = 0; index < this._keys.length; index++) {
  30699. var prop = this._keys[index];
  30700. if (typeof (this[prop]) === "number") {
  30701. this[prop] = 0;
  30702. }
  30703. else {
  30704. this[prop] = false;
  30705. }
  30706. }
  30707. };
  30708. /**
  30709. * Converts the material define values to a string.
  30710. * @returns - String of material define information.
  30711. */
  30712. MaterialDefines.prototype.toString = function () {
  30713. var result = "";
  30714. for (var index = 0; index < this._keys.length; index++) {
  30715. var prop = this._keys[index];
  30716. var value = this[prop];
  30717. if (typeof (value) === "number") {
  30718. result += "#define " + prop + " " + this[prop] + "\n";
  30719. }
  30720. else if (value) {
  30721. result += "#define " + prop + "\n";
  30722. }
  30723. }
  30724. return result;
  30725. };
  30726. return MaterialDefines;
  30727. }());
  30728. BABYLON.MaterialDefines = MaterialDefines;
  30729. /**
  30730. * This offers the main features of a material in BJS.
  30731. */
  30732. var Material = /** @class */ (function () {
  30733. /**
  30734. * Creates a material instance.
  30735. * @param name - The name of the material.
  30736. * @param scene - The BJS scene to reference.
  30737. * @param doNotAdd - Specifies if the material should be added to the scene.
  30738. */
  30739. function Material(name, scene, doNotAdd) {
  30740. /**
  30741. * Specifies if the ready state should be checked on each call.
  30742. */
  30743. this.checkReadyOnEveryCall = false;
  30744. /**
  30745. * Specifies if the ready state should be checked once.
  30746. */
  30747. this.checkReadyOnlyOnce = false;
  30748. /**
  30749. * The state of the material.
  30750. */
  30751. this.state = "";
  30752. /**
  30753. * The alpha value of the material.
  30754. */
  30755. this._alpha = 1.0;
  30756. /**
  30757. * Specifies if back face culling is enabled.
  30758. */
  30759. this._backFaceCulling = true;
  30760. /**
  30761. * Specifies if the material should be serialized.
  30762. */
  30763. this.doNotSerialize = false;
  30764. /**
  30765. * Specifies if the effect should be stored on sub meshes.
  30766. */
  30767. this.storeEffectOnSubMeshes = false;
  30768. /**
  30769. * An event triggered when the material is disposed.
  30770. * @type {BABYLON.Observable}
  30771. */
  30772. this.onDisposeObservable = new BABYLON.Observable();
  30773. /**
  30774. * An event triggered when the material is bound.
  30775. * @type {BABYLON.Observable}
  30776. */
  30777. this.onBindObservable = new BABYLON.Observable();
  30778. /**
  30779. * An event triggered when the material is unbound.
  30780. * @type {BABYLON.Observable}
  30781. */
  30782. this.onUnBindObservable = new BABYLON.Observable();
  30783. /**
  30784. * Stores the value of the alpha mode.
  30785. */
  30786. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30787. /**
  30788. * Stores the state of the need depth pre-pass value.
  30789. */
  30790. this._needDepthPrePass = false;
  30791. /**
  30792. * Specifies if depth writing should be disabled.
  30793. */
  30794. this.disableDepthWrite = false;
  30795. /**
  30796. * Specifies if depth writing should be forced.
  30797. */
  30798. this.forceDepthWrite = false;
  30799. /**
  30800. * Specifies if there should be a separate pass for culling.
  30801. */
  30802. this.separateCullingPass = false;
  30803. /**
  30804. * Stores the state specifing if fog should be enabled.
  30805. */
  30806. this._fogEnabled = true;
  30807. /**
  30808. * Stores the size of points.
  30809. */
  30810. this.pointSize = 1.0;
  30811. /**
  30812. * Stores the z offset value.
  30813. */
  30814. this.zOffset = 0;
  30815. /**
  30816. * Specifies if the material was previously ready.
  30817. */
  30818. this._wasPreviouslyReady = false;
  30819. /**
  30820. * Stores the fill mode state.
  30821. */
  30822. this._fillMode = Material.TriangleFillMode;
  30823. this.name = name;
  30824. this.id = name || BABYLON.Tools.RandomId();
  30825. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30826. if (this._scene.useRightHandedSystem) {
  30827. this.sideOrientation = Material.ClockWiseSideOrientation;
  30828. }
  30829. else {
  30830. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30831. }
  30832. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30833. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30834. if (!doNotAdd) {
  30835. this._scene.materials.push(this);
  30836. }
  30837. }
  30838. Object.defineProperty(Material, "TriangleFillMode", {
  30839. /**
  30840. * Returns the triangle fill mode.
  30841. */
  30842. get: function () {
  30843. return Material._TriangleFillMode;
  30844. },
  30845. enumerable: true,
  30846. configurable: true
  30847. });
  30848. Object.defineProperty(Material, "WireFrameFillMode", {
  30849. /**
  30850. * Returns the wireframe mode.
  30851. */
  30852. get: function () {
  30853. return Material._WireFrameFillMode;
  30854. },
  30855. enumerable: true,
  30856. configurable: true
  30857. });
  30858. Object.defineProperty(Material, "PointFillMode", {
  30859. /**
  30860. * Returns the point fill mode.
  30861. */
  30862. get: function () {
  30863. return Material._PointFillMode;
  30864. },
  30865. enumerable: true,
  30866. configurable: true
  30867. });
  30868. Object.defineProperty(Material, "PointListDrawMode", {
  30869. /**
  30870. * Returns the point list draw mode.
  30871. */
  30872. get: function () {
  30873. return Material._PointListDrawMode;
  30874. },
  30875. enumerable: true,
  30876. configurable: true
  30877. });
  30878. Object.defineProperty(Material, "LineListDrawMode", {
  30879. /**
  30880. * Returns the line list draw mode.
  30881. */
  30882. get: function () {
  30883. return Material._LineListDrawMode;
  30884. },
  30885. enumerable: true,
  30886. configurable: true
  30887. });
  30888. Object.defineProperty(Material, "LineLoopDrawMode", {
  30889. /**
  30890. * Returns the line loop draw mode.
  30891. */
  30892. get: function () {
  30893. return Material._LineLoopDrawMode;
  30894. },
  30895. enumerable: true,
  30896. configurable: true
  30897. });
  30898. Object.defineProperty(Material, "LineStripDrawMode", {
  30899. /**
  30900. * Returns the line strip draw mode.
  30901. */
  30902. get: function () {
  30903. return Material._LineStripDrawMode;
  30904. },
  30905. enumerable: true,
  30906. configurable: true
  30907. });
  30908. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30909. /**
  30910. * Returns the triangle strip draw mode.
  30911. */
  30912. get: function () {
  30913. return Material._TriangleStripDrawMode;
  30914. },
  30915. enumerable: true,
  30916. configurable: true
  30917. });
  30918. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30919. /**
  30920. * Returns the triangle fan draw mode.
  30921. */
  30922. get: function () {
  30923. return Material._TriangleFanDrawMode;
  30924. },
  30925. enumerable: true,
  30926. configurable: true
  30927. });
  30928. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30929. /**
  30930. * Returns the clock-wise side orientation.
  30931. */
  30932. get: function () {
  30933. return Material._ClockWiseSideOrientation;
  30934. },
  30935. enumerable: true,
  30936. configurable: true
  30937. });
  30938. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30939. /**
  30940. * Returns the counter clock-wise side orientation.
  30941. */
  30942. get: function () {
  30943. return Material._CounterClockWiseSideOrientation;
  30944. },
  30945. enumerable: true,
  30946. configurable: true
  30947. });
  30948. Object.defineProperty(Material, "TextureDirtyFlag", {
  30949. /**
  30950. * Returns the dirty texture flag value.
  30951. */
  30952. get: function () {
  30953. return Material._TextureDirtyFlag;
  30954. },
  30955. enumerable: true,
  30956. configurable: true
  30957. });
  30958. Object.defineProperty(Material, "LightDirtyFlag", {
  30959. /**
  30960. * Returns the dirty light flag value.
  30961. */
  30962. get: function () {
  30963. return Material._LightDirtyFlag;
  30964. },
  30965. enumerable: true,
  30966. configurable: true
  30967. });
  30968. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30969. /**
  30970. * Returns the dirty fresnel flag value.
  30971. */
  30972. get: function () {
  30973. return Material._FresnelDirtyFlag;
  30974. },
  30975. enumerable: true,
  30976. configurable: true
  30977. });
  30978. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30979. /**
  30980. * Returns the dirty attributes flag value.
  30981. */
  30982. get: function () {
  30983. return Material._AttributesDirtyFlag;
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. Object.defineProperty(Material, "MiscDirtyFlag", {
  30989. /**
  30990. * Returns the dirty misc flag value.
  30991. */
  30992. get: function () {
  30993. return Material._MiscDirtyFlag;
  30994. },
  30995. enumerable: true,
  30996. configurable: true
  30997. });
  30998. Object.defineProperty(Material.prototype, "alpha", {
  30999. /**
  31000. * Gets the alpha value of the material.
  31001. */
  31002. get: function () {
  31003. return this._alpha;
  31004. },
  31005. /**
  31006. * Sets the alpha value of the material.
  31007. */
  31008. set: function (value) {
  31009. if (this._alpha === value) {
  31010. return;
  31011. }
  31012. this._alpha = value;
  31013. this.markAsDirty(Material.MiscDirtyFlag);
  31014. },
  31015. enumerable: true,
  31016. configurable: true
  31017. });
  31018. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31019. /**
  31020. * Gets the back-face culling state.
  31021. */
  31022. get: function () {
  31023. return this._backFaceCulling;
  31024. },
  31025. /**
  31026. * Sets the back-face culling state.
  31027. */
  31028. set: function (value) {
  31029. if (this._backFaceCulling === value) {
  31030. return;
  31031. }
  31032. this._backFaceCulling = value;
  31033. this.markAsDirty(Material.TextureDirtyFlag);
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(Material.prototype, "onDispose", {
  31039. /**
  31040. * Called during a dispose event.
  31041. */
  31042. set: function (callback) {
  31043. if (this._onDisposeObserver) {
  31044. this.onDisposeObservable.remove(this._onDisposeObserver);
  31045. }
  31046. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31047. },
  31048. enumerable: true,
  31049. configurable: true
  31050. });
  31051. Object.defineProperty(Material.prototype, "onBind", {
  31052. /**
  31053. * Called during a bind event.
  31054. */
  31055. set: function (callback) {
  31056. if (this._onBindObserver) {
  31057. this.onBindObservable.remove(this._onBindObserver);
  31058. }
  31059. this._onBindObserver = this.onBindObservable.add(callback);
  31060. },
  31061. enumerable: true,
  31062. configurable: true
  31063. });
  31064. Object.defineProperty(Material.prototype, "alphaMode", {
  31065. /**
  31066. * Gets the value of the alpha mode.
  31067. */
  31068. get: function () {
  31069. return this._alphaMode;
  31070. },
  31071. /**
  31072. * Sets the value of the alpha mode.
  31073. */
  31074. set: function (value) {
  31075. if (this._alphaMode === value) {
  31076. return;
  31077. }
  31078. this._alphaMode = value;
  31079. this.markAsDirty(Material.TextureDirtyFlag);
  31080. },
  31081. enumerable: true,
  31082. configurable: true
  31083. });
  31084. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31085. /**
  31086. * Gets the depth pre-pass value.
  31087. */
  31088. get: function () {
  31089. return this._needDepthPrePass;
  31090. },
  31091. /**
  31092. * Sets the need depth pre-pass value.
  31093. */
  31094. set: function (value) {
  31095. if (this._needDepthPrePass === value) {
  31096. return;
  31097. }
  31098. this._needDepthPrePass = value;
  31099. if (this._needDepthPrePass) {
  31100. this.checkReadyOnEveryCall = true;
  31101. }
  31102. },
  31103. enumerable: true,
  31104. configurable: true
  31105. });
  31106. Object.defineProperty(Material.prototype, "fogEnabled", {
  31107. /**
  31108. * Gets the value of the fog enabled state.
  31109. */
  31110. get: function () {
  31111. return this._fogEnabled;
  31112. },
  31113. /**
  31114. * Sets the state for enabling fog.
  31115. */
  31116. set: function (value) {
  31117. if (this._fogEnabled === value) {
  31118. return;
  31119. }
  31120. this._fogEnabled = value;
  31121. this.markAsDirty(Material.MiscDirtyFlag);
  31122. },
  31123. enumerable: true,
  31124. configurable: true
  31125. });
  31126. Object.defineProperty(Material.prototype, "wireframe", {
  31127. /**
  31128. * Gets a value specifying if wireframe mode is enabled.
  31129. */
  31130. get: function () {
  31131. return this._fillMode === Material.WireFrameFillMode;
  31132. },
  31133. /**
  31134. * Sets the state of wireframe mode.
  31135. */
  31136. set: function (value) {
  31137. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31138. },
  31139. enumerable: true,
  31140. configurable: true
  31141. });
  31142. Object.defineProperty(Material.prototype, "pointsCloud", {
  31143. /**
  31144. * Gets the value specifying if point clouds are enabled.
  31145. */
  31146. get: function () {
  31147. return this._fillMode === Material.PointFillMode;
  31148. },
  31149. /**
  31150. * Sets the state of point cloud mode.
  31151. */
  31152. set: function (value) {
  31153. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(Material.prototype, "fillMode", {
  31159. /**
  31160. * Gets the material fill mode.
  31161. */
  31162. get: function () {
  31163. return this._fillMode;
  31164. },
  31165. /**
  31166. * Sets the material fill mode.
  31167. */
  31168. set: function (value) {
  31169. if (this._fillMode === value) {
  31170. return;
  31171. }
  31172. this._fillMode = value;
  31173. this.markAsDirty(Material.MiscDirtyFlag);
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. /**
  31179. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31180. * subclasses should override adding information pertainent to themselves.
  31181. * @returns - String with material information.
  31182. */
  31183. Material.prototype.toString = function (fullDetails) {
  31184. var ret = "Name: " + this.name;
  31185. if (fullDetails) {
  31186. }
  31187. return ret;
  31188. };
  31189. /**
  31190. * Gets the class name of the material.
  31191. * @returns - String with the class name of the material.
  31192. */
  31193. Material.prototype.getClassName = function () {
  31194. return "Material";
  31195. };
  31196. Object.defineProperty(Material.prototype, "isFrozen", {
  31197. /**
  31198. * Specifies if updates for the material been locked.
  31199. */
  31200. get: function () {
  31201. return this.checkReadyOnlyOnce;
  31202. },
  31203. enumerable: true,
  31204. configurable: true
  31205. });
  31206. /**
  31207. * Locks updates for the material.
  31208. */
  31209. Material.prototype.freeze = function () {
  31210. this.checkReadyOnlyOnce = true;
  31211. };
  31212. /**
  31213. * Unlocks updates for the material.
  31214. */
  31215. Material.prototype.unfreeze = function () {
  31216. this.checkReadyOnlyOnce = false;
  31217. };
  31218. /**
  31219. * Specifies if the material is ready to be used.
  31220. * @param mesh - BJS mesh.
  31221. * @param useInstances - Specifies if instances should be used.
  31222. * @returns - Boolean indicating if the material is ready to be used.
  31223. */
  31224. Material.prototype.isReady = function (mesh, useInstances) {
  31225. return true;
  31226. };
  31227. /**
  31228. * Specifies that the submesh is ready to be used.
  31229. * @param mesh - BJS mesh.
  31230. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31231. * @param useInstances - Specifies that instances should be used.
  31232. * @returns - boolean indicating that the submesh is ready or not.
  31233. */
  31234. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31235. return false;
  31236. };
  31237. /**
  31238. * Returns the material effect.
  31239. * @returns - Nullable material effect.
  31240. */
  31241. Material.prototype.getEffect = function () {
  31242. return this._effect;
  31243. };
  31244. /**
  31245. * Returns the BJS scene.
  31246. * @returns - BJS Scene.
  31247. */
  31248. Material.prototype.getScene = function () {
  31249. return this._scene;
  31250. };
  31251. /**
  31252. * Specifies if the material will require alpha blending
  31253. * @returns - Boolean specifying if alpha blending is needed.
  31254. */
  31255. Material.prototype.needAlphaBlending = function () {
  31256. return (this.alpha < 1.0);
  31257. };
  31258. /**
  31259. * Specifies if the mesh will require alpha blending.
  31260. * @param mesh - BJS mesh.
  31261. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31262. */
  31263. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31264. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31265. };
  31266. /**
  31267. * Specifies if this material should be rendered in alpha test mode.
  31268. * @returns - Boolean specifying if an alpha test is needed.
  31269. */
  31270. Material.prototype.needAlphaTesting = function () {
  31271. return false;
  31272. };
  31273. /**
  31274. * Gets the texture used for the alpha test.
  31275. * @returns - Nullable alpha test texture.
  31276. */
  31277. Material.prototype.getAlphaTestTexture = function () {
  31278. return null;
  31279. };
  31280. /**
  31281. * Marks the material to indicate that it needs to be re-calculated.
  31282. */
  31283. Material.prototype.markDirty = function () {
  31284. this._wasPreviouslyReady = false;
  31285. };
  31286. Material.prototype._preBind = function (effect, overrideOrientation) {
  31287. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31288. var engine = this._scene.getEngine();
  31289. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31290. var reverse = orientation === Material.ClockWiseSideOrientation;
  31291. engine.enableEffect(effect ? effect : this._effect);
  31292. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31293. return reverse;
  31294. };
  31295. /**
  31296. * Binds the material to the mesh.
  31297. * @param world - World transformation matrix.
  31298. * @param mesh - Mesh to bind the material to.
  31299. */
  31300. Material.prototype.bind = function (world, mesh) {
  31301. };
  31302. /**
  31303. * Binds the submesh to the material.
  31304. * @param world - World transformation matrix.
  31305. * @param mesh - Mesh containing the submesh.
  31306. * @param subMesh - Submesh to bind the material to.
  31307. */
  31308. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31309. };
  31310. /**
  31311. * Binds the world matrix to the material.
  31312. * @param world - World transformation matrix.
  31313. */
  31314. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31315. };
  31316. /**
  31317. * Binds the scene's uniform buffer to the effect.
  31318. * @param effect - Effect to bind to the scene uniform buffer.
  31319. * @param sceneUbo - Scene uniform buffer.
  31320. */
  31321. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31322. sceneUbo.bindToEffect(effect, "Scene");
  31323. };
  31324. /**
  31325. * Binds the view matrix to the effect.
  31326. * @param effect - Effect to bind the view matrix to.
  31327. */
  31328. Material.prototype.bindView = function (effect) {
  31329. if (!this._useUBO) {
  31330. effect.setMatrix("view", this.getScene().getViewMatrix());
  31331. }
  31332. else {
  31333. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31334. }
  31335. };
  31336. /**
  31337. * Binds the view projection matrix to the effect.
  31338. * @param effect - Effect to bind the view projection matrix to.
  31339. */
  31340. Material.prototype.bindViewProjection = function (effect) {
  31341. if (!this._useUBO) {
  31342. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31343. }
  31344. else {
  31345. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31346. }
  31347. };
  31348. /**
  31349. * Specifies if material alpha testing should be turned on for the mesh.
  31350. * @param mesh - BJS mesh.
  31351. */
  31352. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31353. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31354. };
  31355. /**
  31356. * Processes to execute after binding the material to a mesh.
  31357. * @param mesh - BJS mesh.
  31358. */
  31359. Material.prototype._afterBind = function (mesh) {
  31360. this._scene._cachedMaterial = this;
  31361. if (mesh) {
  31362. this._scene._cachedVisibility = mesh.visibility;
  31363. }
  31364. else {
  31365. this._scene._cachedVisibility = 1;
  31366. }
  31367. if (mesh) {
  31368. this.onBindObservable.notifyObservers(mesh);
  31369. }
  31370. if (this.disableDepthWrite) {
  31371. var engine = this._scene.getEngine();
  31372. this._cachedDepthWriteState = engine.getDepthWrite();
  31373. engine.setDepthWrite(false);
  31374. }
  31375. };
  31376. /**
  31377. * Unbinds the material from the mesh.
  31378. */
  31379. Material.prototype.unbind = function () {
  31380. this.onUnBindObservable.notifyObservers(this);
  31381. if (this.disableDepthWrite) {
  31382. var engine = this._scene.getEngine();
  31383. engine.setDepthWrite(this._cachedDepthWriteState);
  31384. }
  31385. };
  31386. /**
  31387. * Gets the active textures from the material.
  31388. * @returns - Array of textures.
  31389. */
  31390. Material.prototype.getActiveTextures = function () {
  31391. return [];
  31392. };
  31393. /**
  31394. * Specifies if the material uses a texture.
  31395. * @param texture - Texture to check against the material.
  31396. * @returns - Boolean specifying if the material uses the texture.
  31397. */
  31398. Material.prototype.hasTexture = function (texture) {
  31399. return false;
  31400. };
  31401. /**
  31402. * Makes a duplicate of the material, and gives it a new name.
  31403. * @param name - Name to call the duplicated material.
  31404. * @returns - Nullable cloned material
  31405. */
  31406. Material.prototype.clone = function (name) {
  31407. return null;
  31408. };
  31409. /**
  31410. * Gets the meshes bound to the material.
  31411. * @returns - Array of meshes bound to the material.
  31412. */
  31413. Material.prototype.getBindedMeshes = function () {
  31414. var result = new Array();
  31415. for (var index = 0; index < this._scene.meshes.length; index++) {
  31416. var mesh = this._scene.meshes[index];
  31417. if (mesh.material === this) {
  31418. result.push(mesh);
  31419. }
  31420. }
  31421. return result;
  31422. };
  31423. /**
  31424. * Force shader compilation
  31425. * @param mesh - BJS mesh.
  31426. * @param onCompiled - function to execute once the material is compiled.
  31427. * @param options - options to pass to this function.
  31428. */
  31429. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31430. var _this = this;
  31431. var localOptions = __assign({ clipPlane: false }, options);
  31432. var subMesh = new BABYLON.BaseSubMesh();
  31433. var scene = this.getScene();
  31434. var checkReady = function () {
  31435. if (!_this._scene || !_this._scene.getEngine()) {
  31436. return;
  31437. }
  31438. if (subMesh._materialDefines) {
  31439. subMesh._materialDefines._renderId = -1;
  31440. }
  31441. var clipPlaneState = scene.clipPlane;
  31442. if (localOptions.clipPlane) {
  31443. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31444. }
  31445. if (_this.storeEffectOnSubMeshes) {
  31446. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31447. if (onCompiled) {
  31448. onCompiled(_this);
  31449. }
  31450. }
  31451. else {
  31452. setTimeout(checkReady, 16);
  31453. }
  31454. }
  31455. else {
  31456. if (_this.isReady(mesh)) {
  31457. if (onCompiled) {
  31458. onCompiled(_this);
  31459. }
  31460. }
  31461. else {
  31462. setTimeout(checkReady, 16);
  31463. }
  31464. }
  31465. if (localOptions.clipPlane) {
  31466. scene.clipPlane = clipPlaneState;
  31467. }
  31468. };
  31469. checkReady();
  31470. };
  31471. /**
  31472. * Force shader compilation.
  31473. * @param mesh The mesh that will use this material
  31474. * @param options Additional options for compiling the shaders
  31475. * @returns A promise that resolves when the compilation completes
  31476. */
  31477. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31478. var _this = this;
  31479. return new Promise(function (resolve) {
  31480. _this.forceCompilation(mesh, function () {
  31481. resolve();
  31482. }, options);
  31483. });
  31484. };
  31485. /**
  31486. * Marks a define in the material to indicate that it needs to be re-computed.
  31487. * @param flag - Material define flag.
  31488. */
  31489. Material.prototype.markAsDirty = function (flag) {
  31490. if (flag & Material.TextureDirtyFlag) {
  31491. this._markAllSubMeshesAsTexturesDirty();
  31492. }
  31493. if (flag & Material.LightDirtyFlag) {
  31494. this._markAllSubMeshesAsLightsDirty();
  31495. }
  31496. if (flag & Material.FresnelDirtyFlag) {
  31497. this._markAllSubMeshesAsFresnelDirty();
  31498. }
  31499. if (flag & Material.AttributesDirtyFlag) {
  31500. this._markAllSubMeshesAsAttributesDirty();
  31501. }
  31502. if (flag & Material.MiscDirtyFlag) {
  31503. this._markAllSubMeshesAsMiscDirty();
  31504. }
  31505. this.getScene().resetCachedMaterial();
  31506. };
  31507. /**
  31508. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31509. * @param func - function which checks material defines against the submeshes.
  31510. */
  31511. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31512. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31513. var mesh = _a[_i];
  31514. if (!mesh.subMeshes) {
  31515. continue;
  31516. }
  31517. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31518. var subMesh = _c[_b];
  31519. if (subMesh.getMaterial() !== this) {
  31520. continue;
  31521. }
  31522. if (!subMesh._materialDefines) {
  31523. continue;
  31524. }
  31525. func(subMesh._materialDefines);
  31526. }
  31527. }
  31528. };
  31529. /**
  31530. * Indicates that image processing needs to be re-calculated for all submeshes.
  31531. */
  31532. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31533. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31534. };
  31535. /**
  31536. * Indicates that textures need to be re-calculated for all submeshes.
  31537. */
  31538. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31539. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31540. };
  31541. /**
  31542. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31543. */
  31544. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31545. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31546. };
  31547. /**
  31548. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31549. */
  31550. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31551. this._markAllSubMeshesAsDirty(function (defines) {
  31552. defines.markAsFresnelDirty();
  31553. defines.markAsMiscDirty();
  31554. });
  31555. };
  31556. /**
  31557. * Indicates that lights need to be re-calculated for all submeshes.
  31558. */
  31559. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31560. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31561. };
  31562. /**
  31563. * Indicates that attributes need to be re-calculated for all submeshes.
  31564. */
  31565. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31566. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31567. };
  31568. /**
  31569. * Indicates that misc needs to be re-calculated for all submeshes.
  31570. */
  31571. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31573. };
  31574. /**
  31575. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31576. */
  31577. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31578. this._markAllSubMeshesAsDirty(function (defines) {
  31579. defines.markAsTexturesDirty();
  31580. defines.markAsMiscDirty();
  31581. });
  31582. };
  31583. /**
  31584. * Disposes the material.
  31585. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31586. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31587. */
  31588. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31589. // Animations
  31590. this.getScene().stopAnimation(this);
  31591. // Remove from scene
  31592. var index = this._scene.materials.indexOf(this);
  31593. if (index >= 0) {
  31594. this._scene.materials.splice(index, 1);
  31595. }
  31596. // Remove from meshes
  31597. for (index = 0; index < this._scene.meshes.length; index++) {
  31598. var mesh = this._scene.meshes[index];
  31599. if (mesh.material === this) {
  31600. mesh.material = null;
  31601. if (mesh.geometry) {
  31602. var geometry = (mesh.geometry);
  31603. if (this.storeEffectOnSubMeshes) {
  31604. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31605. var subMesh = _a[_i];
  31606. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31607. if (forceDisposeEffect && subMesh._materialEffect) {
  31608. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31609. }
  31610. }
  31611. }
  31612. else {
  31613. geometry._releaseVertexArrayObject(this._effect);
  31614. }
  31615. }
  31616. }
  31617. }
  31618. this._uniformBuffer.dispose();
  31619. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31620. if (forceDisposeEffect && this._effect) {
  31621. if (!this.storeEffectOnSubMeshes) {
  31622. this._scene.getEngine()._releaseEffect(this._effect);
  31623. }
  31624. this._effect = null;
  31625. }
  31626. // Callback
  31627. this.onDisposeObservable.notifyObservers(this);
  31628. this.onDisposeObservable.clear();
  31629. this.onBindObservable.clear();
  31630. this.onUnBindObservable.clear();
  31631. };
  31632. /**
  31633. * Serializes this material.
  31634. * @returns - serialized material object.
  31635. */
  31636. Material.prototype.serialize = function () {
  31637. return BABYLON.SerializationHelper.Serialize(this);
  31638. };
  31639. /**
  31640. * Creates a MultiMaterial from parse MultiMaterial data.
  31641. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31642. * @param scene - BJS scene.
  31643. * @returns - MultiMaterial.
  31644. */
  31645. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31646. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31647. multiMaterial.id = parsedMultiMaterial.id;
  31648. if (BABYLON.Tags) {
  31649. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31650. }
  31651. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31652. var subMatId = parsedMultiMaterial.materials[matIndex];
  31653. if (subMatId) {
  31654. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31655. }
  31656. else {
  31657. multiMaterial.subMaterials.push(null);
  31658. }
  31659. }
  31660. return multiMaterial;
  31661. };
  31662. /**
  31663. * Creates a material from parsed material data.
  31664. * @param parsedMaterial - Parsed material data.
  31665. * @param scene - BJS scene.
  31666. * @param rootUrl - Root URL containing the material information.
  31667. * @returns - Parsed material.
  31668. */
  31669. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31670. if (!parsedMaterial.customType) {
  31671. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31672. }
  31673. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31674. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31675. if (!BABYLON.LegacyPBRMaterial) {
  31676. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31677. return;
  31678. }
  31679. }
  31680. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31681. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31682. ;
  31683. };
  31684. // Triangle views
  31685. Material._TriangleFillMode = 0;
  31686. Material._WireFrameFillMode = 1;
  31687. Material._PointFillMode = 2;
  31688. // Draw modes
  31689. Material._PointListDrawMode = 3;
  31690. Material._LineListDrawMode = 4;
  31691. Material._LineLoopDrawMode = 5;
  31692. Material._LineStripDrawMode = 6;
  31693. Material._TriangleStripDrawMode = 7;
  31694. Material._TriangleFanDrawMode = 8;
  31695. /**
  31696. * Stores the clock-wise side orientation.
  31697. */
  31698. Material._ClockWiseSideOrientation = 0;
  31699. /**
  31700. * Stores the counter clock-wise side orientation.
  31701. */
  31702. Material._CounterClockWiseSideOrientation = 1;
  31703. /**
  31704. * The dirty texture flag value.
  31705. */
  31706. Material._TextureDirtyFlag = 1;
  31707. /**
  31708. * The dirty light flag value.
  31709. */
  31710. Material._LightDirtyFlag = 2;
  31711. /**
  31712. * The dirty fresnel flag value.
  31713. */
  31714. Material._FresnelDirtyFlag = 4;
  31715. /**
  31716. * The dirty attribute flag value.
  31717. */
  31718. Material._AttributesDirtyFlag = 8;
  31719. /**
  31720. * The dirty misc flag value.
  31721. */
  31722. Material._MiscDirtyFlag = 16;
  31723. __decorate([
  31724. BABYLON.serialize()
  31725. ], Material.prototype, "id", void 0);
  31726. __decorate([
  31727. BABYLON.serialize()
  31728. ], Material.prototype, "name", void 0);
  31729. __decorate([
  31730. BABYLON.serialize()
  31731. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31732. __decorate([
  31733. BABYLON.serialize()
  31734. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31735. __decorate([
  31736. BABYLON.serialize()
  31737. ], Material.prototype, "state", void 0);
  31738. __decorate([
  31739. BABYLON.serialize("alpha")
  31740. ], Material.prototype, "_alpha", void 0);
  31741. __decorate([
  31742. BABYLON.serialize("backFaceCulling")
  31743. ], Material.prototype, "_backFaceCulling", void 0);
  31744. __decorate([
  31745. BABYLON.serialize()
  31746. ], Material.prototype, "sideOrientation", void 0);
  31747. __decorate([
  31748. BABYLON.serialize("alphaMode")
  31749. ], Material.prototype, "_alphaMode", void 0);
  31750. __decorate([
  31751. BABYLON.serialize()
  31752. ], Material.prototype, "_needDepthPrePass", void 0);
  31753. __decorate([
  31754. BABYLON.serialize()
  31755. ], Material.prototype, "disableDepthWrite", void 0);
  31756. __decorate([
  31757. BABYLON.serialize()
  31758. ], Material.prototype, "forceDepthWrite", void 0);
  31759. __decorate([
  31760. BABYLON.serialize()
  31761. ], Material.prototype, "separateCullingPass", void 0);
  31762. __decorate([
  31763. BABYLON.serialize("fogEnabled")
  31764. ], Material.prototype, "_fogEnabled", void 0);
  31765. __decorate([
  31766. BABYLON.serialize()
  31767. ], Material.prototype, "pointSize", void 0);
  31768. __decorate([
  31769. BABYLON.serialize()
  31770. ], Material.prototype, "zOffset", void 0);
  31771. __decorate([
  31772. BABYLON.serialize()
  31773. ], Material.prototype, "wireframe", null);
  31774. __decorate([
  31775. BABYLON.serialize()
  31776. ], Material.prototype, "pointsCloud", null);
  31777. __decorate([
  31778. BABYLON.serialize()
  31779. ], Material.prototype, "fillMode", null);
  31780. return Material;
  31781. }());
  31782. BABYLON.Material = Material;
  31783. })(BABYLON || (BABYLON = {}));
  31784. //# sourceMappingURL=babylon.material.js.map
  31785. var BABYLON;
  31786. (function (BABYLON) {
  31787. var UniformBuffer = /** @class */ (function () {
  31788. /**
  31789. * Uniform buffer objects.
  31790. *
  31791. * Handles blocks of uniform on the GPU.
  31792. *
  31793. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31794. *
  31795. * For more information, please refer to :
  31796. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31797. */
  31798. function UniformBuffer(engine, data, dynamic) {
  31799. this._engine = engine;
  31800. this._noUBO = !engine.supportsUniformBuffers;
  31801. this._dynamic = dynamic;
  31802. this._data = data || [];
  31803. this._uniformLocations = {};
  31804. this._uniformSizes = {};
  31805. this._uniformLocationPointer = 0;
  31806. this._needSync = false;
  31807. if (this._noUBO) {
  31808. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31809. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31810. this.updateFloat = this._updateFloatForEffect;
  31811. this.updateFloat2 = this._updateFloat2ForEffect;
  31812. this.updateFloat3 = this._updateFloat3ForEffect;
  31813. this.updateFloat4 = this._updateFloat4ForEffect;
  31814. this.updateMatrix = this._updateMatrixForEffect;
  31815. this.updateVector3 = this._updateVector3ForEffect;
  31816. this.updateVector4 = this._updateVector4ForEffect;
  31817. this.updateColor3 = this._updateColor3ForEffect;
  31818. this.updateColor4 = this._updateColor4ForEffect;
  31819. }
  31820. else {
  31821. this._engine._uniformBuffers.push(this);
  31822. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31823. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31824. this.updateFloat = this._updateFloatForUniform;
  31825. this.updateFloat2 = this._updateFloat2ForUniform;
  31826. this.updateFloat3 = this._updateFloat3ForUniform;
  31827. this.updateFloat4 = this._updateFloat4ForUniform;
  31828. this.updateMatrix = this._updateMatrixForUniform;
  31829. this.updateVector3 = this._updateVector3ForUniform;
  31830. this.updateVector4 = this._updateVector4ForUniform;
  31831. this.updateColor3 = this._updateColor3ForUniform;
  31832. this.updateColor4 = this._updateColor4ForUniform;
  31833. }
  31834. }
  31835. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31836. // Properties
  31837. /**
  31838. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31839. * or just falling back on setUniformXXX calls.
  31840. */
  31841. get: function () {
  31842. return !this._noUBO;
  31843. },
  31844. enumerable: true,
  31845. configurable: true
  31846. });
  31847. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31848. /**
  31849. * Indicates if the WebGL underlying uniform buffer is in sync
  31850. * with the javascript cache data.
  31851. */
  31852. get: function () {
  31853. return !this._needSync;
  31854. },
  31855. enumerable: true,
  31856. configurable: true
  31857. });
  31858. /**
  31859. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31860. * Also, a dynamic UniformBuffer will disable cache verification and always
  31861. * update the underlying WebGL uniform buffer to the GPU.
  31862. */
  31863. UniformBuffer.prototype.isDynamic = function () {
  31864. return this._dynamic !== undefined;
  31865. };
  31866. /**
  31867. * The data cache on JS side.
  31868. */
  31869. UniformBuffer.prototype.getData = function () {
  31870. return this._bufferData;
  31871. };
  31872. /**
  31873. * The underlying WebGL Uniform buffer.
  31874. */
  31875. UniformBuffer.prototype.getBuffer = function () {
  31876. return this._buffer;
  31877. };
  31878. /**
  31879. * std140 layout specifies how to align data within an UBO structure.
  31880. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31881. * for specs.
  31882. */
  31883. UniformBuffer.prototype._fillAlignment = function (size) {
  31884. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31885. // and 4x4 matrices
  31886. // TODO : change if other types are used
  31887. var alignment;
  31888. if (size <= 2) {
  31889. alignment = size;
  31890. }
  31891. else {
  31892. alignment = 4;
  31893. }
  31894. if ((this._uniformLocationPointer % alignment) !== 0) {
  31895. var oldPointer = this._uniformLocationPointer;
  31896. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31897. var diff = this._uniformLocationPointer - oldPointer;
  31898. for (var i = 0; i < diff; i++) {
  31899. this._data.push(0);
  31900. }
  31901. }
  31902. };
  31903. /**
  31904. * Adds an uniform in the buffer.
  31905. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31906. * for the layout to be correct !
  31907. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31908. * @param {number|number[]} size Data size, or data directly.
  31909. */
  31910. UniformBuffer.prototype.addUniform = function (name, size) {
  31911. if (this._noUBO) {
  31912. return;
  31913. }
  31914. if (this._uniformLocations[name] !== undefined) {
  31915. // Already existing uniform
  31916. return;
  31917. }
  31918. // This function must be called in the order of the shader layout !
  31919. // size can be the size of the uniform, or data directly
  31920. var data;
  31921. if (size instanceof Array) {
  31922. data = size;
  31923. size = data.length;
  31924. }
  31925. else {
  31926. size = size;
  31927. data = [];
  31928. // Fill with zeros
  31929. for (var i = 0; i < size; i++) {
  31930. data.push(0);
  31931. }
  31932. }
  31933. this._fillAlignment(size);
  31934. this._uniformSizes[name] = size;
  31935. this._uniformLocations[name] = this._uniformLocationPointer;
  31936. this._uniformLocationPointer += size;
  31937. for (var i = 0; i < size; i++) {
  31938. this._data.push(data[i]);
  31939. }
  31940. this._needSync = true;
  31941. };
  31942. /**
  31943. * Wrapper for addUniform.
  31944. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31945. * @param {Matrix} mat A 4x4 matrix.
  31946. */
  31947. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31948. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31949. };
  31950. /**
  31951. * Wrapper for addUniform.
  31952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31953. * @param {number} x
  31954. * @param {number} y
  31955. */
  31956. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31957. var temp = [x, y];
  31958. this.addUniform(name, temp);
  31959. };
  31960. /**
  31961. * Wrapper for addUniform.
  31962. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31963. * @param {number} x
  31964. * @param {number} y
  31965. * @param {number} z
  31966. */
  31967. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31968. var temp = [x, y, z];
  31969. this.addUniform(name, temp);
  31970. };
  31971. /**
  31972. * Wrapper for addUniform.
  31973. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31974. * @param {Color3} color
  31975. */
  31976. UniformBuffer.prototype.addColor3 = function (name, color) {
  31977. var temp = new Array();
  31978. color.toArray(temp);
  31979. this.addUniform(name, temp);
  31980. };
  31981. /**
  31982. * Wrapper for addUniform.
  31983. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31984. * @param {Color3} color
  31985. * @param {number} alpha
  31986. */
  31987. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31988. var temp = new Array();
  31989. color.toArray(temp);
  31990. temp.push(alpha);
  31991. this.addUniform(name, temp);
  31992. };
  31993. /**
  31994. * Wrapper for addUniform.
  31995. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31996. * @param {Vector3} vector
  31997. */
  31998. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31999. var temp = new Array();
  32000. vector.toArray(temp);
  32001. this.addUniform(name, temp);
  32002. };
  32003. /**
  32004. * Wrapper for addUniform.
  32005. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32006. */
  32007. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32008. this.addUniform(name, 12);
  32009. };
  32010. /**
  32011. * Wrapper for addUniform.
  32012. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32013. */
  32014. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32015. this.addUniform(name, 8);
  32016. };
  32017. /**
  32018. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32019. */
  32020. UniformBuffer.prototype.create = function () {
  32021. if (this._noUBO) {
  32022. return;
  32023. }
  32024. if (this._buffer) {
  32025. return; // nothing to do
  32026. }
  32027. // See spec, alignment must be filled as a vec4
  32028. this._fillAlignment(4);
  32029. this._bufferData = new Float32Array(this._data);
  32030. this._rebuild();
  32031. this._needSync = true;
  32032. };
  32033. UniformBuffer.prototype._rebuild = function () {
  32034. if (this._noUBO) {
  32035. return;
  32036. }
  32037. if (this._dynamic) {
  32038. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32039. }
  32040. else {
  32041. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32042. }
  32043. };
  32044. /**
  32045. * Updates the WebGL Uniform Buffer on the GPU.
  32046. * If the `dynamic` flag is set to true, no cache comparison is done.
  32047. * Otherwise, the buffer will be updated only if the cache differs.
  32048. */
  32049. UniformBuffer.prototype.update = function () {
  32050. if (!this._buffer) {
  32051. this.create();
  32052. return;
  32053. }
  32054. if (!this._dynamic && !this._needSync) {
  32055. return;
  32056. }
  32057. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32058. this._needSync = false;
  32059. };
  32060. /**
  32061. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32062. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32063. * @param {number[]|Float32Array} data Flattened data
  32064. * @param {number} size Size of the data.
  32065. */
  32066. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32067. var location = this._uniformLocations[uniformName];
  32068. if (location === undefined) {
  32069. if (this._buffer) {
  32070. // Cannot add an uniform if the buffer is already created
  32071. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32072. return;
  32073. }
  32074. this.addUniform(uniformName, size);
  32075. location = this._uniformLocations[uniformName];
  32076. }
  32077. if (!this._buffer) {
  32078. this.create();
  32079. }
  32080. if (!this._dynamic) {
  32081. // Cache for static uniform buffers
  32082. var changed = false;
  32083. for (var i = 0; i < size; i++) {
  32084. if (this._bufferData[location + i] !== data[i]) {
  32085. changed = true;
  32086. this._bufferData[location + i] = data[i];
  32087. }
  32088. }
  32089. this._needSync = this._needSync || changed;
  32090. }
  32091. else {
  32092. // No cache for dynamic
  32093. for (var i = 0; i < size; i++) {
  32094. this._bufferData[location + i] = data[i];
  32095. }
  32096. }
  32097. };
  32098. // Update methods
  32099. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32100. // To match std140, matrix must be realigned
  32101. for (var i = 0; i < 3; i++) {
  32102. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32103. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32104. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32105. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32106. }
  32107. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32108. };
  32109. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32110. this._currentEffect.setMatrix3x3(name, matrix);
  32111. };
  32112. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32113. this._currentEffect.setMatrix2x2(name, matrix);
  32114. };
  32115. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32116. // To match std140, matrix must be realigned
  32117. for (var i = 0; i < 2; i++) {
  32118. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32119. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32120. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32121. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32122. }
  32123. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32124. };
  32125. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32126. this._currentEffect.setFloat(name, x);
  32127. };
  32128. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32129. UniformBuffer._tempBuffer[0] = x;
  32130. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32131. };
  32132. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32133. if (suffix === void 0) { suffix = ""; }
  32134. this._currentEffect.setFloat2(name + suffix, x, y);
  32135. };
  32136. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. UniformBuffer._tempBuffer[0] = x;
  32139. UniformBuffer._tempBuffer[1] = y;
  32140. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32141. };
  32142. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32143. if (suffix === void 0) { suffix = ""; }
  32144. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32145. };
  32146. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32147. if (suffix === void 0) { suffix = ""; }
  32148. UniformBuffer._tempBuffer[0] = x;
  32149. UniformBuffer._tempBuffer[1] = y;
  32150. UniformBuffer._tempBuffer[2] = z;
  32151. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32152. };
  32153. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32154. if (suffix === void 0) { suffix = ""; }
  32155. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32156. };
  32157. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32158. if (suffix === void 0) { suffix = ""; }
  32159. UniformBuffer._tempBuffer[0] = x;
  32160. UniformBuffer._tempBuffer[1] = y;
  32161. UniformBuffer._tempBuffer[2] = z;
  32162. UniformBuffer._tempBuffer[3] = w;
  32163. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32164. };
  32165. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32166. this._currentEffect.setMatrix(name, mat);
  32167. };
  32168. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32169. this.updateUniform(name, mat.toArray(), 16);
  32170. };
  32171. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32172. this._currentEffect.setVector3(name, vector);
  32173. };
  32174. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32175. vector.toArray(UniformBuffer._tempBuffer);
  32176. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32177. };
  32178. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32179. this._currentEffect.setVector4(name, vector);
  32180. };
  32181. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32182. vector.toArray(UniformBuffer._tempBuffer);
  32183. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32184. };
  32185. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32186. if (suffix === void 0) { suffix = ""; }
  32187. this._currentEffect.setColor3(name + suffix, color);
  32188. };
  32189. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32190. if (suffix === void 0) { suffix = ""; }
  32191. color.toArray(UniformBuffer._tempBuffer);
  32192. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32193. };
  32194. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32195. if (suffix === void 0) { suffix = ""; }
  32196. this._currentEffect.setColor4(name + suffix, color, alpha);
  32197. };
  32198. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32199. if (suffix === void 0) { suffix = ""; }
  32200. color.toArray(UniformBuffer._tempBuffer);
  32201. UniformBuffer._tempBuffer[3] = alpha;
  32202. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32203. };
  32204. /**
  32205. * Sets a sampler uniform on the effect.
  32206. * @param {string} name Name of the sampler.
  32207. * @param {Texture} texture
  32208. */
  32209. UniformBuffer.prototype.setTexture = function (name, texture) {
  32210. this._currentEffect.setTexture(name, texture);
  32211. };
  32212. /**
  32213. * Directly updates the value of the uniform in the cache AND on the GPU.
  32214. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32215. * @param {number[]|Float32Array} data Flattened data
  32216. */
  32217. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32218. this.updateUniform(uniformName, data, data.length);
  32219. this.update();
  32220. };
  32221. /**
  32222. * Binds this uniform buffer to an effect.
  32223. * @param {Effect} effect
  32224. * @param {string} name Name of the uniform block in the shader.
  32225. */
  32226. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32227. this._currentEffect = effect;
  32228. if (this._noUBO || !this._buffer) {
  32229. return;
  32230. }
  32231. effect.bindUniformBuffer(this._buffer, name);
  32232. };
  32233. /**
  32234. * Disposes the uniform buffer.
  32235. */
  32236. UniformBuffer.prototype.dispose = function () {
  32237. if (this._noUBO) {
  32238. return;
  32239. }
  32240. var index = this._engine._uniformBuffers.indexOf(this);
  32241. if (index !== -1) {
  32242. this._engine._uniformBuffers.splice(index, 1);
  32243. }
  32244. if (!this._buffer) {
  32245. return;
  32246. }
  32247. if (this._engine._releaseBuffer(this._buffer)) {
  32248. this._buffer = null;
  32249. }
  32250. };
  32251. // Pool for avoiding memory leaks
  32252. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32253. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32254. return UniformBuffer;
  32255. }());
  32256. BABYLON.UniformBuffer = UniformBuffer;
  32257. })(BABYLON || (BABYLON = {}));
  32258. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32259. var BABYLON;
  32260. (function (BABYLON) {
  32261. var VertexData = /** @class */ (function () {
  32262. function VertexData() {
  32263. }
  32264. VertexData.prototype.set = function (data, kind) {
  32265. switch (kind) {
  32266. case BABYLON.VertexBuffer.PositionKind:
  32267. this.positions = data;
  32268. break;
  32269. case BABYLON.VertexBuffer.NormalKind:
  32270. this.normals = data;
  32271. break;
  32272. case BABYLON.VertexBuffer.TangentKind:
  32273. this.tangents = data;
  32274. break;
  32275. case BABYLON.VertexBuffer.UVKind:
  32276. this.uvs = data;
  32277. break;
  32278. case BABYLON.VertexBuffer.UV2Kind:
  32279. this.uvs2 = data;
  32280. break;
  32281. case BABYLON.VertexBuffer.UV3Kind:
  32282. this.uvs3 = data;
  32283. break;
  32284. case BABYLON.VertexBuffer.UV4Kind:
  32285. this.uvs4 = data;
  32286. break;
  32287. case BABYLON.VertexBuffer.UV5Kind:
  32288. this.uvs5 = data;
  32289. break;
  32290. case BABYLON.VertexBuffer.UV6Kind:
  32291. this.uvs6 = data;
  32292. break;
  32293. case BABYLON.VertexBuffer.ColorKind:
  32294. this.colors = data;
  32295. break;
  32296. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32297. this.matricesIndices = data;
  32298. break;
  32299. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32300. this.matricesWeights = data;
  32301. break;
  32302. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32303. this.matricesIndicesExtra = data;
  32304. break;
  32305. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32306. this.matricesWeightsExtra = data;
  32307. break;
  32308. }
  32309. };
  32310. /**
  32311. * Associates the vertexData to the passed Mesh.
  32312. * Sets it as updatable or not (default `false`).
  32313. * Returns the VertexData.
  32314. */
  32315. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32316. this._applyTo(mesh, updatable);
  32317. return this;
  32318. };
  32319. /**
  32320. * Associates the vertexData to the passed Geometry.
  32321. * Sets it as updatable or not (default `false`).
  32322. * Returns the VertexData.
  32323. */
  32324. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32325. this._applyTo(geometry, updatable);
  32326. return this;
  32327. };
  32328. /**
  32329. * Updates the associated mesh.
  32330. * Returns the VertexData.
  32331. */
  32332. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32333. this._update(mesh);
  32334. return this;
  32335. };
  32336. /**
  32337. * Updates the associated geometry.
  32338. * Returns the VertexData.
  32339. */
  32340. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32341. this._update(geometry);
  32342. return this;
  32343. };
  32344. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32345. if (updatable === void 0) { updatable = false; }
  32346. if (this.positions) {
  32347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32348. }
  32349. if (this.normals) {
  32350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32351. }
  32352. if (this.tangents) {
  32353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32354. }
  32355. if (this.uvs) {
  32356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32357. }
  32358. if (this.uvs2) {
  32359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32360. }
  32361. if (this.uvs3) {
  32362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32363. }
  32364. if (this.uvs4) {
  32365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32366. }
  32367. if (this.uvs5) {
  32368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32369. }
  32370. if (this.uvs6) {
  32371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32372. }
  32373. if (this.colors) {
  32374. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32375. }
  32376. if (this.matricesIndices) {
  32377. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32378. }
  32379. if (this.matricesWeights) {
  32380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32381. }
  32382. if (this.matricesIndicesExtra) {
  32383. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32384. }
  32385. if (this.matricesWeightsExtra) {
  32386. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32387. }
  32388. if (this.indices) {
  32389. meshOrGeometry.setIndices(this.indices, null, updatable);
  32390. }
  32391. return this;
  32392. };
  32393. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32394. if (this.positions) {
  32395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32396. }
  32397. if (this.normals) {
  32398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32399. }
  32400. if (this.tangents) {
  32401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32402. }
  32403. if (this.uvs) {
  32404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32405. }
  32406. if (this.uvs2) {
  32407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32408. }
  32409. if (this.uvs3) {
  32410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32411. }
  32412. if (this.uvs4) {
  32413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32414. }
  32415. if (this.uvs5) {
  32416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32417. }
  32418. if (this.uvs6) {
  32419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32420. }
  32421. if (this.colors) {
  32422. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32423. }
  32424. if (this.matricesIndices) {
  32425. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32426. }
  32427. if (this.matricesWeights) {
  32428. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32429. }
  32430. if (this.matricesIndicesExtra) {
  32431. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32432. }
  32433. if (this.matricesWeightsExtra) {
  32434. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32435. }
  32436. if (this.indices) {
  32437. meshOrGeometry.setIndices(this.indices, null);
  32438. }
  32439. return this;
  32440. };
  32441. /**
  32442. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32443. * Returns the VertexData.
  32444. */
  32445. VertexData.prototype.transform = function (matrix) {
  32446. var transformed = BABYLON.Vector3.Zero();
  32447. var index;
  32448. if (this.positions) {
  32449. var position = BABYLON.Vector3.Zero();
  32450. for (index = 0; index < this.positions.length; index += 3) {
  32451. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32452. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32453. this.positions[index] = transformed.x;
  32454. this.positions[index + 1] = transformed.y;
  32455. this.positions[index + 2] = transformed.z;
  32456. }
  32457. }
  32458. if (this.normals) {
  32459. var normal = BABYLON.Vector3.Zero();
  32460. for (index = 0; index < this.normals.length; index += 3) {
  32461. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32462. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32463. this.normals[index] = transformed.x;
  32464. this.normals[index + 1] = transformed.y;
  32465. this.normals[index + 2] = transformed.z;
  32466. }
  32467. }
  32468. if (this.tangents) {
  32469. var tangent = BABYLON.Vector4.Zero();
  32470. var tangentTransformed = BABYLON.Vector4.Zero();
  32471. for (index = 0; index < this.tangents.length; index += 4) {
  32472. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32473. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32474. this.tangents[index] = tangentTransformed.x;
  32475. this.tangents[index + 1] = tangentTransformed.y;
  32476. this.tangents[index + 2] = tangentTransformed.z;
  32477. this.tangents[index + 3] = tangentTransformed.w;
  32478. }
  32479. }
  32480. return this;
  32481. };
  32482. /**
  32483. * Merges the passed VertexData into the current one.
  32484. * Returns the modified VertexData.
  32485. */
  32486. VertexData.prototype.merge = function (other) {
  32487. this._validate();
  32488. other._validate();
  32489. if (!this.normals !== !other.normals ||
  32490. !this.tangents !== !other.tangents ||
  32491. !this.uvs !== !other.uvs ||
  32492. !this.uvs2 !== !other.uvs2 ||
  32493. !this.uvs3 !== !other.uvs3 ||
  32494. !this.uvs4 !== !other.uvs4 ||
  32495. !this.uvs5 !== !other.uvs5 ||
  32496. !this.uvs6 !== !other.uvs6 ||
  32497. !this.colors !== !other.colors ||
  32498. !this.matricesIndices !== !other.matricesIndices ||
  32499. !this.matricesWeights !== !other.matricesWeights ||
  32500. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32501. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32502. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32503. }
  32504. if (other.indices) {
  32505. if (!this.indices) {
  32506. this.indices = [];
  32507. }
  32508. var offset = this.positions ? this.positions.length / 3 : 0;
  32509. for (var index = 0; index < other.indices.length; index++) {
  32510. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32511. this.indices.push(other.indices[index] + offset);
  32512. }
  32513. }
  32514. this.positions = this._mergeElement(this.positions, other.positions);
  32515. this.normals = this._mergeElement(this.normals, other.normals);
  32516. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32517. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32518. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32519. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32520. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32521. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32522. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32523. this.colors = this._mergeElement(this.colors, other.colors);
  32524. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32525. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32526. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32527. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32528. return this;
  32529. };
  32530. VertexData.prototype._mergeElement = function (source, other) {
  32531. if (!source) {
  32532. return other;
  32533. }
  32534. if (!other) {
  32535. return source;
  32536. }
  32537. var len = other.length + source.length;
  32538. var isSrcTypedArray = source instanceof Float32Array;
  32539. var isOthTypedArray = other instanceof Float32Array;
  32540. // use non-loop method when the source is Float32Array
  32541. if (isSrcTypedArray) {
  32542. var ret32 = new Float32Array(len);
  32543. ret32.set(source);
  32544. ret32.set(other, source.length);
  32545. return ret32;
  32546. // source is number[], when other is also use concat
  32547. }
  32548. else if (!isOthTypedArray) {
  32549. return source.concat(other);
  32550. // source is a number[], but other is a Float32Array, loop required
  32551. }
  32552. else {
  32553. var ret = source.slice(0); // copy source to a separate array
  32554. for (var i = 0, len = other.length; i < len; i++) {
  32555. ret.push(other[i]);
  32556. }
  32557. return ret;
  32558. }
  32559. };
  32560. VertexData.prototype._validate = function () {
  32561. if (!this.positions) {
  32562. throw new Error("Positions are required");
  32563. }
  32564. var getElementCount = function (kind, values) {
  32565. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32566. if ((values.length % stride) !== 0) {
  32567. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32568. }
  32569. return values.length / stride;
  32570. };
  32571. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32572. var validateElementCount = function (kind, values) {
  32573. var elementCount = getElementCount(kind, values);
  32574. if (elementCount !== positionsElementCount) {
  32575. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32576. }
  32577. };
  32578. if (this.normals)
  32579. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32580. if (this.tangents)
  32581. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32582. if (this.uvs)
  32583. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32584. if (this.uvs2)
  32585. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32586. if (this.uvs3)
  32587. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32588. if (this.uvs4)
  32589. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32590. if (this.uvs5)
  32591. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32592. if (this.uvs6)
  32593. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32594. if (this.colors)
  32595. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32596. if (this.matricesIndices)
  32597. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32598. if (this.matricesWeights)
  32599. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32600. if (this.matricesIndicesExtra)
  32601. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32602. if (this.matricesWeightsExtra)
  32603. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32604. };
  32605. /**
  32606. * Serializes the VertexData.
  32607. * Returns a serialized object.
  32608. */
  32609. VertexData.prototype.serialize = function () {
  32610. var serializationObject = this.serialize();
  32611. if (this.positions) {
  32612. serializationObject.positions = this.positions;
  32613. }
  32614. if (this.normals) {
  32615. serializationObject.normals = this.normals;
  32616. }
  32617. if (this.tangents) {
  32618. serializationObject.tangents = this.tangents;
  32619. }
  32620. if (this.uvs) {
  32621. serializationObject.uvs = this.uvs;
  32622. }
  32623. if (this.uvs2) {
  32624. serializationObject.uvs2 = this.uvs2;
  32625. }
  32626. if (this.uvs3) {
  32627. serializationObject.uvs3 = this.uvs3;
  32628. }
  32629. if (this.uvs4) {
  32630. serializationObject.uvs4 = this.uvs4;
  32631. }
  32632. if (this.uvs5) {
  32633. serializationObject.uvs5 = this.uvs5;
  32634. }
  32635. if (this.uvs6) {
  32636. serializationObject.uvs6 = this.uvs6;
  32637. }
  32638. if (this.colors) {
  32639. serializationObject.colors = this.colors;
  32640. }
  32641. if (this.matricesIndices) {
  32642. serializationObject.matricesIndices = this.matricesIndices;
  32643. serializationObject.matricesIndices._isExpanded = true;
  32644. }
  32645. if (this.matricesWeights) {
  32646. serializationObject.matricesWeights = this.matricesWeights;
  32647. }
  32648. if (this.matricesIndicesExtra) {
  32649. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32650. serializationObject.matricesIndicesExtra._isExpanded = true;
  32651. }
  32652. if (this.matricesWeightsExtra) {
  32653. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32654. }
  32655. serializationObject.indices = this.indices;
  32656. return serializationObject;
  32657. };
  32658. // Statics
  32659. /**
  32660. * Returns the object VertexData associated to the passed mesh.
  32661. */
  32662. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32663. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32664. };
  32665. /**
  32666. * Returns the object VertexData associated to the passed geometry.
  32667. */
  32668. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32669. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32670. };
  32671. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32672. var result = new VertexData();
  32673. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32674. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32675. }
  32676. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32677. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32678. }
  32679. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32680. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32681. }
  32682. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32683. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32684. }
  32685. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32686. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32687. }
  32688. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32689. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32690. }
  32691. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32692. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32693. }
  32694. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32695. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32696. }
  32697. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32698. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32699. }
  32700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32701. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32702. }
  32703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32704. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32705. }
  32706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32707. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32708. }
  32709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32710. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32711. }
  32712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32713. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32714. }
  32715. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32716. return result;
  32717. };
  32718. /**
  32719. * Creates the vertexData of the Ribbon.
  32720. */
  32721. VertexData.CreateRibbon = function (options) {
  32722. var pathArray = options.pathArray;
  32723. var closeArray = options.closeArray || false;
  32724. var closePath = options.closePath || false;
  32725. var invertUV = options.invertUV || false;
  32726. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32727. var offset = options.offset || defaultOffset;
  32728. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32729. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32730. var customUV = options.uvs;
  32731. var customColors = options.colors;
  32732. var positions = [];
  32733. var indices = [];
  32734. var normals = [];
  32735. var uvs = [];
  32736. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32737. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32738. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32739. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32740. var minlg; // minimal length among all paths from pathArray
  32741. var lg = []; // array of path lengths : nb of vertex per path
  32742. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32743. var p; // path iterator
  32744. var i; // point iterator
  32745. var j; // point iterator
  32746. // if single path in pathArray
  32747. if (pathArray.length < 2) {
  32748. var ar1 = [];
  32749. var ar2 = [];
  32750. for (i = 0; i < pathArray[0].length - offset; i++) {
  32751. ar1.push(pathArray[0][i]);
  32752. ar2.push(pathArray[0][i + offset]);
  32753. }
  32754. pathArray = [ar1, ar2];
  32755. }
  32756. // positions and horizontal distances (u)
  32757. var idc = 0;
  32758. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32759. var path;
  32760. var l;
  32761. minlg = pathArray[0].length;
  32762. var vectlg;
  32763. var dist;
  32764. for (p = 0; p < pathArray.length; p++) {
  32765. uTotalDistance[p] = 0;
  32766. us[p] = [0];
  32767. path = pathArray[p];
  32768. l = path.length;
  32769. minlg = (minlg < l) ? minlg : l;
  32770. j = 0;
  32771. while (j < l) {
  32772. positions.push(path[j].x, path[j].y, path[j].z);
  32773. if (j > 0) {
  32774. vectlg = path[j].subtract(path[j - 1]).length();
  32775. dist = vectlg + uTotalDistance[p];
  32776. us[p].push(dist);
  32777. uTotalDistance[p] = dist;
  32778. }
  32779. j++;
  32780. }
  32781. if (closePath) {
  32782. j--;
  32783. positions.push(path[0].x, path[0].y, path[0].z);
  32784. vectlg = path[j].subtract(path[0]).length();
  32785. dist = vectlg + uTotalDistance[p];
  32786. us[p].push(dist);
  32787. uTotalDistance[p] = dist;
  32788. }
  32789. lg[p] = l + closePathCorr;
  32790. idx[p] = idc;
  32791. idc += (l + closePathCorr);
  32792. }
  32793. // vertical distances (v)
  32794. var path1;
  32795. var path2;
  32796. var vertex1 = null;
  32797. var vertex2 = null;
  32798. for (i = 0; i < minlg + closePathCorr; i++) {
  32799. vTotalDistance[i] = 0;
  32800. vs[i] = [0];
  32801. for (p = 0; p < pathArray.length - 1; p++) {
  32802. path1 = pathArray[p];
  32803. path2 = pathArray[p + 1];
  32804. if (i === minlg) {
  32805. vertex1 = path1[0];
  32806. vertex2 = path2[0];
  32807. }
  32808. else {
  32809. vertex1 = path1[i];
  32810. vertex2 = path2[i];
  32811. }
  32812. vectlg = vertex2.subtract(vertex1).length();
  32813. dist = vectlg + vTotalDistance[i];
  32814. vs[i].push(dist);
  32815. vTotalDistance[i] = dist;
  32816. }
  32817. if (closeArray && vertex2 && vertex1) {
  32818. path1 = pathArray[p];
  32819. path2 = pathArray[0];
  32820. if (i === minlg) {
  32821. vertex2 = path2[0];
  32822. }
  32823. vectlg = vertex2.subtract(vertex1).length();
  32824. dist = vectlg + vTotalDistance[i];
  32825. vTotalDistance[i] = dist;
  32826. }
  32827. }
  32828. // uvs
  32829. var u;
  32830. var v;
  32831. if (customUV) {
  32832. for (p = 0; p < customUV.length; p++) {
  32833. uvs.push(customUV[p].x, customUV[p].y);
  32834. }
  32835. }
  32836. else {
  32837. for (p = 0; p < pathArray.length; p++) {
  32838. for (i = 0; i < minlg + closePathCorr; i++) {
  32839. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32840. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32841. if (invertUV) {
  32842. uvs.push(v, u);
  32843. }
  32844. else {
  32845. uvs.push(u, v);
  32846. }
  32847. }
  32848. }
  32849. }
  32850. // indices
  32851. p = 0; // path index
  32852. var pi = 0; // positions array index
  32853. var l1 = lg[p] - 1; // path1 length
  32854. var l2 = lg[p + 1] - 1; // path2 length
  32855. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32856. var shft = idx[1] - idx[0]; // shift
  32857. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32858. while (pi <= min && p < path1nb) {
  32859. // 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
  32860. indices.push(pi, pi + shft, pi + 1);
  32861. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32862. pi += 1;
  32863. if (pi === min) {
  32864. p++;
  32865. if (p === lg.length - 1) {
  32866. shft = idx[0] - idx[p];
  32867. l1 = lg[p] - 1;
  32868. l2 = lg[0] - 1;
  32869. }
  32870. else {
  32871. shft = idx[p + 1] - idx[p];
  32872. l1 = lg[p] - 1;
  32873. l2 = lg[p + 1] - 1;
  32874. }
  32875. pi = idx[p];
  32876. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32877. }
  32878. }
  32879. // normals
  32880. VertexData.ComputeNormals(positions, indices, normals);
  32881. if (closePath) {
  32882. var indexFirst = 0;
  32883. var indexLast = 0;
  32884. for (p = 0; p < pathArray.length; p++) {
  32885. indexFirst = idx[p] * 3;
  32886. if (p + 1 < pathArray.length) {
  32887. indexLast = (idx[p + 1] - 1) * 3;
  32888. }
  32889. else {
  32890. indexLast = normals.length - 3;
  32891. }
  32892. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32893. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32894. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32895. normals[indexLast] = normals[indexFirst];
  32896. normals[indexLast + 1] = normals[indexFirst + 1];
  32897. normals[indexLast + 2] = normals[indexFirst + 2];
  32898. }
  32899. }
  32900. // sides
  32901. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32902. // Colors
  32903. var colors = null;
  32904. if (customColors) {
  32905. colors = new Float32Array(customColors.length * 4);
  32906. for (var c = 0; c < customColors.length; c++) {
  32907. colors[c * 4] = customColors[c].r;
  32908. colors[c * 4 + 1] = customColors[c].g;
  32909. colors[c * 4 + 2] = customColors[c].b;
  32910. colors[c * 4 + 3] = customColors[c].a;
  32911. }
  32912. }
  32913. // Result
  32914. var vertexData = new VertexData();
  32915. var positions32 = new Float32Array(positions);
  32916. var normals32 = new Float32Array(normals);
  32917. var uvs32 = new Float32Array(uvs);
  32918. vertexData.indices = indices;
  32919. vertexData.positions = positions32;
  32920. vertexData.normals = normals32;
  32921. vertexData.uvs = uvs32;
  32922. if (colors) {
  32923. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32924. }
  32925. if (closePath) {
  32926. vertexData._idx = idx;
  32927. }
  32928. return vertexData;
  32929. };
  32930. /**
  32931. * Creates the VertexData of the Box.
  32932. */
  32933. VertexData.CreateBox = function (options) {
  32934. var normalsSource = [
  32935. new BABYLON.Vector3(0, 0, 1),
  32936. new BABYLON.Vector3(0, 0, -1),
  32937. new BABYLON.Vector3(1, 0, 0),
  32938. new BABYLON.Vector3(-1, 0, 0),
  32939. new BABYLON.Vector3(0, 1, 0),
  32940. new BABYLON.Vector3(0, -1, 0)
  32941. ];
  32942. var indices = [];
  32943. var positions = [];
  32944. var normals = [];
  32945. var uvs = [];
  32946. var width = options.width || options.size || 1;
  32947. var height = options.height || options.size || 1;
  32948. var depth = options.depth || options.size || 1;
  32949. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32950. var faceUV = options.faceUV || new Array(6);
  32951. var faceColors = options.faceColors;
  32952. var colors = [];
  32953. // default face colors and UV if undefined
  32954. for (var f = 0; f < 6; f++) {
  32955. if (faceUV[f] === undefined) {
  32956. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32957. }
  32958. if (faceColors && faceColors[f] === undefined) {
  32959. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32960. }
  32961. }
  32962. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32963. // Create each face in turn.
  32964. for (var index = 0; index < normalsSource.length; index++) {
  32965. var normal = normalsSource[index];
  32966. // Get two vectors perpendicular to the face normal and to each other.
  32967. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32968. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32969. // Six indices (two triangles) per face.
  32970. var verticesLength = positions.length / 3;
  32971. indices.push(verticesLength);
  32972. indices.push(verticesLength + 1);
  32973. indices.push(verticesLength + 2);
  32974. indices.push(verticesLength);
  32975. indices.push(verticesLength + 2);
  32976. indices.push(verticesLength + 3);
  32977. // Four vertices per face.
  32978. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32979. positions.push(vertex.x, vertex.y, vertex.z);
  32980. normals.push(normal.x, normal.y, normal.z);
  32981. uvs.push(faceUV[index].z, faceUV[index].w);
  32982. if (faceColors) {
  32983. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32984. }
  32985. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32986. positions.push(vertex.x, vertex.y, vertex.z);
  32987. normals.push(normal.x, normal.y, normal.z);
  32988. uvs.push(faceUV[index].x, faceUV[index].w);
  32989. if (faceColors) {
  32990. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32991. }
  32992. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32993. positions.push(vertex.x, vertex.y, vertex.z);
  32994. normals.push(normal.x, normal.y, normal.z);
  32995. uvs.push(faceUV[index].x, faceUV[index].y);
  32996. if (faceColors) {
  32997. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32998. }
  32999. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33000. positions.push(vertex.x, vertex.y, vertex.z);
  33001. normals.push(normal.x, normal.y, normal.z);
  33002. uvs.push(faceUV[index].z, faceUV[index].y);
  33003. if (faceColors) {
  33004. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33005. }
  33006. }
  33007. // sides
  33008. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33009. // Result
  33010. var vertexData = new VertexData();
  33011. vertexData.indices = indices;
  33012. vertexData.positions = positions;
  33013. vertexData.normals = normals;
  33014. vertexData.uvs = uvs;
  33015. if (faceColors) {
  33016. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33017. vertexData.colors = totalColors;
  33018. }
  33019. return vertexData;
  33020. };
  33021. /**
  33022. * Creates the VertexData of the Sphere.
  33023. */
  33024. VertexData.CreateSphere = function (options) {
  33025. var segments = options.segments || 32;
  33026. var diameterX = options.diameterX || options.diameter || 1;
  33027. var diameterY = options.diameterY || options.diameter || 1;
  33028. var diameterZ = options.diameterZ || options.diameter || 1;
  33029. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33030. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33031. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33032. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33033. var totalZRotationSteps = 2 + segments;
  33034. var totalYRotationSteps = 2 * totalZRotationSteps;
  33035. var indices = [];
  33036. var positions = [];
  33037. var normals = [];
  33038. var uvs = [];
  33039. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33040. var normalizedZ = zRotationStep / totalZRotationSteps;
  33041. var angleZ = normalizedZ * Math.PI * slice;
  33042. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33043. var normalizedY = yRotationStep / totalYRotationSteps;
  33044. var angleY = normalizedY * Math.PI * 2 * arc;
  33045. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33046. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33047. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33048. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33049. var vertex = complete.multiply(radius);
  33050. var normal = complete.divide(radius).normalize();
  33051. positions.push(vertex.x, vertex.y, vertex.z);
  33052. normals.push(normal.x, normal.y, normal.z);
  33053. uvs.push(normalizedY, normalizedZ);
  33054. }
  33055. if (zRotationStep > 0) {
  33056. var verticesCount = positions.length / 3;
  33057. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33058. indices.push((firstIndex));
  33059. indices.push((firstIndex + 1));
  33060. indices.push(firstIndex + totalYRotationSteps + 1);
  33061. indices.push((firstIndex + totalYRotationSteps + 1));
  33062. indices.push((firstIndex + 1));
  33063. indices.push((firstIndex + totalYRotationSteps + 2));
  33064. }
  33065. }
  33066. }
  33067. // Sides
  33068. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33069. // Result
  33070. var vertexData = new VertexData();
  33071. vertexData.indices = indices;
  33072. vertexData.positions = positions;
  33073. vertexData.normals = normals;
  33074. vertexData.uvs = uvs;
  33075. return vertexData;
  33076. };
  33077. /**
  33078. * Creates the VertexData of the Cylinder or Cone.
  33079. */
  33080. VertexData.CreateCylinder = function (options) {
  33081. var height = options.height || 2;
  33082. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33083. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33084. var tessellation = options.tessellation || 24;
  33085. var subdivisions = options.subdivisions || 1;
  33086. var hasRings = options.hasRings ? true : false;
  33087. var enclose = options.enclose ? true : false;
  33088. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33089. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33090. var faceUV = options.faceUV || new Array(3);
  33091. var faceColors = options.faceColors;
  33092. // default face colors and UV if undefined
  33093. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33094. var ringNb = (hasRings) ? subdivisions : 1;
  33095. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33096. var f;
  33097. for (f = 0; f < surfaceNb; f++) {
  33098. if (faceColors && faceColors[f] === undefined) {
  33099. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33100. }
  33101. }
  33102. for (f = 0; f < surfaceNb; f++) {
  33103. if (faceUV && faceUV[f] === undefined) {
  33104. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33105. }
  33106. }
  33107. var indices = new Array();
  33108. var positions = new Array();
  33109. var normals = new Array();
  33110. var uvs = new Array();
  33111. var colors = new Array();
  33112. var angle_step = Math.PI * 2 * arc / tessellation;
  33113. var angle;
  33114. var h;
  33115. var radius;
  33116. var tan = (diameterBottom - diameterTop) / 2 / height;
  33117. var ringVertex = BABYLON.Vector3.Zero();
  33118. var ringNormal = BABYLON.Vector3.Zero();
  33119. var ringFirstVertex = BABYLON.Vector3.Zero();
  33120. var ringFirstNormal = BABYLON.Vector3.Zero();
  33121. var quadNormal = BABYLON.Vector3.Zero();
  33122. var Y = BABYLON.Axis.Y;
  33123. // positions, normals, uvs
  33124. var i;
  33125. var j;
  33126. var r;
  33127. var ringIdx = 1;
  33128. var s = 1; // surface index
  33129. var cs = 0;
  33130. var v = 0;
  33131. for (i = 0; i <= subdivisions; i++) {
  33132. h = i / subdivisions;
  33133. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33134. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33135. for (r = 0; r < ringIdx; r++) {
  33136. if (hasRings) {
  33137. s += r;
  33138. }
  33139. if (enclose) {
  33140. s += 2 * r;
  33141. }
  33142. for (j = 0; j <= tessellation; j++) {
  33143. angle = j * angle_step;
  33144. // position
  33145. ringVertex.x = Math.cos(-angle) * radius;
  33146. ringVertex.y = -height / 2 + h * height;
  33147. ringVertex.z = Math.sin(-angle) * radius;
  33148. // normal
  33149. if (diameterTop === 0 && i === subdivisions) {
  33150. // if no top cap, reuse former normals
  33151. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33152. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33153. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33154. }
  33155. else {
  33156. ringNormal.x = ringVertex.x;
  33157. ringNormal.z = ringVertex.z;
  33158. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33159. ringNormal.normalize();
  33160. }
  33161. // keep first ring vertex values for enclose
  33162. if (j === 0) {
  33163. ringFirstVertex.copyFrom(ringVertex);
  33164. ringFirstNormal.copyFrom(ringNormal);
  33165. }
  33166. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33167. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33168. if (hasRings) {
  33169. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33170. }
  33171. else {
  33172. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33173. }
  33174. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33175. if (faceColors) {
  33176. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33177. }
  33178. }
  33179. // if enclose, add four vertices and their dedicated normals
  33180. if (arc !== 1 && enclose) {
  33181. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33182. positions.push(0, ringVertex.y, 0);
  33183. positions.push(0, ringVertex.y, 0);
  33184. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33185. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33186. quadNormal.normalize();
  33187. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33188. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33189. quadNormal.normalize();
  33190. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33191. if (hasRings) {
  33192. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33193. }
  33194. else {
  33195. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33196. }
  33197. uvs.push(faceUV[s + 1].x, v);
  33198. uvs.push(faceUV[s + 1].z, v);
  33199. if (hasRings) {
  33200. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33201. }
  33202. else {
  33203. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33204. }
  33205. uvs.push(faceUV[s + 2].x, v);
  33206. uvs.push(faceUV[s + 2].z, v);
  33207. if (faceColors) {
  33208. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33209. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33210. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33211. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33212. }
  33213. }
  33214. if (cs !== s) {
  33215. cs = s;
  33216. }
  33217. }
  33218. }
  33219. // indices
  33220. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33221. var s;
  33222. i = 0;
  33223. for (s = 0; s < subdivisions; s++) {
  33224. var i0 = 0;
  33225. var i1 = 0;
  33226. var i2 = 0;
  33227. var i3 = 0;
  33228. for (j = 0; j < tessellation; j++) {
  33229. i0 = i * (e + 1) + j;
  33230. i1 = (i + 1) * (e + 1) + j;
  33231. i2 = i * (e + 1) + (j + 1);
  33232. i3 = (i + 1) * (e + 1) + (j + 1);
  33233. indices.push(i0, i1, i2);
  33234. indices.push(i3, i2, i1);
  33235. }
  33236. if (arc !== 1 && enclose) {
  33237. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33238. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33239. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33240. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33241. }
  33242. i = (hasRings) ? (i + 2) : (i + 1);
  33243. }
  33244. // Caps
  33245. var createCylinderCap = function (isTop) {
  33246. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33247. if (radius === 0) {
  33248. return;
  33249. }
  33250. // Cap positions, normals & uvs
  33251. var angle;
  33252. var circleVector;
  33253. var i;
  33254. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33255. var c = null;
  33256. if (faceColors) {
  33257. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33258. }
  33259. // cap center
  33260. var vbase = positions.length / 3;
  33261. var offset = isTop ? height / 2 : -height / 2;
  33262. var center = new BABYLON.Vector3(0, offset, 0);
  33263. positions.push(center.x, center.y, center.z);
  33264. normals.push(0, isTop ? 1 : -1, 0);
  33265. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33266. if (c) {
  33267. colors.push(c.r, c.g, c.b, c.a);
  33268. }
  33269. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33270. for (i = 0; i <= tessellation; i++) {
  33271. angle = Math.PI * 2 * i * arc / tessellation;
  33272. var cos = Math.cos(-angle);
  33273. var sin = Math.sin(-angle);
  33274. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33275. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33276. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33277. normals.push(0, isTop ? 1 : -1, 0);
  33278. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33279. if (c) {
  33280. colors.push(c.r, c.g, c.b, c.a);
  33281. }
  33282. }
  33283. // Cap indices
  33284. for (i = 0; i < tessellation; i++) {
  33285. if (!isTop) {
  33286. indices.push(vbase);
  33287. indices.push(vbase + (i + 1));
  33288. indices.push(vbase + (i + 2));
  33289. }
  33290. else {
  33291. indices.push(vbase);
  33292. indices.push(vbase + (i + 2));
  33293. indices.push(vbase + (i + 1));
  33294. }
  33295. }
  33296. };
  33297. // add caps to geometry
  33298. createCylinderCap(false);
  33299. createCylinderCap(true);
  33300. // Sides
  33301. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33302. var vertexData = new VertexData();
  33303. vertexData.indices = indices;
  33304. vertexData.positions = positions;
  33305. vertexData.normals = normals;
  33306. vertexData.uvs = uvs;
  33307. if (faceColors) {
  33308. vertexData.colors = colors;
  33309. }
  33310. return vertexData;
  33311. };
  33312. /**
  33313. * Creates the VertexData of the Torus.
  33314. */
  33315. VertexData.CreateTorus = function (options) {
  33316. var indices = [];
  33317. var positions = [];
  33318. var normals = [];
  33319. var uvs = [];
  33320. var diameter = options.diameter || 1;
  33321. var thickness = options.thickness || 0.5;
  33322. var tessellation = options.tessellation || 16;
  33323. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33324. var stride = tessellation + 1;
  33325. for (var i = 0; i <= tessellation; i++) {
  33326. var u = i / tessellation;
  33327. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33328. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33329. for (var j = 0; j <= tessellation; j++) {
  33330. var v = 1 - j / tessellation;
  33331. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33332. var dx = Math.cos(innerAngle);
  33333. var dy = Math.sin(innerAngle);
  33334. // Create a vertex.
  33335. var normal = new BABYLON.Vector3(dx, dy, 0);
  33336. var position = normal.scale(thickness / 2);
  33337. var textureCoordinate = new BABYLON.Vector2(u, v);
  33338. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33339. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33340. positions.push(position.x, position.y, position.z);
  33341. normals.push(normal.x, normal.y, normal.z);
  33342. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33343. // And create indices for two triangles.
  33344. var nextI = (i + 1) % stride;
  33345. var nextJ = (j + 1) % stride;
  33346. indices.push(i * stride + j);
  33347. indices.push(i * stride + nextJ);
  33348. indices.push(nextI * stride + j);
  33349. indices.push(i * stride + nextJ);
  33350. indices.push(nextI * stride + nextJ);
  33351. indices.push(nextI * stride + j);
  33352. }
  33353. }
  33354. // Sides
  33355. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33356. // Result
  33357. var vertexData = new VertexData();
  33358. vertexData.indices = indices;
  33359. vertexData.positions = positions;
  33360. vertexData.normals = normals;
  33361. vertexData.uvs = uvs;
  33362. return vertexData;
  33363. };
  33364. /**
  33365. * Creates the VertexData of the LineSystem.
  33366. */
  33367. VertexData.CreateLineSystem = function (options) {
  33368. var indices = [];
  33369. var positions = [];
  33370. var lines = options.lines;
  33371. var colors = options.colors;
  33372. var vertexColors = [];
  33373. var idx = 0;
  33374. for (var l = 0; l < lines.length; l++) {
  33375. var points = lines[l];
  33376. for (var index = 0; index < points.length; index++) {
  33377. positions.push(points[index].x, points[index].y, points[index].z);
  33378. if (colors) {
  33379. var color = colors[l];
  33380. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33381. }
  33382. if (index > 0) {
  33383. indices.push(idx - 1);
  33384. indices.push(idx);
  33385. }
  33386. idx++;
  33387. }
  33388. }
  33389. var vertexData = new VertexData();
  33390. vertexData.indices = indices;
  33391. vertexData.positions = positions;
  33392. if (colors) {
  33393. vertexData.colors = vertexColors;
  33394. }
  33395. return vertexData;
  33396. };
  33397. /**
  33398. * Create the VertexData of the DashedLines.
  33399. */
  33400. VertexData.CreateDashedLines = function (options) {
  33401. var dashSize = options.dashSize || 3;
  33402. var gapSize = options.gapSize || 1;
  33403. var dashNb = options.dashNb || 200;
  33404. var points = options.points;
  33405. var positions = new Array();
  33406. var indices = new Array();
  33407. var curvect = BABYLON.Vector3.Zero();
  33408. var lg = 0;
  33409. var nb = 0;
  33410. var shft = 0;
  33411. var dashshft = 0;
  33412. var curshft = 0;
  33413. var idx = 0;
  33414. var i = 0;
  33415. for (i = 0; i < points.length - 1; i++) {
  33416. points[i + 1].subtractToRef(points[i], curvect);
  33417. lg += curvect.length();
  33418. }
  33419. shft = lg / dashNb;
  33420. dashshft = dashSize * shft / (dashSize + gapSize);
  33421. for (i = 0; i < points.length - 1; i++) {
  33422. points[i + 1].subtractToRef(points[i], curvect);
  33423. nb = Math.floor(curvect.length() / shft);
  33424. curvect.normalize();
  33425. for (var j = 0; j < nb; j++) {
  33426. curshft = shft * j;
  33427. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33428. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33429. indices.push(idx, idx + 1);
  33430. idx += 2;
  33431. }
  33432. }
  33433. // Result
  33434. var vertexData = new VertexData();
  33435. vertexData.positions = positions;
  33436. vertexData.indices = indices;
  33437. return vertexData;
  33438. };
  33439. /**
  33440. * Creates the VertexData of the Ground.
  33441. */
  33442. VertexData.CreateGround = function (options) {
  33443. var indices = [];
  33444. var positions = [];
  33445. var normals = [];
  33446. var uvs = [];
  33447. var row, col;
  33448. var width = options.width || 1;
  33449. var height = options.height || 1;
  33450. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33451. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33452. for (row = 0; row <= subdivisionsY; row++) {
  33453. for (col = 0; col <= subdivisionsX; col++) {
  33454. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33455. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33456. positions.push(position.x, position.y, position.z);
  33457. normals.push(normal.x, normal.y, normal.z);
  33458. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33459. }
  33460. }
  33461. for (row = 0; row < subdivisionsY; row++) {
  33462. for (col = 0; col < subdivisionsX; col++) {
  33463. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33464. indices.push(col + 1 + row * (subdivisionsX + 1));
  33465. indices.push(col + row * (subdivisionsX + 1));
  33466. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33467. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33468. indices.push(col + row * (subdivisionsX + 1));
  33469. }
  33470. }
  33471. // Result
  33472. var vertexData = new VertexData();
  33473. vertexData.indices = indices;
  33474. vertexData.positions = positions;
  33475. vertexData.normals = normals;
  33476. vertexData.uvs = uvs;
  33477. return vertexData;
  33478. };
  33479. /**
  33480. * Creates the VertexData of the TiledGround.
  33481. */
  33482. VertexData.CreateTiledGround = function (options) {
  33483. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33484. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33485. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33486. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33487. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33488. var precision = options.precision || { w: 1, h: 1 };
  33489. var indices = new Array();
  33490. var positions = new Array();
  33491. var normals = new Array();
  33492. var uvs = new Array();
  33493. var row, col, tileRow, tileCol;
  33494. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33495. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33496. precision.w = (precision.w < 1) ? 1 : precision.w;
  33497. precision.h = (precision.h < 1) ? 1 : precision.h;
  33498. var tileSize = {
  33499. 'w': (xmax - xmin) / subdivisions.w,
  33500. 'h': (zmax - zmin) / subdivisions.h
  33501. };
  33502. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33503. // Indices
  33504. var base = positions.length / 3;
  33505. var rowLength = precision.w + 1;
  33506. for (row = 0; row < precision.h; row++) {
  33507. for (col = 0; col < precision.w; col++) {
  33508. var square = [
  33509. base + col + row * rowLength,
  33510. base + (col + 1) + row * rowLength,
  33511. base + (col + 1) + (row + 1) * rowLength,
  33512. base + col + (row + 1) * rowLength
  33513. ];
  33514. indices.push(square[1]);
  33515. indices.push(square[2]);
  33516. indices.push(square[3]);
  33517. indices.push(square[0]);
  33518. indices.push(square[1]);
  33519. indices.push(square[3]);
  33520. }
  33521. }
  33522. // Position, normals and uvs
  33523. var position = BABYLON.Vector3.Zero();
  33524. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33525. for (row = 0; row <= precision.h; row++) {
  33526. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33527. for (col = 0; col <= precision.w; col++) {
  33528. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33529. position.y = 0;
  33530. positions.push(position.x, position.y, position.z);
  33531. normals.push(normal.x, normal.y, normal.z);
  33532. uvs.push(col / precision.w, row / precision.h);
  33533. }
  33534. }
  33535. }
  33536. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33537. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33538. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33539. }
  33540. }
  33541. // Result
  33542. var vertexData = new VertexData();
  33543. vertexData.indices = indices;
  33544. vertexData.positions = positions;
  33545. vertexData.normals = normals;
  33546. vertexData.uvs = uvs;
  33547. return vertexData;
  33548. };
  33549. /**
  33550. * Creates the VertexData of the Ground designed from a heightmap.
  33551. */
  33552. VertexData.CreateGroundFromHeightMap = function (options) {
  33553. var indices = [];
  33554. var positions = [];
  33555. var normals = [];
  33556. var uvs = [];
  33557. var row, col;
  33558. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33559. // Vertices
  33560. for (row = 0; row <= options.subdivisions; row++) {
  33561. for (col = 0; col <= options.subdivisions; col++) {
  33562. 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));
  33563. // Compute height
  33564. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33565. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33566. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33567. var r = options.buffer[pos] / 255.0;
  33568. var g = options.buffer[pos + 1] / 255.0;
  33569. var b = options.buffer[pos + 2] / 255.0;
  33570. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33571. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33572. // Add vertex
  33573. positions.push(position.x, position.y, position.z);
  33574. normals.push(0, 0, 0);
  33575. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33576. }
  33577. }
  33578. // Indices
  33579. for (row = 0; row < options.subdivisions; row++) {
  33580. for (col = 0; col < options.subdivisions; col++) {
  33581. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33582. indices.push(col + 1 + row * (options.subdivisions + 1));
  33583. indices.push(col + row * (options.subdivisions + 1));
  33584. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33585. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33586. indices.push(col + row * (options.subdivisions + 1));
  33587. }
  33588. }
  33589. // Normals
  33590. VertexData.ComputeNormals(positions, indices, normals);
  33591. // Result
  33592. var vertexData = new VertexData();
  33593. vertexData.indices = indices;
  33594. vertexData.positions = positions;
  33595. vertexData.normals = normals;
  33596. vertexData.uvs = uvs;
  33597. return vertexData;
  33598. };
  33599. /**
  33600. * Creates the VertexData of the Plane.
  33601. */
  33602. VertexData.CreatePlane = function (options) {
  33603. var indices = [];
  33604. var positions = [];
  33605. var normals = [];
  33606. var uvs = [];
  33607. var width = options.width || options.size || 1;
  33608. var height = options.height || options.size || 1;
  33609. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33610. // Vertices
  33611. var halfWidth = width / 2.0;
  33612. var halfHeight = height / 2.0;
  33613. positions.push(-halfWidth, -halfHeight, 0);
  33614. normals.push(0, 0, -1.0);
  33615. uvs.push(0.0, 0.0);
  33616. positions.push(halfWidth, -halfHeight, 0);
  33617. normals.push(0, 0, -1.0);
  33618. uvs.push(1.0, 0.0);
  33619. positions.push(halfWidth, halfHeight, 0);
  33620. normals.push(0, 0, -1.0);
  33621. uvs.push(1.0, 1.0);
  33622. positions.push(-halfWidth, halfHeight, 0);
  33623. normals.push(0, 0, -1.0);
  33624. uvs.push(0.0, 1.0);
  33625. // Indices
  33626. indices.push(0);
  33627. indices.push(1);
  33628. indices.push(2);
  33629. indices.push(0);
  33630. indices.push(2);
  33631. indices.push(3);
  33632. // Sides
  33633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33634. // Result
  33635. var vertexData = new VertexData();
  33636. vertexData.indices = indices;
  33637. vertexData.positions = positions;
  33638. vertexData.normals = normals;
  33639. vertexData.uvs = uvs;
  33640. return vertexData;
  33641. };
  33642. /**
  33643. * Creates the VertexData of the Disc or regular Polygon.
  33644. */
  33645. VertexData.CreateDisc = function (options) {
  33646. var positions = new Array();
  33647. var indices = new Array();
  33648. var normals = new Array();
  33649. var uvs = new Array();
  33650. var radius = options.radius || 0.5;
  33651. var tessellation = options.tessellation || 64;
  33652. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33653. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33654. // positions and uvs
  33655. positions.push(0, 0, 0); // disc center first
  33656. uvs.push(0.5, 0.5);
  33657. var theta = Math.PI * 2 * arc;
  33658. var step = theta / tessellation;
  33659. for (var a = 0; a < theta; a += step) {
  33660. var x = Math.cos(a);
  33661. var y = Math.sin(a);
  33662. var u = (x + 1) / 2;
  33663. var v = (1 - y) / 2;
  33664. positions.push(radius * x, radius * y, 0);
  33665. uvs.push(u, v);
  33666. }
  33667. if (arc === 1) {
  33668. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33669. uvs.push(uvs[2], uvs[3]);
  33670. }
  33671. //indices
  33672. var vertexNb = positions.length / 3;
  33673. for (var i = 1; i < vertexNb - 1; i++) {
  33674. indices.push(i + 1, 0, i);
  33675. }
  33676. // result
  33677. VertexData.ComputeNormals(positions, indices, normals);
  33678. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33679. var vertexData = new VertexData();
  33680. vertexData.indices = indices;
  33681. vertexData.positions = positions;
  33682. vertexData.normals = normals;
  33683. vertexData.uvs = uvs;
  33684. return vertexData;
  33685. };
  33686. /**
  33687. * Re-creates the VertexData of the Polygon for sideOrientation.
  33688. */
  33689. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33690. var faceUV = fUV || new Array(3);
  33691. var faceColors = fColors;
  33692. var colors = [];
  33693. // default face colors and UV if undefined
  33694. for (var f = 0; f < 3; f++) {
  33695. if (faceUV[f] === undefined) {
  33696. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33697. }
  33698. if (faceColors && faceColors[f] === undefined) {
  33699. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33700. }
  33701. }
  33702. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33703. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33704. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33705. var indices = polygon.getIndices();
  33706. // set face colours and textures
  33707. var idx = 0;
  33708. var face = 0;
  33709. for (var index = 0; index < normals.length; index += 3) {
  33710. //Edge Face no. 1
  33711. if (Math.abs(normals[index + 1]) < 0.001) {
  33712. face = 1;
  33713. }
  33714. //Top Face no. 0
  33715. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33716. face = 0;
  33717. }
  33718. //Bottom Face no. 2
  33719. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33720. face = 2;
  33721. }
  33722. idx = index / 3;
  33723. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33724. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33725. if (faceColors) {
  33726. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33727. }
  33728. }
  33729. // sides
  33730. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33731. // Result
  33732. var vertexData = new VertexData();
  33733. vertexData.indices = indices;
  33734. vertexData.positions = positions;
  33735. vertexData.normals = normals;
  33736. vertexData.uvs = uvs;
  33737. if (faceColors) {
  33738. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33739. vertexData.colors = totalColors;
  33740. }
  33741. return vertexData;
  33742. };
  33743. /**
  33744. * Creates the VertexData of the IcoSphere.
  33745. */
  33746. VertexData.CreateIcoSphere = function (options) {
  33747. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33748. var radius = options.radius || 1;
  33749. var flat = (options.flat === undefined) ? true : options.flat;
  33750. var subdivisions = options.subdivisions || 4;
  33751. var radiusX = options.radiusX || radius;
  33752. var radiusY = options.radiusY || radius;
  33753. var radiusZ = options.radiusZ || radius;
  33754. var t = (1 + Math.sqrt(5)) / 2;
  33755. // 12 vertex x,y,z
  33756. var ico_vertices = [
  33757. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33758. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33759. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33760. ];
  33761. // index of 3 vertex makes a face of icopshere
  33762. var ico_indices = [
  33763. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33764. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33765. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33766. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33767. ];
  33768. // vertex for uv have aliased position, not for UV
  33769. var vertices_unalias_id = [
  33770. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33771. // vertex alias
  33772. 0,
  33773. 2,
  33774. 3,
  33775. 3,
  33776. 3,
  33777. 4,
  33778. 7,
  33779. 8,
  33780. 9,
  33781. 9,
  33782. 10,
  33783. 11 // 23: B + 12
  33784. ];
  33785. // uv as integer step (not pixels !)
  33786. var ico_vertexuv = [
  33787. 5, 1, 3, 1, 6, 4, 0, 0,
  33788. 5, 3, 4, 2, 2, 2, 4, 0,
  33789. 2, 0, 1, 1, 6, 0, 6, 2,
  33790. // vertex alias (for same vertex on different faces)
  33791. 0, 4,
  33792. 3, 3,
  33793. 4, 4,
  33794. 3, 1,
  33795. 4, 2,
  33796. 4, 4,
  33797. 0, 2,
  33798. 1, 1,
  33799. 2, 2,
  33800. 3, 3,
  33801. 1, 3,
  33802. 2, 4 // 23: B + 12
  33803. ];
  33804. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33805. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33806. // First island of uv mapping
  33807. // v = 4h 3+ 2
  33808. // v = 3h 9+ 4
  33809. // v = 2h 9+ 5 B
  33810. // v = 1h 9 1 0
  33811. // v = 0h 3 8 7 A
  33812. // u = 0 1 2 3 4 5 6 *a
  33813. // Second island of uv mapping
  33814. // v = 4h 0+ B+ 4+
  33815. // v = 3h A+ 2+
  33816. // v = 2h 7+ 6 3+
  33817. // v = 1h 8+ 3+
  33818. // v = 0h
  33819. // u = 0 1 2 3 4 5 6 *a
  33820. // Face layout on texture UV mapping
  33821. // ============
  33822. // \ 4 /\ 16 / ======
  33823. // \ / \ / /\ 11 /
  33824. // \/ 7 \/ / \ /
  33825. // ======= / 10 \/
  33826. // /\ 17 /\ =======
  33827. // / \ / \ \ 15 /\
  33828. // / 8 \/ 12 \ \ / \
  33829. // ============ \/ 6 \
  33830. // \ 18 /\ ============
  33831. // \ / \ \ 5 /\ 0 /
  33832. // \/ 13 \ \ / \ /
  33833. // ======= \/ 1 \/
  33834. // =============
  33835. // /\ 19 /\ 2 /\
  33836. // / \ / \ / \
  33837. // / 14 \/ 9 \/ 3 \
  33838. // ===================
  33839. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33840. var ustep = 138 / 1024;
  33841. var vstep = 239 / 1024;
  33842. var uoffset = 60 / 1024;
  33843. var voffset = 26 / 1024;
  33844. // Second island should have margin, not to touch the first island
  33845. // avoid any borderline artefact in pixel rounding
  33846. var island_u_offset = -40 / 1024;
  33847. var island_v_offset = +20 / 1024;
  33848. // face is either island 0 or 1 :
  33849. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33850. var island = [
  33851. 0, 0, 0, 0, 1,
  33852. 0, 0, 1, 1, 0,
  33853. 0, 0, 1, 1, 0,
  33854. 0, 1, 1, 1, 0 // 15 - 19
  33855. ];
  33856. var indices = new Array();
  33857. var positions = new Array();
  33858. var normals = new Array();
  33859. var uvs = new Array();
  33860. var current_indice = 0;
  33861. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33862. var face_vertex_pos = new Array(3);
  33863. var face_vertex_uv = new Array(3);
  33864. var v012;
  33865. for (v012 = 0; v012 < 3; v012++) {
  33866. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33867. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33868. }
  33869. // create all with normals
  33870. for (var face = 0; face < 20; face++) {
  33871. // 3 vertex per face
  33872. for (v012 = 0; v012 < 3; v012++) {
  33873. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33874. var v_id = ico_indices[3 * face + v012];
  33875. // vertex have 3D position (x,y,z)
  33876. 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]);
  33877. // Normalize to get normal, then scale to radius
  33878. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33879. // uv Coordinates from vertex ID
  33880. 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);
  33881. }
  33882. // Subdivide the face (interpolate pos, norm, uv)
  33883. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33884. // - norm is linear interpolation of vertex corner normal
  33885. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33886. // - uv is linear interpolation
  33887. //
  33888. // Topology is as below for sub-divide by 2
  33889. // vertex shown as v0,v1,v2
  33890. // interp index is i1 to progress in range [v0,v1[
  33891. // interp index is i2 to progress in range [v0,v2[
  33892. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33893. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33894. //
  33895. //
  33896. // i2 v2
  33897. // ^ ^
  33898. // / / \
  33899. // / / \
  33900. // / / \
  33901. // / / (0,1) \
  33902. // / #---------\
  33903. // / / \ (0,0)'/ \
  33904. // / / \ / \
  33905. // / / \ / \
  33906. // / / (0,0) \ / (1,0) \
  33907. // / #---------#---------\
  33908. // v0 v1
  33909. //
  33910. // --------------------> i1
  33911. //
  33912. // interp of (i1,i2):
  33913. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33914. // along i1 : lerp(x0,x1, i1/(S-i2))
  33915. //
  33916. // centroid of triangle is needed to get help normal computation
  33917. // (c1,c2) are used for centroid location
  33918. var interp_vertex = function (i1, i2, c1, c2) {
  33919. // vertex is interpolated from
  33920. // - face_vertex_pos[0..2]
  33921. // - face_vertex_uv[0..2]
  33922. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33923. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33924. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33925. pos_interp.normalize();
  33926. var vertex_normal;
  33927. if (flat) {
  33928. // in flat mode, recalculate normal as face centroid normal
  33929. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33930. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33931. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33932. }
  33933. else {
  33934. // in smooth mode, recalculate normal from each single vertex position
  33935. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33936. }
  33937. // Vertex normal need correction due to X,Y,Z radius scaling
  33938. vertex_normal.x /= radiusX;
  33939. vertex_normal.y /= radiusY;
  33940. vertex_normal.z /= radiusZ;
  33941. vertex_normal.normalize();
  33942. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33943. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33944. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33945. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33946. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33947. uvs.push(uv_interp.x, uv_interp.y);
  33948. // push each vertex has member of a face
  33949. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33950. indices.push(current_indice);
  33951. current_indice++;
  33952. };
  33953. for (var i2 = 0; i2 < subdivisions; i2++) {
  33954. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33955. // face : (i1,i2) for /\ :
  33956. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33957. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33958. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33959. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33960. if (i1 + i2 + 1 < subdivisions) {
  33961. // face : (i1,i2)' for \/ :
  33962. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33963. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33964. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33965. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33966. }
  33967. }
  33968. }
  33969. }
  33970. // Sides
  33971. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33972. // Result
  33973. var vertexData = new VertexData();
  33974. vertexData.indices = indices;
  33975. vertexData.positions = positions;
  33976. vertexData.normals = normals;
  33977. vertexData.uvs = uvs;
  33978. return vertexData;
  33979. };
  33980. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33981. /**
  33982. * Creates the VertexData of the Polyhedron.
  33983. */
  33984. VertexData.CreatePolyhedron = function (options) {
  33985. // provided polyhedron types :
  33986. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33987. // 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)
  33988. var polyhedra = [];
  33989. 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]] };
  33990. 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]] };
  33991. polyhedra[2] = {
  33992. 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]],
  33993. 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]]
  33994. };
  33995. polyhedra[3] = {
  33996. 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]],
  33997. 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]]
  33998. };
  33999. polyhedra[4] = {
  34000. 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]],
  34001. 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]]
  34002. };
  34003. 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]] };
  34004. 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]] };
  34005. 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]] };
  34006. 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]] };
  34007. 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]] };
  34008. 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]] };
  34009. 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]] };
  34010. 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]] };
  34011. 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]] };
  34012. polyhedra[14] = {
  34013. 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]],
  34014. 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]]
  34015. };
  34016. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34017. var size = options.size;
  34018. var sizeX = options.sizeX || size || 1;
  34019. var sizeY = options.sizeY || size || 1;
  34020. var sizeZ = options.sizeZ || size || 1;
  34021. var data = options.custom || polyhedra[type];
  34022. var nbfaces = data.face.length;
  34023. var faceUV = options.faceUV || new Array(nbfaces);
  34024. var faceColors = options.faceColors;
  34025. var flat = (options.flat === undefined) ? true : options.flat;
  34026. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34027. var positions = new Array();
  34028. var indices = new Array();
  34029. var normals = new Array();
  34030. var uvs = new Array();
  34031. var colors = new Array();
  34032. var index = 0;
  34033. var faceIdx = 0; // face cursor in the array "indexes"
  34034. var indexes = new Array();
  34035. var i = 0;
  34036. var f = 0;
  34037. var u, v, ang, x, y, tmp;
  34038. // default face colors and UV if undefined
  34039. if (flat) {
  34040. for (f = 0; f < nbfaces; f++) {
  34041. if (faceColors && faceColors[f] === undefined) {
  34042. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34043. }
  34044. if (faceUV && faceUV[f] === undefined) {
  34045. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34046. }
  34047. }
  34048. }
  34049. if (!flat) {
  34050. for (i = 0; i < data.vertex.length; i++) {
  34051. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34052. uvs.push(0, 0);
  34053. }
  34054. for (f = 0; f < nbfaces; f++) {
  34055. for (i = 0; i < data.face[f].length - 2; i++) {
  34056. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34057. }
  34058. }
  34059. }
  34060. else {
  34061. for (f = 0; f < nbfaces; f++) {
  34062. var fl = data.face[f].length; // number of vertices of the current face
  34063. ang = 2 * Math.PI / fl;
  34064. x = 0.5 * Math.tan(ang / 2);
  34065. y = 0.5;
  34066. // positions, uvs, colors
  34067. for (i = 0; i < fl; i++) {
  34068. // positions
  34069. 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);
  34070. indexes.push(index);
  34071. index++;
  34072. // uvs
  34073. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34074. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34075. uvs.push(u, v);
  34076. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34077. y = x * Math.sin(ang) + y * Math.cos(ang);
  34078. x = tmp;
  34079. // colors
  34080. if (faceColors) {
  34081. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34082. }
  34083. }
  34084. // indices from indexes
  34085. for (i = 0; i < fl - 2; i++) {
  34086. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34087. }
  34088. faceIdx += fl;
  34089. }
  34090. }
  34091. VertexData.ComputeNormals(positions, indices, normals);
  34092. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34093. var vertexData = new VertexData();
  34094. vertexData.positions = positions;
  34095. vertexData.indices = indices;
  34096. vertexData.normals = normals;
  34097. vertexData.uvs = uvs;
  34098. if (faceColors && flat) {
  34099. vertexData.colors = colors;
  34100. }
  34101. return vertexData;
  34102. };
  34103. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34104. /**
  34105. * Creates the VertexData of the Torus Knot.
  34106. */
  34107. VertexData.CreateTorusKnot = function (options) {
  34108. var indices = new Array();
  34109. var positions = new Array();
  34110. var normals = new Array();
  34111. var uvs = new Array();
  34112. var radius = options.radius || 2;
  34113. var tube = options.tube || 0.5;
  34114. var radialSegments = options.radialSegments || 32;
  34115. var tubularSegments = options.tubularSegments || 32;
  34116. var p = options.p || 2;
  34117. var q = options.q || 3;
  34118. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34119. // Helper
  34120. var getPos = function (angle) {
  34121. var cu = Math.cos(angle);
  34122. var su = Math.sin(angle);
  34123. var quOverP = q / p * angle;
  34124. var cs = Math.cos(quOverP);
  34125. var tx = radius * (2 + cs) * 0.5 * cu;
  34126. var ty = radius * (2 + cs) * su * 0.5;
  34127. var tz = radius * Math.sin(quOverP) * 0.5;
  34128. return new BABYLON.Vector3(tx, ty, tz);
  34129. };
  34130. // Vertices
  34131. var i;
  34132. var j;
  34133. for (i = 0; i <= radialSegments; i++) {
  34134. var modI = i % radialSegments;
  34135. var u = modI / radialSegments * 2 * p * Math.PI;
  34136. var p1 = getPos(u);
  34137. var p2 = getPos(u + 0.01);
  34138. var tang = p2.subtract(p1);
  34139. var n = p2.add(p1);
  34140. var bitan = BABYLON.Vector3.Cross(tang, n);
  34141. n = BABYLON.Vector3.Cross(bitan, tang);
  34142. bitan.normalize();
  34143. n.normalize();
  34144. for (j = 0; j < tubularSegments; j++) {
  34145. var modJ = j % tubularSegments;
  34146. var v = modJ / tubularSegments * 2 * Math.PI;
  34147. var cx = -tube * Math.cos(v);
  34148. var cy = tube * Math.sin(v);
  34149. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34150. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34151. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34152. uvs.push(i / radialSegments);
  34153. uvs.push(j / tubularSegments);
  34154. }
  34155. }
  34156. for (i = 0; i < radialSegments; i++) {
  34157. for (j = 0; j < tubularSegments; j++) {
  34158. var jNext = (j + 1) % tubularSegments;
  34159. var a = i * tubularSegments + j;
  34160. var b = (i + 1) * tubularSegments + j;
  34161. var c = (i + 1) * tubularSegments + jNext;
  34162. var d = i * tubularSegments + jNext;
  34163. indices.push(d);
  34164. indices.push(b);
  34165. indices.push(a);
  34166. indices.push(d);
  34167. indices.push(c);
  34168. indices.push(b);
  34169. }
  34170. }
  34171. // Normals
  34172. VertexData.ComputeNormals(positions, indices, normals);
  34173. // Sides
  34174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34175. // Result
  34176. var vertexData = new VertexData();
  34177. vertexData.indices = indices;
  34178. vertexData.positions = positions;
  34179. vertexData.normals = normals;
  34180. vertexData.uvs = uvs;
  34181. return vertexData;
  34182. };
  34183. // Tools
  34184. /**
  34185. * @param {any} - positions (number[] or Float32Array)
  34186. * @param {any} - indices (number[] or Uint16Array)
  34187. * @param {any} - normals (number[] or Float32Array)
  34188. * options (optional) :
  34189. * facetPositions : optional array of facet positions (vector3)
  34190. * facetNormals : optional array of facet normals (vector3)
  34191. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34192. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34193. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34194. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34195. * bInfo : optional bounding info, required for facetPartitioning computation
  34196. * useRightHandedSystem: optional boolean to for right handed system computation
  34197. * depthSort : optional boolean to enable the facet depth sort computation
  34198. * distanceTo : optional Vector3 to compute the facet depth from this location
  34199. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34200. */
  34201. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34202. // temporary scalar variables
  34203. var index = 0; // facet index
  34204. var p1p2x = 0.0; // p1p2 vector x coordinate
  34205. var p1p2y = 0.0; // p1p2 vector y coordinate
  34206. var p1p2z = 0.0; // p1p2 vector z coordinate
  34207. var p3p2x = 0.0; // p3p2 vector x coordinate
  34208. var p3p2y = 0.0; // p3p2 vector y coordinate
  34209. var p3p2z = 0.0; // p3p2 vector z coordinate
  34210. var faceNormalx = 0.0; // facet normal x coordinate
  34211. var faceNormaly = 0.0; // facet normal y coordinate
  34212. var faceNormalz = 0.0; // facet normal z coordinate
  34213. var length = 0.0; // facet normal length before normalization
  34214. var v1x = 0; // vector1 x index in the positions array
  34215. var v1y = 0; // vector1 y index in the positions array
  34216. var v1z = 0; // vector1 z index in the positions array
  34217. var v2x = 0; // vector2 x index in the positions array
  34218. var v2y = 0; // vector2 y index in the positions array
  34219. var v2z = 0; // vector2 z index in the positions array
  34220. var v3x = 0; // vector3 x index in the positions array
  34221. var v3y = 0; // vector3 y index in the positions array
  34222. var v3z = 0; // vector3 z index in the positions array
  34223. var computeFacetNormals = false;
  34224. var computeFacetPositions = false;
  34225. var computeFacetPartitioning = false;
  34226. var computeDepthSort = false;
  34227. var faceNormalSign = 1;
  34228. var ratio = 0;
  34229. var distanceTo = null;
  34230. if (options) {
  34231. computeFacetNormals = (options.facetNormals) ? true : false;
  34232. computeFacetPositions = (options.facetPositions) ? true : false;
  34233. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34234. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34235. ratio = options.ratio || 0;
  34236. computeDepthSort = (options.depthSort) ? true : false;
  34237. distanceTo = (options.distanceTo);
  34238. if (computeDepthSort) {
  34239. if (distanceTo === undefined) {
  34240. distanceTo = BABYLON.Vector3.Zero();
  34241. }
  34242. var depthSortedFacets = options.depthSortedFacets;
  34243. }
  34244. }
  34245. // facetPartitioning reinit if needed
  34246. var xSubRatio = 0;
  34247. var ySubRatio = 0;
  34248. var zSubRatio = 0;
  34249. var subSq = 0;
  34250. if (computeFacetPartitioning && options && options.bbSize) {
  34251. var ox = 0; // X partitioning index for facet position
  34252. var oy = 0; // Y partinioning index for facet position
  34253. var oz = 0; // Z partinioning index for facet position
  34254. var b1x = 0; // X partitioning index for facet v1 vertex
  34255. var b1y = 0; // Y partitioning index for facet v1 vertex
  34256. var b1z = 0; // z partitioning index for facet v1 vertex
  34257. var b2x = 0; // X partitioning index for facet v2 vertex
  34258. var b2y = 0; // Y partitioning index for facet v2 vertex
  34259. var b2z = 0; // Z partitioning index for facet v2 vertex
  34260. var b3x = 0; // X partitioning index for facet v3 vertex
  34261. var b3y = 0; // Y partitioning index for facet v3 vertex
  34262. var b3z = 0; // Z partitioning index for facet v3 vertex
  34263. var block_idx_o = 0; // facet barycenter block index
  34264. var block_idx_v1 = 0; // v1 vertex block index
  34265. var block_idx_v2 = 0; // v2 vertex block index
  34266. var block_idx_v3 = 0; // v3 vertex block index
  34267. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34268. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34269. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34270. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34271. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34272. subSq = options.subDiv.max * options.subDiv.max;
  34273. options.facetPartitioning.length = 0;
  34274. }
  34275. // reset the normals
  34276. for (index = 0; index < positions.length; index++) {
  34277. normals[index] = 0.0;
  34278. }
  34279. // Loop : 1 indice triplet = 1 facet
  34280. var nbFaces = (indices.length / 3) | 0;
  34281. for (index = 0; index < nbFaces; index++) {
  34282. // get the indexes of the coordinates of each vertex of the facet
  34283. v1x = indices[index * 3] * 3;
  34284. v1y = v1x + 1;
  34285. v1z = v1x + 2;
  34286. v2x = indices[index * 3 + 1] * 3;
  34287. v2y = v2x + 1;
  34288. v2z = v2x + 2;
  34289. v3x = indices[index * 3 + 2] * 3;
  34290. v3y = v3x + 1;
  34291. v3z = v3x + 2;
  34292. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34293. p1p2y = positions[v1y] - positions[v2y];
  34294. p1p2z = positions[v1z] - positions[v2z];
  34295. p3p2x = positions[v3x] - positions[v2x];
  34296. p3p2y = positions[v3y] - positions[v2y];
  34297. p3p2z = positions[v3z] - positions[v2z];
  34298. // compute the face normal with the cross product
  34299. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34300. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34301. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34302. // normalize this normal and store it in the array facetData
  34303. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34304. length = (length === 0) ? 1.0 : length;
  34305. faceNormalx /= length;
  34306. faceNormaly /= length;
  34307. faceNormalz /= length;
  34308. if (computeFacetNormals && options) {
  34309. options.facetNormals[index].x = faceNormalx;
  34310. options.facetNormals[index].y = faceNormaly;
  34311. options.facetNormals[index].z = faceNormalz;
  34312. }
  34313. if (computeFacetPositions && options) {
  34314. // compute and the facet barycenter coordinates in the array facetPositions
  34315. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34316. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34317. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34318. }
  34319. if (computeFacetPartitioning && options) {
  34320. // store the facet indexes in arrays in the main facetPartitioning array :
  34321. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34322. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34323. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34324. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34325. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34326. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34327. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34328. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34329. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34330. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34331. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34332. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34333. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34334. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34335. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34336. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34337. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34338. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34339. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34340. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34341. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34342. // push each facet index in each block containing the vertex
  34343. options.facetPartitioning[block_idx_v1].push(index);
  34344. if (block_idx_v2 != block_idx_v1) {
  34345. options.facetPartitioning[block_idx_v2].push(index);
  34346. }
  34347. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34348. options.facetPartitioning[block_idx_v3].push(index);
  34349. }
  34350. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34351. options.facetPartitioning[block_idx_o].push(index);
  34352. }
  34353. }
  34354. if (computeDepthSort && options && options.facetPositions) {
  34355. var dsf = depthSortedFacets[index];
  34356. dsf.ind = index * 3;
  34357. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34358. }
  34359. // compute the normals anyway
  34360. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34361. normals[v1y] += faceNormaly;
  34362. normals[v1z] += faceNormalz;
  34363. normals[v2x] += faceNormalx;
  34364. normals[v2y] += faceNormaly;
  34365. normals[v2z] += faceNormalz;
  34366. normals[v3x] += faceNormalx;
  34367. normals[v3y] += faceNormaly;
  34368. normals[v3z] += faceNormalz;
  34369. }
  34370. // last normalization of each normal
  34371. for (index = 0; index < normals.length / 3; index++) {
  34372. faceNormalx = normals[index * 3];
  34373. faceNormaly = normals[index * 3 + 1];
  34374. faceNormalz = normals[index * 3 + 2];
  34375. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34376. length = (length === 0) ? 1.0 : length;
  34377. faceNormalx /= length;
  34378. faceNormaly /= length;
  34379. faceNormalz /= length;
  34380. normals[index * 3] = faceNormalx;
  34381. normals[index * 3 + 1] = faceNormaly;
  34382. normals[index * 3 + 2] = faceNormalz;
  34383. }
  34384. };
  34385. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34386. var li = indices.length;
  34387. var ln = normals.length;
  34388. var i;
  34389. var n;
  34390. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34391. switch (sideOrientation) {
  34392. case BABYLON.Mesh.FRONTSIDE:
  34393. // nothing changed
  34394. break;
  34395. case BABYLON.Mesh.BACKSIDE:
  34396. var tmp;
  34397. // indices
  34398. for (i = 0; i < li; i += 3) {
  34399. tmp = indices[i];
  34400. indices[i] = indices[i + 2];
  34401. indices[i + 2] = tmp;
  34402. }
  34403. // normals
  34404. for (n = 0; n < ln; n++) {
  34405. normals[n] = -normals[n];
  34406. }
  34407. break;
  34408. case BABYLON.Mesh.DOUBLESIDE:
  34409. // positions
  34410. var lp = positions.length;
  34411. var l = lp / 3;
  34412. for (var p = 0; p < lp; p++) {
  34413. positions[lp + p] = positions[p];
  34414. }
  34415. // indices
  34416. for (i = 0; i < li; i += 3) {
  34417. indices[i + li] = indices[i + 2] + l;
  34418. indices[i + 1 + li] = indices[i + 1] + l;
  34419. indices[i + 2 + li] = indices[i] + l;
  34420. }
  34421. // normals
  34422. for (n = 0; n < ln; n++) {
  34423. normals[ln + n] = -normals[n];
  34424. }
  34425. // uvs
  34426. var lu = uvs.length;
  34427. var u = 0;
  34428. for (u = 0; u < lu; u++) {
  34429. uvs[u + lu] = uvs[u];
  34430. }
  34431. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34432. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34433. u = 0;
  34434. for (i = 0; i < lu / 2; i++) {
  34435. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34436. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34437. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34438. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34439. u += 2;
  34440. }
  34441. break;
  34442. }
  34443. };
  34444. /**
  34445. * Creates a new VertexData from the imported parameters.
  34446. */
  34447. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34448. var vertexData = new VertexData();
  34449. // positions
  34450. var positions = parsedVertexData.positions;
  34451. if (positions) {
  34452. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34453. }
  34454. // normals
  34455. var normals = parsedVertexData.normals;
  34456. if (normals) {
  34457. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34458. }
  34459. // tangents
  34460. var tangents = parsedVertexData.tangents;
  34461. if (tangents) {
  34462. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34463. }
  34464. // uvs
  34465. var uvs = parsedVertexData.uvs;
  34466. if (uvs) {
  34467. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34468. }
  34469. // uv2s
  34470. var uv2s = parsedVertexData.uv2s;
  34471. if (uv2s) {
  34472. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34473. }
  34474. // uv3s
  34475. var uv3s = parsedVertexData.uv3s;
  34476. if (uv3s) {
  34477. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34478. }
  34479. // uv4s
  34480. var uv4s = parsedVertexData.uv4s;
  34481. if (uv4s) {
  34482. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34483. }
  34484. // uv5s
  34485. var uv5s = parsedVertexData.uv5s;
  34486. if (uv5s) {
  34487. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34488. }
  34489. // uv6s
  34490. var uv6s = parsedVertexData.uv6s;
  34491. if (uv6s) {
  34492. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34493. }
  34494. // colors
  34495. var colors = parsedVertexData.colors;
  34496. if (colors) {
  34497. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34498. }
  34499. // matricesIndices
  34500. var matricesIndices = parsedVertexData.matricesIndices;
  34501. if (matricesIndices) {
  34502. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34503. }
  34504. // matricesWeights
  34505. var matricesWeights = parsedVertexData.matricesWeights;
  34506. if (matricesWeights) {
  34507. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34508. }
  34509. // indices
  34510. var indices = parsedVertexData.indices;
  34511. if (indices) {
  34512. vertexData.indices = indices;
  34513. }
  34514. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34515. };
  34516. return VertexData;
  34517. }());
  34518. BABYLON.VertexData = VertexData;
  34519. })(BABYLON || (BABYLON = {}));
  34520. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34521. var BABYLON;
  34522. (function (BABYLON) {
  34523. /**
  34524. * Class used to store geometry data (vertex buffers + index buffer)
  34525. */
  34526. var Geometry = /** @class */ (function () {
  34527. /**
  34528. * Creates a new geometry
  34529. * @param id defines the unique ID
  34530. * @param scene defines the hosting scene
  34531. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34532. * @param updatable defines if geometry must be updatable (false by default)
  34533. * @param mesh defines the mesh that will be associated with the geometry
  34534. */
  34535. function Geometry(id, scene, vertexData, updatable, mesh) {
  34536. if (updatable === void 0) { updatable = false; }
  34537. if (mesh === void 0) { mesh = null; }
  34538. /**
  34539. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34540. */
  34541. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34542. this._totalVertices = 0;
  34543. this._isDisposed = false;
  34544. this._indexBufferIsUpdatable = false;
  34545. this.id = id;
  34546. this._engine = scene.getEngine();
  34547. this._meshes = [];
  34548. this._scene = scene;
  34549. //Init vertex buffer cache
  34550. this._vertexBuffers = {};
  34551. this._indices = [];
  34552. this._updatable = updatable;
  34553. // vertexData
  34554. if (vertexData) {
  34555. this.setAllVerticesData(vertexData, updatable);
  34556. }
  34557. else {
  34558. this._totalVertices = 0;
  34559. this._indices = [];
  34560. }
  34561. if (this._engine.getCaps().vertexArrayObject) {
  34562. this._vertexArrayObjects = {};
  34563. }
  34564. // applyToMesh
  34565. if (mesh) {
  34566. if (mesh.getClassName() === "LinesMesh") {
  34567. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34568. this.updateExtend();
  34569. }
  34570. this.applyToMesh(mesh);
  34571. mesh.computeWorldMatrix(true);
  34572. }
  34573. }
  34574. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34575. /**
  34576. * 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
  34577. */
  34578. get: function () {
  34579. return this._boundingBias;
  34580. },
  34581. /**
  34582. * 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
  34583. */
  34584. set: function (value) {
  34585. if (this._boundingBias && this._boundingBias.equals(value)) {
  34586. return;
  34587. }
  34588. this._boundingBias = value.clone();
  34589. this.updateBoundingInfo(true, null);
  34590. },
  34591. enumerable: true,
  34592. configurable: true
  34593. });
  34594. /**
  34595. * Static function used to attach a new empty geometry to a mesh
  34596. * @param mesh defines the mesh to attach the geometry to
  34597. * @returns the new {BABYLON.Geometry}
  34598. */
  34599. Geometry.CreateGeometryForMesh = function (mesh) {
  34600. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34601. geometry.applyToMesh(mesh);
  34602. return geometry;
  34603. };
  34604. Object.defineProperty(Geometry.prototype, "extend", {
  34605. /**
  34606. * Gets the current extend of the geometry
  34607. */
  34608. get: function () {
  34609. return this._extend;
  34610. },
  34611. enumerable: true,
  34612. configurable: true
  34613. });
  34614. /**
  34615. * Gets the hosting scene
  34616. * @returns the hosting {BABYLON.Scene}
  34617. */
  34618. Geometry.prototype.getScene = function () {
  34619. return this._scene;
  34620. };
  34621. /**
  34622. * Gets the hosting engine
  34623. * @returns the hosting {BABYLON.Engine}
  34624. */
  34625. Geometry.prototype.getEngine = function () {
  34626. return this._engine;
  34627. };
  34628. /**
  34629. * Defines if the geometry is ready to use
  34630. * @returns true if the geometry is ready to be used
  34631. */
  34632. Geometry.prototype.isReady = function () {
  34633. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34634. };
  34635. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34636. /**
  34637. * Gets a value indicating that the geometry should not be serialized
  34638. */
  34639. get: function () {
  34640. for (var index = 0; index < this._meshes.length; index++) {
  34641. if (!this._meshes[index].doNotSerialize) {
  34642. return false;
  34643. }
  34644. }
  34645. return true;
  34646. },
  34647. enumerable: true,
  34648. configurable: true
  34649. });
  34650. /** @ignore */
  34651. Geometry.prototype._rebuild = function () {
  34652. if (this._vertexArrayObjects) {
  34653. this._vertexArrayObjects = {};
  34654. }
  34655. // Index buffer
  34656. if (this._meshes.length !== 0 && this._indices) {
  34657. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34658. }
  34659. // Vertex buffers
  34660. for (var key in this._vertexBuffers) {
  34661. var vertexBuffer = this._vertexBuffers[key];
  34662. vertexBuffer._rebuild();
  34663. }
  34664. };
  34665. /**
  34666. * Affects all gemetry data in one call
  34667. * @param vertexData defines the geometry data
  34668. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34669. */
  34670. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34671. vertexData.applyToGeometry(this, updatable);
  34672. this.notifyUpdate();
  34673. };
  34674. /**
  34675. * Set specific vertex data
  34676. * @param kind defines the data kind (Position, normal, etc...)
  34677. * @param data defines the vertex data to use
  34678. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34679. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34680. */
  34681. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34682. if (updatable === void 0) { updatable = false; }
  34683. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34684. this.setVerticesBuffer(buffer);
  34685. };
  34686. /**
  34687. * Removes a specific vertex data
  34688. * @param kind defines the data kind (Position, normal, etc...)
  34689. */
  34690. Geometry.prototype.removeVerticesData = function (kind) {
  34691. if (this._vertexBuffers[kind]) {
  34692. this._vertexBuffers[kind].dispose();
  34693. delete this._vertexBuffers[kind];
  34694. }
  34695. };
  34696. /**
  34697. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34698. * @param buffer defines the vertex buffer to use
  34699. */
  34700. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34701. var kind = buffer.getKind();
  34702. if (this._vertexBuffers[kind]) {
  34703. this._vertexBuffers[kind].dispose();
  34704. }
  34705. this._vertexBuffers[kind] = buffer;
  34706. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34707. var data = buffer.getData();
  34708. var stride = buffer.getStrideSize();
  34709. this._totalVertices = data.length / stride;
  34710. this.updateExtend(data, stride);
  34711. this._resetPointsArrayCache();
  34712. var meshes = this._meshes;
  34713. var numOfMeshes = meshes.length;
  34714. for (var index = 0; index < numOfMeshes; index++) {
  34715. var mesh = meshes[index];
  34716. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34717. mesh._createGlobalSubMesh(false);
  34718. mesh.computeWorldMatrix(true);
  34719. }
  34720. }
  34721. this.notifyUpdate(kind);
  34722. if (this._vertexArrayObjects) {
  34723. this._disposeVertexArrayObjects();
  34724. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34725. }
  34726. };
  34727. /**
  34728. * Update a specific vertex buffer
  34729. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34730. * It will do nothing if the buffer is not updatable
  34731. * @param kind defines the data kind (Position, normal, etc...)
  34732. * @param data defines the data to use
  34733. * @param offset defines the offset in the target buffer where to store the data
  34734. */
  34735. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34736. var vertexBuffer = this.getVertexBuffer(kind);
  34737. if (!vertexBuffer) {
  34738. return;
  34739. }
  34740. vertexBuffer.updateDirectly(data, offset);
  34741. this.notifyUpdate(kind);
  34742. };
  34743. /**
  34744. * Update a specific vertex buffer
  34745. * This function will create a new buffer if the current one is not updatable
  34746. * @param kind defines the data kind (Position, normal, etc...)
  34747. * @param data defines the data to use
  34748. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34749. */
  34750. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34751. if (updateExtends === void 0) { updateExtends = false; }
  34752. var vertexBuffer = this.getVertexBuffer(kind);
  34753. if (!vertexBuffer) {
  34754. return;
  34755. }
  34756. vertexBuffer.update(data);
  34757. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34758. var stride = vertexBuffer.getStrideSize();
  34759. this._totalVertices = data.length / stride;
  34760. this.updateBoundingInfo(updateExtends, data);
  34761. }
  34762. this.notifyUpdate(kind);
  34763. };
  34764. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34765. if (updateExtends) {
  34766. this.updateExtend(data);
  34767. }
  34768. var meshes = this._meshes;
  34769. var numOfMeshes = meshes.length;
  34770. this._resetPointsArrayCache();
  34771. for (var index = 0; index < numOfMeshes; index++) {
  34772. var mesh = meshes[index];
  34773. if (updateExtends) {
  34774. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34775. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34776. var subMesh = mesh.subMeshes[subIndex];
  34777. subMesh.refreshBoundingInfo();
  34778. }
  34779. }
  34780. }
  34781. };
  34782. /** @ignore */
  34783. Geometry.prototype._bind = function (effect, indexToBind) {
  34784. if (!effect) {
  34785. return;
  34786. }
  34787. if (indexToBind === undefined) {
  34788. indexToBind = this._indexBuffer;
  34789. }
  34790. var vbs = this.getVertexBuffers();
  34791. if (!vbs) {
  34792. return;
  34793. }
  34794. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34795. this._engine.bindBuffers(vbs, indexToBind, effect);
  34796. return;
  34797. }
  34798. // Using VAO
  34799. if (!this._vertexArrayObjects[effect.key]) {
  34800. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34801. }
  34802. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34803. };
  34804. /**
  34805. * Gets total number of vertices
  34806. * @returns the total number of vertices
  34807. */
  34808. Geometry.prototype.getTotalVertices = function () {
  34809. if (!this.isReady()) {
  34810. return 0;
  34811. }
  34812. return this._totalVertices;
  34813. };
  34814. /**
  34815. * Gets a specific vertex data attached to this geometry
  34816. * @param kind defines the data kind (Position, normal, etc...)
  34817. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34818. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34819. * @returns a float array containing vertex data
  34820. */
  34821. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34822. var vertexBuffer = this.getVertexBuffer(kind);
  34823. if (!vertexBuffer) {
  34824. return null;
  34825. }
  34826. var orig = vertexBuffer.getData();
  34827. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34828. return orig;
  34829. }
  34830. else {
  34831. var len = orig.length;
  34832. var copy = [];
  34833. for (var i = 0; i < len; i++) {
  34834. copy.push(orig[i]);
  34835. }
  34836. return copy;
  34837. }
  34838. };
  34839. /**
  34840. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34841. * @param kind defines the data kind (Position, normal, etc...)
  34842. * @returns true if the vertex buffer with the specified kind is updatable
  34843. */
  34844. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34845. var vb = this._vertexBuffers[kind];
  34846. if (!vb) {
  34847. return false;
  34848. }
  34849. return vb.isUpdatable();
  34850. };
  34851. /**
  34852. * Gets a specific vertex buffer
  34853. * @param kind defines the data kind (Position, normal, etc...)
  34854. * @returns a {BABYLON.VertexBuffer}
  34855. */
  34856. Geometry.prototype.getVertexBuffer = function (kind) {
  34857. if (!this.isReady()) {
  34858. return null;
  34859. }
  34860. return this._vertexBuffers[kind];
  34861. };
  34862. /**
  34863. * Returns all vertex buffers
  34864. * @return an object holding all vertex buffers indexed by kind
  34865. */
  34866. Geometry.prototype.getVertexBuffers = function () {
  34867. if (!this.isReady()) {
  34868. return null;
  34869. }
  34870. return this._vertexBuffers;
  34871. };
  34872. /**
  34873. * Gets a boolean indicating if specific vertex buffer is present
  34874. * @param kind defines the data kind (Position, normal, etc...)
  34875. * @returns true if data is present
  34876. */
  34877. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34878. if (!this._vertexBuffers) {
  34879. if (this._delayInfo) {
  34880. return this._delayInfo.indexOf(kind) !== -1;
  34881. }
  34882. return false;
  34883. }
  34884. return this._vertexBuffers[kind] !== undefined;
  34885. };
  34886. /**
  34887. * Gets a list of all attached data kinds (Position, normal, etc...)
  34888. * @returns a list of string containing all kinds
  34889. */
  34890. Geometry.prototype.getVerticesDataKinds = function () {
  34891. var result = [];
  34892. var kind;
  34893. if (!this._vertexBuffers && this._delayInfo) {
  34894. for (kind in this._delayInfo) {
  34895. result.push(kind);
  34896. }
  34897. }
  34898. else {
  34899. for (kind in this._vertexBuffers) {
  34900. result.push(kind);
  34901. }
  34902. }
  34903. return result;
  34904. };
  34905. /**
  34906. * Update index buffer
  34907. * @param indices defines the indices to store in the index buffer
  34908. * @param offset defines the offset in the target buffer where to store the data
  34909. */
  34910. Geometry.prototype.updateIndices = function (indices, offset) {
  34911. if (!this._indexBuffer) {
  34912. return;
  34913. }
  34914. if (!this._indexBufferIsUpdatable) {
  34915. this.setIndices(indices, null, true);
  34916. }
  34917. else {
  34918. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34919. }
  34920. };
  34921. /**
  34922. * Creates a new index buffer
  34923. * @param indices defines the indices to store in the index buffer
  34924. * @param totalVertices defines the total number of vertices (could be null)
  34925. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34926. */
  34927. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34928. if (totalVertices === void 0) { totalVertices = null; }
  34929. if (updatable === void 0) { updatable = false; }
  34930. if (this._indexBuffer) {
  34931. this._engine._releaseBuffer(this._indexBuffer);
  34932. }
  34933. this._disposeVertexArrayObjects();
  34934. this._indices = indices;
  34935. this._indexBufferIsUpdatable = updatable;
  34936. if (this._meshes.length !== 0 && this._indices) {
  34937. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34938. }
  34939. if (totalVertices != undefined) {
  34940. this._totalVertices = totalVertices;
  34941. }
  34942. var meshes = this._meshes;
  34943. var numOfMeshes = meshes.length;
  34944. for (var index = 0; index < numOfMeshes; index++) {
  34945. meshes[index]._createGlobalSubMesh(true);
  34946. }
  34947. this.notifyUpdate();
  34948. };
  34949. /**
  34950. * Return the total number of indices
  34951. * @returns the total number of indices
  34952. */
  34953. Geometry.prototype.getTotalIndices = function () {
  34954. if (!this.isReady()) {
  34955. return 0;
  34956. }
  34957. return this._indices.length;
  34958. };
  34959. /**
  34960. * Gets the index buffer array
  34961. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34962. * @returns the index buffer array
  34963. */
  34964. Geometry.prototype.getIndices = function (copyWhenShared) {
  34965. if (!this.isReady()) {
  34966. return null;
  34967. }
  34968. var orig = this._indices;
  34969. if (!copyWhenShared || this._meshes.length === 1) {
  34970. return orig;
  34971. }
  34972. else {
  34973. var len = orig.length;
  34974. var copy = [];
  34975. for (var i = 0; i < len; i++) {
  34976. copy.push(orig[i]);
  34977. }
  34978. return copy;
  34979. }
  34980. };
  34981. /**
  34982. * Gets the index buffer
  34983. * @return the index buffer
  34984. */
  34985. Geometry.prototype.getIndexBuffer = function () {
  34986. if (!this.isReady()) {
  34987. return null;
  34988. }
  34989. return this._indexBuffer;
  34990. };
  34991. /** @ignore */
  34992. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34993. if (effect === void 0) { effect = null; }
  34994. if (!effect || !this._vertexArrayObjects) {
  34995. return;
  34996. }
  34997. if (this._vertexArrayObjects[effect.key]) {
  34998. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34999. delete this._vertexArrayObjects[effect.key];
  35000. }
  35001. };
  35002. /**
  35003. * Release the associated resources for a specific mesh
  35004. * @param mesh defines the source mesh
  35005. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35006. */
  35007. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35008. var meshes = this._meshes;
  35009. var index = meshes.indexOf(mesh);
  35010. if (index === -1) {
  35011. return;
  35012. }
  35013. meshes.splice(index, 1);
  35014. mesh._geometry = null;
  35015. if (meshes.length === 0 && shouldDispose) {
  35016. this.dispose();
  35017. }
  35018. };
  35019. /**
  35020. * Apply current geometry to a given mesh
  35021. * @param mesh defines the mesh to apply geometry to
  35022. */
  35023. Geometry.prototype.applyToMesh = function (mesh) {
  35024. if (mesh._geometry === this) {
  35025. return;
  35026. }
  35027. var previousGeometry = mesh._geometry;
  35028. if (previousGeometry) {
  35029. previousGeometry.releaseForMesh(mesh);
  35030. }
  35031. var meshes = this._meshes;
  35032. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35033. mesh._geometry = this;
  35034. this._scene.pushGeometry(this);
  35035. meshes.push(mesh);
  35036. if (this.isReady()) {
  35037. this._applyToMesh(mesh);
  35038. }
  35039. else {
  35040. mesh._boundingInfo = this._boundingInfo;
  35041. }
  35042. };
  35043. Geometry.prototype.updateExtend = function (data, stride) {
  35044. if (data === void 0) { data = null; }
  35045. if (!data) {
  35046. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35047. }
  35048. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35049. };
  35050. Geometry.prototype._applyToMesh = function (mesh) {
  35051. var numOfMeshes = this._meshes.length;
  35052. // vertexBuffers
  35053. for (var kind in this._vertexBuffers) {
  35054. if (numOfMeshes === 1) {
  35055. this._vertexBuffers[kind].create();
  35056. }
  35057. var buffer = this._vertexBuffers[kind].getBuffer();
  35058. if (buffer)
  35059. buffer.references = numOfMeshes;
  35060. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35061. if (!this._extend) {
  35062. this.updateExtend(this._vertexBuffers[kind].getData());
  35063. }
  35064. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35065. mesh._createGlobalSubMesh(false);
  35066. //bounding info was just created again, world matrix should be applied again.
  35067. mesh._updateBoundingInfo();
  35068. }
  35069. }
  35070. // indexBuffer
  35071. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35072. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35073. }
  35074. if (this._indexBuffer) {
  35075. this._indexBuffer.references = numOfMeshes;
  35076. }
  35077. };
  35078. Geometry.prototype.notifyUpdate = function (kind) {
  35079. if (this.onGeometryUpdated) {
  35080. this.onGeometryUpdated(this, kind);
  35081. }
  35082. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35083. var mesh = _a[_i];
  35084. mesh._markSubMeshesAsAttributesDirty();
  35085. }
  35086. };
  35087. /**
  35088. * Load the geometry if it was flagged as delay loaded
  35089. * @param scene defines the hosting scene
  35090. * @param onLoaded defines a callback called when the geometry is loaded
  35091. */
  35092. Geometry.prototype.load = function (scene, onLoaded) {
  35093. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35094. return;
  35095. }
  35096. if (this.isReady()) {
  35097. if (onLoaded) {
  35098. onLoaded();
  35099. }
  35100. return;
  35101. }
  35102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35103. this._queueLoad(scene, onLoaded);
  35104. };
  35105. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35106. var _this = this;
  35107. if (!this.delayLoadingFile) {
  35108. return;
  35109. }
  35110. scene._addPendingData(this);
  35111. scene._loadFile(this.delayLoadingFile, function (data) {
  35112. if (!_this._delayLoadingFunction) {
  35113. return;
  35114. }
  35115. _this._delayLoadingFunction(JSON.parse(data), _this);
  35116. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35117. _this._delayInfo = [];
  35118. scene._removePendingData(_this);
  35119. var meshes = _this._meshes;
  35120. var numOfMeshes = meshes.length;
  35121. for (var index = 0; index < numOfMeshes; index++) {
  35122. _this._applyToMesh(meshes[index]);
  35123. }
  35124. if (onLoaded) {
  35125. onLoaded();
  35126. }
  35127. }, undefined, true);
  35128. };
  35129. /**
  35130. * Invert the geometry to move from a right handed system to a left handed one.
  35131. */
  35132. Geometry.prototype.toLeftHanded = function () {
  35133. // Flip faces
  35134. var tIndices = this.getIndices(false);
  35135. if (tIndices != null && tIndices.length > 0) {
  35136. for (var i = 0; i < tIndices.length; i += 3) {
  35137. var tTemp = tIndices[i + 0];
  35138. tIndices[i + 0] = tIndices[i + 2];
  35139. tIndices[i + 2] = tTemp;
  35140. }
  35141. this.setIndices(tIndices);
  35142. }
  35143. // Negate position.z
  35144. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35145. if (tPositions != null && tPositions.length > 0) {
  35146. for (var i = 0; i < tPositions.length; i += 3) {
  35147. tPositions[i + 2] = -tPositions[i + 2];
  35148. }
  35149. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35150. }
  35151. // Negate normal.z
  35152. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35153. if (tNormals != null && tNormals.length > 0) {
  35154. for (var i = 0; i < tNormals.length; i += 3) {
  35155. tNormals[i + 2] = -tNormals[i + 2];
  35156. }
  35157. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35158. }
  35159. };
  35160. // Cache
  35161. /** @ignore */
  35162. Geometry.prototype._resetPointsArrayCache = function () {
  35163. this._positions = null;
  35164. };
  35165. /** @ignore */
  35166. Geometry.prototype._generatePointsArray = function () {
  35167. if (this._positions)
  35168. return true;
  35169. this._positions = [];
  35170. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35171. if (!data) {
  35172. return false;
  35173. }
  35174. for (var index = 0; index < data.length; index += 3) {
  35175. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35176. }
  35177. return true;
  35178. };
  35179. /**
  35180. * Gets a value indicating if the geometry is disposed
  35181. * @returns true if the geometry was disposed
  35182. */
  35183. Geometry.prototype.isDisposed = function () {
  35184. return this._isDisposed;
  35185. };
  35186. Geometry.prototype._disposeVertexArrayObjects = function () {
  35187. if (this._vertexArrayObjects) {
  35188. for (var kind in this._vertexArrayObjects) {
  35189. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35190. }
  35191. this._vertexArrayObjects = {};
  35192. }
  35193. };
  35194. /**
  35195. * Free all associated resources
  35196. */
  35197. Geometry.prototype.dispose = function () {
  35198. var meshes = this._meshes;
  35199. var numOfMeshes = meshes.length;
  35200. var index;
  35201. for (index = 0; index < numOfMeshes; index++) {
  35202. this.releaseForMesh(meshes[index]);
  35203. }
  35204. this._meshes = [];
  35205. this._disposeVertexArrayObjects();
  35206. for (var kind in this._vertexBuffers) {
  35207. this._vertexBuffers[kind].dispose();
  35208. }
  35209. this._vertexBuffers = {};
  35210. this._totalVertices = 0;
  35211. if (this._indexBuffer) {
  35212. this._engine._releaseBuffer(this._indexBuffer);
  35213. }
  35214. this._indexBuffer = null;
  35215. this._indices = [];
  35216. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35217. this.delayLoadingFile = null;
  35218. this._delayLoadingFunction = null;
  35219. this._delayInfo = [];
  35220. this._boundingInfo = null;
  35221. this._scene.removeGeometry(this);
  35222. this._isDisposed = true;
  35223. };
  35224. /**
  35225. * Clone the current geometry into a new geometry
  35226. * @param id defines the unique ID of the new geometry
  35227. * @returns a new geometry object
  35228. */
  35229. Geometry.prototype.copy = function (id) {
  35230. var vertexData = new BABYLON.VertexData();
  35231. vertexData.indices = [];
  35232. var indices = this.getIndices();
  35233. if (indices) {
  35234. for (var index = 0; index < indices.length; index++) {
  35235. vertexData.indices.push(indices[index]);
  35236. }
  35237. }
  35238. var updatable = false;
  35239. var stopChecking = false;
  35240. var kind;
  35241. for (kind in this._vertexBuffers) {
  35242. // using slice() to make a copy of the array and not just reference it
  35243. var data = this.getVerticesData(kind);
  35244. if (data instanceof Float32Array) {
  35245. vertexData.set(new Float32Array(data), kind);
  35246. }
  35247. else {
  35248. vertexData.set(data.slice(0), kind);
  35249. }
  35250. if (!stopChecking) {
  35251. var vb = this.getVertexBuffer(kind);
  35252. if (vb) {
  35253. updatable = vb.isUpdatable();
  35254. stopChecking = !updatable;
  35255. }
  35256. }
  35257. }
  35258. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35259. geometry.delayLoadState = this.delayLoadState;
  35260. geometry.delayLoadingFile = this.delayLoadingFile;
  35261. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35262. for (kind in this._delayInfo) {
  35263. geometry._delayInfo = geometry._delayInfo || [];
  35264. geometry._delayInfo.push(kind);
  35265. }
  35266. // Bounding info
  35267. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35268. return geometry;
  35269. };
  35270. /**
  35271. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35272. * @return a JSON representation of the current geometry data (without the vertices data)
  35273. */
  35274. Geometry.prototype.serialize = function () {
  35275. var serializationObject = {};
  35276. serializationObject.id = this.id;
  35277. serializationObject.updatable = this._updatable;
  35278. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35279. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35280. }
  35281. return serializationObject;
  35282. };
  35283. Geometry.prototype.toNumberArray = function (origin) {
  35284. if (Array.isArray(origin)) {
  35285. return origin;
  35286. }
  35287. else {
  35288. return Array.prototype.slice.call(origin);
  35289. }
  35290. };
  35291. /**
  35292. * Serialize all vertices data into a JSON oject
  35293. * @returns a JSON representation of the current geometry data
  35294. */
  35295. Geometry.prototype.serializeVerticeData = function () {
  35296. var serializationObject = this.serialize();
  35297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35298. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35299. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35300. serializationObject.positions._updatable = true;
  35301. }
  35302. }
  35303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35304. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35305. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35306. serializationObject.normals._updatable = true;
  35307. }
  35308. }
  35309. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35310. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35311. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35312. serializationObject.tangets._updatable = true;
  35313. }
  35314. }
  35315. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35316. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35317. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35318. serializationObject.uvs._updatable = true;
  35319. }
  35320. }
  35321. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35322. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35323. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35324. serializationObject.uv2s._updatable = true;
  35325. }
  35326. }
  35327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35328. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35329. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35330. serializationObject.uv3s._updatable = true;
  35331. }
  35332. }
  35333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35334. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35335. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35336. serializationObject.uv4s._updatable = true;
  35337. }
  35338. }
  35339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35340. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35341. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35342. serializationObject.uv5s._updatable = true;
  35343. }
  35344. }
  35345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35346. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35347. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35348. serializationObject.uv6s._updatable = true;
  35349. }
  35350. }
  35351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35352. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35353. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35354. serializationObject.colors._updatable = true;
  35355. }
  35356. }
  35357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35358. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35359. serializationObject.matricesIndices._isExpanded = true;
  35360. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35361. serializationObject.matricesIndices._updatable = true;
  35362. }
  35363. }
  35364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35365. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35366. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35367. serializationObject.matricesWeights._updatable = true;
  35368. }
  35369. }
  35370. serializationObject.indices = this.toNumberArray(this.getIndices());
  35371. return serializationObject;
  35372. };
  35373. // Statics
  35374. /**
  35375. * Extracts a clone of a mesh geometry
  35376. * @param mesh defines the source mesh
  35377. * @param id defines the unique ID of the new geometry object
  35378. * @returns the new geometry object
  35379. */
  35380. Geometry.ExtractFromMesh = function (mesh, id) {
  35381. var geometry = mesh._geometry;
  35382. if (!geometry) {
  35383. return null;
  35384. }
  35385. return geometry.copy(id);
  35386. };
  35387. /**
  35388. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35389. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35390. * Be aware Math.random() could cause collisions, but:
  35391. * "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"
  35392. * @returns a string containing a new GUID
  35393. */
  35394. Geometry.RandomId = function () {
  35395. return BABYLON.Tools.RandomId();
  35396. };
  35397. /** @ignore */
  35398. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35399. var scene = mesh.getScene();
  35400. // Geometry
  35401. var geometryId = parsedGeometry.geometryId;
  35402. if (geometryId) {
  35403. var geometry = scene.getGeometryByID(geometryId);
  35404. if (geometry) {
  35405. geometry.applyToMesh(mesh);
  35406. }
  35407. }
  35408. else if (parsedGeometry instanceof ArrayBuffer) {
  35409. var binaryInfo = mesh._binaryInfo;
  35410. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35411. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35412. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35413. }
  35414. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35415. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35416. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35417. }
  35418. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35419. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35420. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35421. }
  35422. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35423. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35424. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35425. }
  35426. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35427. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35428. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35429. }
  35430. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35431. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35432. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35433. }
  35434. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35435. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35436. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35437. }
  35438. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35439. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35440. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35441. }
  35442. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35443. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35444. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35445. }
  35446. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35447. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35448. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35449. }
  35450. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35451. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35453. }
  35454. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35455. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35457. }
  35458. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35459. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35460. mesh.setIndices(indicesData, null);
  35461. }
  35462. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35463. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35464. mesh.subMeshes = [];
  35465. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35466. var materialIndex = subMeshesData[(i * 5) + 0];
  35467. var verticesStart = subMeshesData[(i * 5) + 1];
  35468. var verticesCount = subMeshesData[(i * 5) + 2];
  35469. var indexStart = subMeshesData[(i * 5) + 3];
  35470. var indexCount = subMeshesData[(i * 5) + 4];
  35471. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35472. }
  35473. }
  35474. }
  35475. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35476. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35477. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35478. if (parsedGeometry.tangents) {
  35479. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35480. }
  35481. if (parsedGeometry.uvs) {
  35482. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35483. }
  35484. if (parsedGeometry.uvs2) {
  35485. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35486. }
  35487. if (parsedGeometry.uvs3) {
  35488. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35489. }
  35490. if (parsedGeometry.uvs4) {
  35491. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35492. }
  35493. if (parsedGeometry.uvs5) {
  35494. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35495. }
  35496. if (parsedGeometry.uvs6) {
  35497. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35498. }
  35499. if (parsedGeometry.colors) {
  35500. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35501. }
  35502. if (parsedGeometry.matricesIndices) {
  35503. if (!parsedGeometry.matricesIndices._isExpanded) {
  35504. var floatIndices = [];
  35505. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35506. var matricesIndex = parsedGeometry.matricesIndices[i];
  35507. floatIndices.push(matricesIndex & 0x000000FF);
  35508. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35509. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35510. floatIndices.push(matricesIndex >> 24);
  35511. }
  35512. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35513. }
  35514. else {
  35515. delete parsedGeometry.matricesIndices._isExpanded;
  35516. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35517. }
  35518. }
  35519. if (parsedGeometry.matricesIndicesExtra) {
  35520. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35521. var floatIndices = [];
  35522. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35523. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35524. floatIndices.push(matricesIndex & 0x000000FF);
  35525. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35526. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35527. floatIndices.push(matricesIndex >> 24);
  35528. }
  35529. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35530. }
  35531. else {
  35532. delete parsedGeometry.matricesIndices._isExpanded;
  35533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35534. }
  35535. }
  35536. if (parsedGeometry.matricesWeights) {
  35537. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35538. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35539. }
  35540. if (parsedGeometry.matricesWeightsExtra) {
  35541. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35542. }
  35543. mesh.setIndices(parsedGeometry.indices, null);
  35544. }
  35545. // SubMeshes
  35546. if (parsedGeometry.subMeshes) {
  35547. mesh.subMeshes = [];
  35548. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35549. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35550. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35551. }
  35552. }
  35553. // Flat shading
  35554. if (mesh._shouldGenerateFlatShading) {
  35555. mesh.convertToFlatShadedMesh();
  35556. delete mesh._shouldGenerateFlatShading;
  35557. }
  35558. // Update
  35559. mesh.computeWorldMatrix(true);
  35560. // Octree
  35561. var sceneOctree = scene.selectionOctree;
  35562. if (sceneOctree !== undefined && sceneOctree !== null) {
  35563. sceneOctree.addMesh(mesh);
  35564. }
  35565. };
  35566. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35567. var epsilon = 1e-3;
  35568. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35569. return;
  35570. }
  35571. var noInfluenceBoneIndex = 0.0;
  35572. if (parsedGeometry.skeletonId > -1) {
  35573. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35574. if (!skeleton) {
  35575. return;
  35576. }
  35577. noInfluenceBoneIndex = skeleton.bones.length;
  35578. }
  35579. else {
  35580. return;
  35581. }
  35582. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35583. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35584. var matricesWeights = parsedGeometry.matricesWeights;
  35585. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35586. var influencers = parsedGeometry.numBoneInfluencer;
  35587. var size = matricesWeights.length;
  35588. for (var i = 0; i < size; i += 4) {
  35589. var weight = 0.0;
  35590. var firstZeroWeight = -1;
  35591. for (var j = 0; j < 4; j++) {
  35592. var w = matricesWeights[i + j];
  35593. weight += w;
  35594. if (w < epsilon && firstZeroWeight < 0) {
  35595. firstZeroWeight = j;
  35596. }
  35597. }
  35598. if (matricesWeightsExtra) {
  35599. for (var j = 0; j < 4; j++) {
  35600. var w = matricesWeightsExtra[i + j];
  35601. weight += w;
  35602. if (w < epsilon && firstZeroWeight < 0) {
  35603. firstZeroWeight = j + 4;
  35604. }
  35605. }
  35606. }
  35607. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35608. firstZeroWeight = influencers - 1;
  35609. }
  35610. if (weight > epsilon) {
  35611. var mweight = 1.0 / weight;
  35612. for (var j = 0; j < 4; j++) {
  35613. matricesWeights[i + j] *= mweight;
  35614. }
  35615. if (matricesWeightsExtra) {
  35616. for (var j = 0; j < 4; j++) {
  35617. matricesWeightsExtra[i + j] *= mweight;
  35618. }
  35619. }
  35620. }
  35621. else {
  35622. if (firstZeroWeight >= 4) {
  35623. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35624. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35625. }
  35626. else {
  35627. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35628. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35629. }
  35630. }
  35631. }
  35632. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35633. if (parsedGeometry.matricesWeightsExtra) {
  35634. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35635. }
  35636. };
  35637. /**
  35638. * Create a new geometry from persisted data (Using .babylon file format)
  35639. * @param parsedVertexData defines the persisted data
  35640. * @param scene defines the hosting scene
  35641. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35642. * @returns the new geometry object
  35643. */
  35644. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35645. if (scene.getGeometryByID(parsedVertexData.id)) {
  35646. return null; // null since geometry could be something else than a box...
  35647. }
  35648. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35649. if (BABYLON.Tags) {
  35650. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35651. }
  35652. if (parsedVertexData.delayLoadingFile) {
  35653. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35654. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35655. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35656. geometry._delayInfo = [];
  35657. if (parsedVertexData.hasUVs) {
  35658. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35659. }
  35660. if (parsedVertexData.hasUVs2) {
  35661. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35662. }
  35663. if (parsedVertexData.hasUVs3) {
  35664. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35665. }
  35666. if (parsedVertexData.hasUVs4) {
  35667. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35668. }
  35669. if (parsedVertexData.hasUVs5) {
  35670. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35671. }
  35672. if (parsedVertexData.hasUVs6) {
  35673. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35674. }
  35675. if (parsedVertexData.hasColors) {
  35676. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35677. }
  35678. if (parsedVertexData.hasMatricesIndices) {
  35679. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35680. }
  35681. if (parsedVertexData.hasMatricesWeights) {
  35682. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35683. }
  35684. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35685. }
  35686. else {
  35687. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35688. }
  35689. scene.pushGeometry(geometry, true);
  35690. return geometry;
  35691. };
  35692. return Geometry;
  35693. }());
  35694. BABYLON.Geometry = Geometry;
  35695. // Primitives
  35696. /// Abstract class
  35697. /**
  35698. * Abstract class used to provide common services for all typed geometries
  35699. */
  35700. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35701. __extends(_PrimitiveGeometry, _super);
  35702. /**
  35703. * Creates a new typed geometry
  35704. * @param id defines the unique ID of the geometry
  35705. * @param scene defines the hosting scene
  35706. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35707. * @param mesh defines the hosting mesh (can be null)
  35708. */
  35709. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35710. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35711. if (mesh === void 0) { mesh = null; }
  35712. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35713. _this._canBeRegenerated = _canBeRegenerated;
  35714. _this._beingRegenerated = true;
  35715. _this.regenerate();
  35716. _this._beingRegenerated = false;
  35717. return _this;
  35718. }
  35719. /**
  35720. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35721. * @returns true if the geometry can be regenerated
  35722. */
  35723. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35724. return this._canBeRegenerated;
  35725. };
  35726. /**
  35727. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35728. */
  35729. _PrimitiveGeometry.prototype.regenerate = function () {
  35730. if (!this._canBeRegenerated) {
  35731. return;
  35732. }
  35733. this._beingRegenerated = true;
  35734. this.setAllVerticesData(this._regenerateVertexData(), false);
  35735. this._beingRegenerated = false;
  35736. };
  35737. /**
  35738. * Clone the geometry
  35739. * @param id defines the unique ID of the new geometry
  35740. * @returns the new geometry
  35741. */
  35742. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35743. return _super.prototype.copy.call(this, id);
  35744. };
  35745. // overrides
  35746. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35747. if (!this._beingRegenerated) {
  35748. return;
  35749. }
  35750. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35751. };
  35752. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35753. if (!this._beingRegenerated) {
  35754. return;
  35755. }
  35756. _super.prototype.setVerticesData.call(this, kind, data, false);
  35757. };
  35758. // to override
  35759. /** @ignore */
  35760. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35761. throw new Error("Abstract method");
  35762. };
  35763. _PrimitiveGeometry.prototype.copy = function (id) {
  35764. throw new Error("Must be overriden in sub-classes.");
  35765. };
  35766. _PrimitiveGeometry.prototype.serialize = function () {
  35767. var serializationObject = _super.prototype.serialize.call(this);
  35768. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35769. return serializationObject;
  35770. };
  35771. return _PrimitiveGeometry;
  35772. }(Geometry));
  35773. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35774. /**
  35775. * Creates a ribbon geometry
  35776. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35777. */
  35778. var RibbonGeometry = /** @class */ (function (_super) {
  35779. __extends(RibbonGeometry, _super);
  35780. /**
  35781. * Creates a ribbon geometry
  35782. * @param id defines the unique ID of the geometry
  35783. * @param scene defines the hosting scene
  35784. * @param pathArray defines the array of paths to use
  35785. * @param closeArray defines if the last path and the first path must be joined
  35786. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35787. * @param offset defines the offset between points
  35788. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35789. * @param mesh defines the hosting mesh (can be null)
  35790. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35791. */
  35792. function RibbonGeometry(id, scene,
  35793. /**
  35794. * Defines the array of paths to use
  35795. */
  35796. pathArray,
  35797. /**
  35798. * Defines if the last and first points of each path in your pathArray must be joined
  35799. */
  35800. closeArray,
  35801. /**
  35802. * Defines if the last and first points of each path in your pathArray must be joined
  35803. */
  35804. closePath,
  35805. /**
  35806. * Defines the offset between points
  35807. */
  35808. offset, canBeRegenerated, mesh,
  35809. /**
  35810. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35811. */
  35812. side) {
  35813. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35814. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35815. _this.pathArray = pathArray;
  35816. _this.closeArray = closeArray;
  35817. _this.closePath = closePath;
  35818. _this.offset = offset;
  35819. _this.side = side;
  35820. return _this;
  35821. }
  35822. /** @ignore */
  35823. RibbonGeometry.prototype._regenerateVertexData = function () {
  35824. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35825. };
  35826. RibbonGeometry.prototype.copy = function (id) {
  35827. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35828. };
  35829. return RibbonGeometry;
  35830. }(_PrimitiveGeometry));
  35831. BABYLON.RibbonGeometry = RibbonGeometry;
  35832. /**
  35833. * Creates a box geometry
  35834. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35835. */
  35836. var BoxGeometry = /** @class */ (function (_super) {
  35837. __extends(BoxGeometry, _super);
  35838. /**
  35839. * Creates a box geometry
  35840. * @param id defines the unique ID of the geometry
  35841. * @param scene defines the hosting scene
  35842. * @param size defines the zise of the box (width, height and depth are the same)
  35843. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35844. * @param mesh defines the hosting mesh (can be null)
  35845. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35846. */
  35847. function BoxGeometry(id, scene,
  35848. /**
  35849. * Defines the zise of the box (width, height and depth are the same)
  35850. */
  35851. size, canBeRegenerated, mesh,
  35852. /**
  35853. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35854. */
  35855. side) {
  35856. if (mesh === void 0) { mesh = null; }
  35857. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35858. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35859. _this.size = size;
  35860. _this.side = side;
  35861. return _this;
  35862. }
  35863. BoxGeometry.prototype._regenerateVertexData = function () {
  35864. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35865. };
  35866. BoxGeometry.prototype.copy = function (id) {
  35867. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35868. };
  35869. BoxGeometry.prototype.serialize = function () {
  35870. var serializationObject = _super.prototype.serialize.call(this);
  35871. serializationObject.size = this.size;
  35872. return serializationObject;
  35873. };
  35874. BoxGeometry.Parse = function (parsedBox, scene) {
  35875. if (scene.getGeometryByID(parsedBox.id)) {
  35876. return null; // null since geometry could be something else than a box...
  35877. }
  35878. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35879. if (BABYLON.Tags) {
  35880. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35881. }
  35882. scene.pushGeometry(box, true);
  35883. return box;
  35884. };
  35885. return BoxGeometry;
  35886. }(_PrimitiveGeometry));
  35887. BABYLON.BoxGeometry = BoxGeometry;
  35888. /**
  35889. * Creates a sphere geometry
  35890. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35891. */
  35892. var SphereGeometry = /** @class */ (function (_super) {
  35893. __extends(SphereGeometry, _super);
  35894. /**
  35895. * Create a new sphere geometry
  35896. * @param id defines the unique ID of the geometry
  35897. * @param scene defines the hosting scene
  35898. * @param segments defines the number of segments to use to create the sphere
  35899. * @param diameter defines the diameter of the sphere
  35900. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35901. * @param mesh defines the hosting mesh (can be null)
  35902. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35903. */
  35904. function SphereGeometry(id, scene,
  35905. /**
  35906. * Defines the number of segments to use to create the sphere
  35907. */
  35908. segments,
  35909. /**
  35910. * Defines the diameter of the sphere
  35911. */
  35912. diameter, canBeRegenerated, mesh,
  35913. /**
  35914. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35915. */
  35916. side) {
  35917. if (mesh === void 0) { mesh = null; }
  35918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35919. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35920. _this.segments = segments;
  35921. _this.diameter = diameter;
  35922. _this.side = side;
  35923. return _this;
  35924. }
  35925. SphereGeometry.prototype._regenerateVertexData = function () {
  35926. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35927. };
  35928. SphereGeometry.prototype.copy = function (id) {
  35929. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35930. };
  35931. SphereGeometry.prototype.serialize = function () {
  35932. var serializationObject = _super.prototype.serialize.call(this);
  35933. serializationObject.segments = this.segments;
  35934. serializationObject.diameter = this.diameter;
  35935. return serializationObject;
  35936. };
  35937. SphereGeometry.Parse = function (parsedSphere, scene) {
  35938. if (scene.getGeometryByID(parsedSphere.id)) {
  35939. return null; // null since geometry could be something else than a sphere...
  35940. }
  35941. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35942. if (BABYLON.Tags) {
  35943. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35944. }
  35945. scene.pushGeometry(sphere, true);
  35946. return sphere;
  35947. };
  35948. return SphereGeometry;
  35949. }(_PrimitiveGeometry));
  35950. BABYLON.SphereGeometry = SphereGeometry;
  35951. /**
  35952. * Creates a disc geometry
  35953. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35954. */
  35955. var DiscGeometry = /** @class */ (function (_super) {
  35956. __extends(DiscGeometry, _super);
  35957. /**
  35958. * Creates a new disc geometry
  35959. * @param id defines the unique ID of the geometry
  35960. * @param scene defines the hosting scene
  35961. * @param radius defines the radius of the disc
  35962. * @param tessellation defines the tesselation factor to apply to the disc
  35963. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35964. * @param mesh defines the hosting mesh (can be null)
  35965. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35966. */
  35967. function DiscGeometry(id, scene,
  35968. /**
  35969. * Defines the radius of the disc
  35970. */
  35971. radius,
  35972. /**
  35973. * Defines the tesselation factor to apply to the disc
  35974. */
  35975. tessellation, canBeRegenerated, mesh,
  35976. /**
  35977. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35978. */
  35979. side) {
  35980. if (mesh === void 0) { mesh = null; }
  35981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35982. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35983. _this.radius = radius;
  35984. _this.tessellation = tessellation;
  35985. _this.side = side;
  35986. return _this;
  35987. }
  35988. DiscGeometry.prototype._regenerateVertexData = function () {
  35989. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35990. };
  35991. DiscGeometry.prototype.copy = function (id) {
  35992. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35993. };
  35994. return DiscGeometry;
  35995. }(_PrimitiveGeometry));
  35996. BABYLON.DiscGeometry = DiscGeometry;
  35997. /**
  35998. * Creates a new cylinder geometry
  35999. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36000. */
  36001. var CylinderGeometry = /** @class */ (function (_super) {
  36002. __extends(CylinderGeometry, _super);
  36003. /**
  36004. * Creates a new cylinder geometry
  36005. * @param id defines the unique ID of the geometry
  36006. * @param scene defines the hosting scene
  36007. * @param height defines the height of the cylinder
  36008. * @param diameterTop defines the diameter of the cylinder's top cap
  36009. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36010. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36011. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36012. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36013. * @param mesh defines the hosting mesh (can be null)
  36014. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36015. */
  36016. function CylinderGeometry(id, scene,
  36017. /**
  36018. * Defines the height of the cylinder
  36019. */
  36020. height,
  36021. /**
  36022. * Defines the diameter of the cylinder's top cap
  36023. */
  36024. diameterTop,
  36025. /**
  36026. * Defines the diameter of the cylinder's bottom cap
  36027. */
  36028. diameterBottom,
  36029. /**
  36030. * Defines the tessellation factor to apply to the cylinder
  36031. */
  36032. tessellation,
  36033. /**
  36034. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36035. */
  36036. subdivisions, canBeRegenerated, mesh,
  36037. /**
  36038. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36039. */
  36040. side) {
  36041. if (subdivisions === void 0) { subdivisions = 1; }
  36042. if (mesh === void 0) { mesh = null; }
  36043. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36044. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36045. _this.height = height;
  36046. _this.diameterTop = diameterTop;
  36047. _this.diameterBottom = diameterBottom;
  36048. _this.tessellation = tessellation;
  36049. _this.subdivisions = subdivisions;
  36050. _this.side = side;
  36051. return _this;
  36052. }
  36053. CylinderGeometry.prototype._regenerateVertexData = function () {
  36054. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36055. };
  36056. CylinderGeometry.prototype.copy = function (id) {
  36057. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36058. };
  36059. CylinderGeometry.prototype.serialize = function () {
  36060. var serializationObject = _super.prototype.serialize.call(this);
  36061. serializationObject.height = this.height;
  36062. serializationObject.diameterTop = this.diameterTop;
  36063. serializationObject.diameterBottom = this.diameterBottom;
  36064. serializationObject.tessellation = this.tessellation;
  36065. return serializationObject;
  36066. };
  36067. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36068. if (scene.getGeometryByID(parsedCylinder.id)) {
  36069. return null; // null since geometry could be something else than a cylinder...
  36070. }
  36071. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36072. if (BABYLON.Tags) {
  36073. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36074. }
  36075. scene.pushGeometry(cylinder, true);
  36076. return cylinder;
  36077. };
  36078. return CylinderGeometry;
  36079. }(_PrimitiveGeometry));
  36080. BABYLON.CylinderGeometry = CylinderGeometry;
  36081. /**
  36082. * Creates a new torus geometry
  36083. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36084. */
  36085. var TorusGeometry = /** @class */ (function (_super) {
  36086. __extends(TorusGeometry, _super);
  36087. /**
  36088. * Creates a new torus geometry
  36089. * @param id defines the unique ID of the geometry
  36090. * @param scene defines the hosting scene
  36091. * @param diameter defines the diameter of the torus
  36092. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36093. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36094. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36095. * @param mesh defines the hosting mesh (can be null)
  36096. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36097. */
  36098. function TorusGeometry(id, scene,
  36099. /**
  36100. * Defines the diameter of the torus
  36101. */
  36102. diameter,
  36103. /**
  36104. * Defines the thickness of the torus (ie. internal diameter)
  36105. */
  36106. thickness,
  36107. /**
  36108. * Defines the tesselation factor to apply to the torus
  36109. */
  36110. tessellation, canBeRegenerated, mesh,
  36111. /**
  36112. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36113. */
  36114. side) {
  36115. if (mesh === void 0) { mesh = null; }
  36116. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36117. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36118. _this.diameter = diameter;
  36119. _this.thickness = thickness;
  36120. _this.tessellation = tessellation;
  36121. _this.side = side;
  36122. return _this;
  36123. }
  36124. TorusGeometry.prototype._regenerateVertexData = function () {
  36125. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36126. };
  36127. TorusGeometry.prototype.copy = function (id) {
  36128. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36129. };
  36130. TorusGeometry.prototype.serialize = function () {
  36131. var serializationObject = _super.prototype.serialize.call(this);
  36132. serializationObject.diameter = this.diameter;
  36133. serializationObject.thickness = this.thickness;
  36134. serializationObject.tessellation = this.tessellation;
  36135. return serializationObject;
  36136. };
  36137. TorusGeometry.Parse = function (parsedTorus, scene) {
  36138. if (scene.getGeometryByID(parsedTorus.id)) {
  36139. return null; // null since geometry could be something else than a torus...
  36140. }
  36141. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36142. if (BABYLON.Tags) {
  36143. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36144. }
  36145. scene.pushGeometry(torus, true);
  36146. return torus;
  36147. };
  36148. return TorusGeometry;
  36149. }(_PrimitiveGeometry));
  36150. BABYLON.TorusGeometry = TorusGeometry;
  36151. /**
  36152. * Creates a new ground geometry
  36153. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36154. */
  36155. var GroundGeometry = /** @class */ (function (_super) {
  36156. __extends(GroundGeometry, _super);
  36157. /**
  36158. * Creates a new ground geometry
  36159. * @param id defines the unique ID of the geometry
  36160. * @param scene defines the hosting scene
  36161. * @param width defines the width of the ground
  36162. * @param height defines the height of the ground
  36163. * @param subdivisions defines the subdivisions to apply to the ground
  36164. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36165. * @param mesh defines the hosting mesh (can be null)
  36166. */
  36167. function GroundGeometry(id, scene,
  36168. /**
  36169. * Defines the width of the ground
  36170. */
  36171. width,
  36172. /**
  36173. * Defines the height of the ground
  36174. */
  36175. height,
  36176. /**
  36177. * Defines the subdivisions to apply to the ground
  36178. */
  36179. subdivisions, canBeRegenerated, mesh) {
  36180. if (mesh === void 0) { mesh = null; }
  36181. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36182. _this.width = width;
  36183. _this.height = height;
  36184. _this.subdivisions = subdivisions;
  36185. return _this;
  36186. }
  36187. GroundGeometry.prototype._regenerateVertexData = function () {
  36188. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36189. };
  36190. GroundGeometry.prototype.copy = function (id) {
  36191. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36192. };
  36193. GroundGeometry.prototype.serialize = function () {
  36194. var serializationObject = _super.prototype.serialize.call(this);
  36195. serializationObject.width = this.width;
  36196. serializationObject.height = this.height;
  36197. serializationObject.subdivisions = this.subdivisions;
  36198. return serializationObject;
  36199. };
  36200. GroundGeometry.Parse = function (parsedGround, scene) {
  36201. if (scene.getGeometryByID(parsedGround.id)) {
  36202. return null; // null since geometry could be something else than a ground...
  36203. }
  36204. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36205. if (BABYLON.Tags) {
  36206. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36207. }
  36208. scene.pushGeometry(ground, true);
  36209. return ground;
  36210. };
  36211. return GroundGeometry;
  36212. }(_PrimitiveGeometry));
  36213. BABYLON.GroundGeometry = GroundGeometry;
  36214. /**
  36215. * Creates a tiled ground geometry
  36216. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36217. */
  36218. var TiledGroundGeometry = /** @class */ (function (_super) {
  36219. __extends(TiledGroundGeometry, _super);
  36220. /**
  36221. * Creates a tiled ground geometry
  36222. * @param id defines the unique ID of the geometry
  36223. * @param scene defines the hosting scene
  36224. * @param xmin defines the minimum value on X axis
  36225. * @param zmin defines the minimum value on Z axis
  36226. * @param xmax defines the maximum value on X axis
  36227. * @param zmax defines the maximum value on Z axis
  36228. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36229. * @param precision defines the precision to use when computing the tiles
  36230. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36231. * @param mesh defines the hosting mesh (can be null)
  36232. */
  36233. function TiledGroundGeometry(id, scene,
  36234. /**
  36235. * Defines the minimum value on X axis
  36236. */
  36237. xmin,
  36238. /**
  36239. * Defines the minimum value on Z axis
  36240. */
  36241. zmin,
  36242. /**
  36243. * Defines the maximum value on X axis
  36244. */
  36245. xmax,
  36246. /**
  36247. * Defines the maximum value on Z axis
  36248. */
  36249. zmax,
  36250. /**
  36251. * Defines the subdivisions to apply to the ground
  36252. */
  36253. subdivisions,
  36254. /**
  36255. * Defines the precision to use when computing the tiles
  36256. */
  36257. precision, canBeRegenerated, mesh) {
  36258. if (mesh === void 0) { mesh = null; }
  36259. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36260. _this.xmin = xmin;
  36261. _this.zmin = zmin;
  36262. _this.xmax = xmax;
  36263. _this.zmax = zmax;
  36264. _this.subdivisions = subdivisions;
  36265. _this.precision = precision;
  36266. return _this;
  36267. }
  36268. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36269. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36270. };
  36271. TiledGroundGeometry.prototype.copy = function (id) {
  36272. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36273. };
  36274. return TiledGroundGeometry;
  36275. }(_PrimitiveGeometry));
  36276. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36277. /**
  36278. * Creates a plane geometry
  36279. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36280. */
  36281. var PlaneGeometry = /** @class */ (function (_super) {
  36282. __extends(PlaneGeometry, _super);
  36283. /**
  36284. * Creates a plane geometry
  36285. * @param id defines the unique ID of the geometry
  36286. * @param scene defines the hosting scene
  36287. * @param size defines the size of the plane (width === height)
  36288. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36289. * @param mesh defines the hosting mesh (can be null)
  36290. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36291. */
  36292. function PlaneGeometry(id, scene,
  36293. /**
  36294. * Defines the size of the plane (width === height)
  36295. */
  36296. size, canBeRegenerated, mesh,
  36297. /**
  36298. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36299. */
  36300. side) {
  36301. if (mesh === void 0) { mesh = null; }
  36302. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36303. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36304. _this.size = size;
  36305. _this.side = side;
  36306. return _this;
  36307. }
  36308. PlaneGeometry.prototype._regenerateVertexData = function () {
  36309. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36310. };
  36311. PlaneGeometry.prototype.copy = function (id) {
  36312. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36313. };
  36314. PlaneGeometry.prototype.serialize = function () {
  36315. var serializationObject = _super.prototype.serialize.call(this);
  36316. serializationObject.size = this.size;
  36317. return serializationObject;
  36318. };
  36319. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36320. if (scene.getGeometryByID(parsedPlane.id)) {
  36321. return null; // null since geometry could be something else than a ground...
  36322. }
  36323. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36324. if (BABYLON.Tags) {
  36325. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36326. }
  36327. scene.pushGeometry(plane, true);
  36328. return plane;
  36329. };
  36330. return PlaneGeometry;
  36331. }(_PrimitiveGeometry));
  36332. BABYLON.PlaneGeometry = PlaneGeometry;
  36333. /**
  36334. * Creates a torus knot geometry
  36335. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36336. */
  36337. var TorusKnotGeometry = /** @class */ (function (_super) {
  36338. __extends(TorusKnotGeometry, _super);
  36339. /**
  36340. * Creates a torus knot geometry
  36341. * @param id defines the unique ID of the geometry
  36342. * @param scene defines the hosting scene
  36343. * @param radius defines the radius of the torus knot
  36344. * @param tube defines the thickness of the torus knot tube
  36345. * @param radialSegments defines the number of radial segments
  36346. * @param tubularSegments defines the number of tubular segments
  36347. * @param p defines the first number of windings
  36348. * @param q defines the second number of windings
  36349. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36350. * @param mesh defines the hosting mesh (can be null)
  36351. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36352. */
  36353. function TorusKnotGeometry(id, scene,
  36354. /**
  36355. * Defines the radius of the torus knot
  36356. */
  36357. radius,
  36358. /**
  36359. * Defines the thickness of the torus knot tube
  36360. */
  36361. tube,
  36362. /**
  36363. * Defines the number of radial segments
  36364. */
  36365. radialSegments,
  36366. /**
  36367. * Defines the number of tubular segments
  36368. */
  36369. tubularSegments,
  36370. /**
  36371. * Defines the first number of windings
  36372. */
  36373. p,
  36374. /**
  36375. * Defines the second number of windings
  36376. */
  36377. q, canBeRegenerated, mesh,
  36378. /**
  36379. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36380. */
  36381. side) {
  36382. if (mesh === void 0) { mesh = null; }
  36383. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36384. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36385. _this.radius = radius;
  36386. _this.tube = tube;
  36387. _this.radialSegments = radialSegments;
  36388. _this.tubularSegments = tubularSegments;
  36389. _this.p = p;
  36390. _this.q = q;
  36391. _this.side = side;
  36392. return _this;
  36393. }
  36394. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36395. 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 });
  36396. };
  36397. TorusKnotGeometry.prototype.copy = function (id) {
  36398. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36399. };
  36400. TorusKnotGeometry.prototype.serialize = function () {
  36401. var serializationObject = _super.prototype.serialize.call(this);
  36402. serializationObject.radius = this.radius;
  36403. serializationObject.tube = this.tube;
  36404. serializationObject.radialSegments = this.radialSegments;
  36405. serializationObject.tubularSegments = this.tubularSegments;
  36406. serializationObject.p = this.p;
  36407. serializationObject.q = this.q;
  36408. return serializationObject;
  36409. };
  36410. ;
  36411. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36412. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36413. return null; // null since geometry could be something else than a ground...
  36414. }
  36415. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36416. if (BABYLON.Tags) {
  36417. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36418. }
  36419. scene.pushGeometry(torusKnot, true);
  36420. return torusKnot;
  36421. };
  36422. return TorusKnotGeometry;
  36423. }(_PrimitiveGeometry));
  36424. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36425. //}
  36426. })(BABYLON || (BABYLON = {}));
  36427. //# sourceMappingURL=babylon.geometry.js.map
  36428. var BABYLON;
  36429. (function (BABYLON) {
  36430. /**
  36431. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36432. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36433. */
  36434. var PostProcessManager = /** @class */ (function () {
  36435. /**
  36436. * Creates a new instance of @see PostProcess
  36437. * @param scene The scene that the post process is associated with.
  36438. */
  36439. function PostProcessManager(scene) {
  36440. this._vertexBuffers = {};
  36441. this._scene = scene;
  36442. }
  36443. PostProcessManager.prototype._prepareBuffers = function () {
  36444. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36445. return;
  36446. }
  36447. // VBO
  36448. var vertices = [];
  36449. vertices.push(1, 1);
  36450. vertices.push(-1, 1);
  36451. vertices.push(-1, -1);
  36452. vertices.push(1, -1);
  36453. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36454. this._buildIndexBuffer();
  36455. };
  36456. PostProcessManager.prototype._buildIndexBuffer = function () {
  36457. // Indices
  36458. var indices = [];
  36459. indices.push(0);
  36460. indices.push(1);
  36461. indices.push(2);
  36462. indices.push(0);
  36463. indices.push(2);
  36464. indices.push(3);
  36465. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36466. };
  36467. /**
  36468. * Rebuilds the vertex buffers of the manager.
  36469. */
  36470. PostProcessManager.prototype._rebuild = function () {
  36471. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36472. if (!vb) {
  36473. return;
  36474. }
  36475. vb._rebuild();
  36476. this._buildIndexBuffer();
  36477. };
  36478. // Methods
  36479. /**
  36480. * Prepares a frame to be run through a post process.
  36481. * @param sourceTexture The input texture to the post procesess. (default: null)
  36482. * @param postProcesses An array of post processes to be run. (default: null)
  36483. * @returns True if the post processes were able to be run.
  36484. */
  36485. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36486. if (sourceTexture === void 0) { sourceTexture = null; }
  36487. if (postProcesses === void 0) { postProcesses = null; }
  36488. var camera = this._scene.activeCamera;
  36489. if (!camera) {
  36490. return false;
  36491. }
  36492. var postProcesses = postProcesses || camera._postProcesses;
  36493. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36494. return false;
  36495. }
  36496. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36497. return true;
  36498. };
  36499. /**
  36500. * Manually render a set of post processes to a texture.
  36501. * @param postProcesses An array of post processes to be run.
  36502. * @param targetTexture The target texture to render to.
  36503. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36504. */
  36505. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36506. if (targetTexture === void 0) { targetTexture = null; }
  36507. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36508. var engine = this._scene.getEngine();
  36509. for (var index = 0; index < postProcesses.length; index++) {
  36510. if (index < postProcesses.length - 1) {
  36511. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36512. }
  36513. else {
  36514. if (targetTexture) {
  36515. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36516. }
  36517. else {
  36518. engine.restoreDefaultFramebuffer();
  36519. }
  36520. }
  36521. var pp = postProcesses[index];
  36522. var effect = pp.apply();
  36523. if (effect) {
  36524. pp.onBeforeRenderObservable.notifyObservers(effect);
  36525. // VBOs
  36526. this._prepareBuffers();
  36527. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36528. // Draw order
  36529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36530. pp.onAfterRenderObservable.notifyObservers(effect);
  36531. }
  36532. }
  36533. // Restore depth buffer
  36534. engine.setDepthBuffer(true);
  36535. engine.setDepthWrite(true);
  36536. };
  36537. /**
  36538. * Finalize the result of the output of the postprocesses.
  36539. * @param doNotPresent If true the result will not be displayed to the screen.
  36540. * @param targetTexture The target texture to render to.
  36541. * @param faceIndex The index of the face to bind the target texture to.
  36542. * @param postProcesses The array of post processes to render.
  36543. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36544. */
  36545. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36546. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36547. var camera = this._scene.activeCamera;
  36548. if (!camera) {
  36549. return;
  36550. }
  36551. postProcesses = postProcesses || camera._postProcesses;
  36552. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36553. return;
  36554. }
  36555. var engine = this._scene.getEngine();
  36556. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36557. if (index < len - 1) {
  36558. postProcesses[index + 1].activate(camera, targetTexture);
  36559. }
  36560. else {
  36561. if (targetTexture) {
  36562. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36563. }
  36564. else {
  36565. engine.restoreDefaultFramebuffer();
  36566. }
  36567. }
  36568. if (doNotPresent) {
  36569. break;
  36570. }
  36571. var pp = postProcesses[index];
  36572. var effect = pp.apply();
  36573. if (effect) {
  36574. pp.onBeforeRenderObservable.notifyObservers(effect);
  36575. // VBOs
  36576. this._prepareBuffers();
  36577. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36578. // Draw order
  36579. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36580. pp.onAfterRenderObservable.notifyObservers(effect);
  36581. }
  36582. }
  36583. // Restore states
  36584. engine.setDepthBuffer(true);
  36585. engine.setDepthWrite(true);
  36586. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36587. };
  36588. /**
  36589. * Disposes of the post process manager.
  36590. */
  36591. PostProcessManager.prototype.dispose = function () {
  36592. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36593. if (buffer) {
  36594. buffer.dispose();
  36595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36596. }
  36597. if (this._indexBuffer) {
  36598. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36599. this._indexBuffer = null;
  36600. }
  36601. };
  36602. return PostProcessManager;
  36603. }());
  36604. BABYLON.PostProcessManager = PostProcessManager;
  36605. })(BABYLON || (BABYLON = {}));
  36606. //# sourceMappingURL=babylon.postProcessManager.js.map
  36607. var BABYLON;
  36608. (function (BABYLON) {
  36609. /**
  36610. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36611. */
  36612. var PerformanceMonitor = /** @class */ (function () {
  36613. /**
  36614. * constructor
  36615. * @param frameSampleSize The number of samples required to saturate the sliding window
  36616. */
  36617. function PerformanceMonitor(frameSampleSize) {
  36618. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36619. this._enabled = true;
  36620. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36621. }
  36622. /**
  36623. * Samples current frame
  36624. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36625. */
  36626. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36627. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36628. if (!this._enabled)
  36629. return;
  36630. if (this._lastFrameTimeMs != null) {
  36631. var dt = timeMs - this._lastFrameTimeMs;
  36632. this._rollingFrameTime.add(dt);
  36633. }
  36634. this._lastFrameTimeMs = timeMs;
  36635. };
  36636. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36637. /**
  36638. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36639. * @return Average frame time in milliseconds
  36640. */
  36641. get: function () {
  36642. return this._rollingFrameTime.average;
  36643. },
  36644. enumerable: true,
  36645. configurable: true
  36646. });
  36647. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36648. /**
  36649. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36650. * @return Frame time variance in milliseconds squared
  36651. */
  36652. get: function () {
  36653. return this._rollingFrameTime.variance;
  36654. },
  36655. enumerable: true,
  36656. configurable: true
  36657. });
  36658. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36659. /**
  36660. * Returns the frame time of the most recent frame
  36661. * @return Frame time in milliseconds
  36662. */
  36663. get: function () {
  36664. return this._rollingFrameTime.history(0);
  36665. },
  36666. enumerable: true,
  36667. configurable: true
  36668. });
  36669. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36670. /**
  36671. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36672. * @return Framerate in frames per second
  36673. */
  36674. get: function () {
  36675. return 1000.0 / this._rollingFrameTime.average;
  36676. },
  36677. enumerable: true,
  36678. configurable: true
  36679. });
  36680. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36681. /**
  36682. * Returns the average framerate in frames per second using the most recent frame time
  36683. * @return Framerate in frames per second
  36684. */
  36685. get: function () {
  36686. var history = this._rollingFrameTime.history(0);
  36687. if (history === 0) {
  36688. return 0;
  36689. }
  36690. return 1000.0 / history;
  36691. },
  36692. enumerable: true,
  36693. configurable: true
  36694. });
  36695. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36696. /**
  36697. * Returns true if enough samples have been taken to completely fill the sliding window
  36698. * @return true if saturated
  36699. */
  36700. get: function () {
  36701. return this._rollingFrameTime.isSaturated();
  36702. },
  36703. enumerable: true,
  36704. configurable: true
  36705. });
  36706. /**
  36707. * Enables contributions to the sliding window sample set
  36708. */
  36709. PerformanceMonitor.prototype.enable = function () {
  36710. this._enabled = true;
  36711. };
  36712. /**
  36713. * Disables contributions to the sliding window sample set
  36714. * Samples will not be interpolated over the disabled period
  36715. */
  36716. PerformanceMonitor.prototype.disable = function () {
  36717. this._enabled = false;
  36718. //clear last sample to avoid interpolating over the disabled period when next enabled
  36719. this._lastFrameTimeMs = null;
  36720. };
  36721. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36722. /**
  36723. * Returns true if sampling is enabled
  36724. * @return true if enabled
  36725. */
  36726. get: function () {
  36727. return this._enabled;
  36728. },
  36729. enumerable: true,
  36730. configurable: true
  36731. });
  36732. /**
  36733. * Resets performance monitor
  36734. */
  36735. PerformanceMonitor.prototype.reset = function () {
  36736. //clear last sample to avoid interpolating over the disabled period when next enabled
  36737. this._lastFrameTimeMs = null;
  36738. //wipe record
  36739. this._rollingFrameTime.reset();
  36740. };
  36741. return PerformanceMonitor;
  36742. }());
  36743. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36744. /**
  36745. * RollingAverage
  36746. *
  36747. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36748. */
  36749. var RollingAverage = /** @class */ (function () {
  36750. /**
  36751. * constructor
  36752. * @param length The number of samples required to saturate the sliding window
  36753. */
  36754. function RollingAverage(length) {
  36755. this._samples = new Array(length);
  36756. this.reset();
  36757. }
  36758. /**
  36759. * Adds a sample to the sample set
  36760. * @param v The sample value
  36761. */
  36762. RollingAverage.prototype.add = function (v) {
  36763. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36764. var delta;
  36765. //we need to check if we've already wrapped round
  36766. if (this.isSaturated()) {
  36767. //remove bottom of stack from mean
  36768. var bottomValue = this._samples[this._pos];
  36769. delta = bottomValue - this.average;
  36770. this.average -= delta / (this._sampleCount - 1);
  36771. this._m2 -= delta * (bottomValue - this.average);
  36772. }
  36773. else {
  36774. this._sampleCount++;
  36775. }
  36776. //add new value to mean
  36777. delta = v - this.average;
  36778. this.average += delta / (this._sampleCount);
  36779. this._m2 += delta * (v - this.average);
  36780. //set the new variance
  36781. this.variance = this._m2 / (this._sampleCount - 1);
  36782. this._samples[this._pos] = v;
  36783. this._pos++;
  36784. this._pos %= this._samples.length; //positive wrap around
  36785. };
  36786. /**
  36787. * Returns previously added values or null if outside of history or outside the sliding window domain
  36788. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36789. * @return Value previously recorded with add() or null if outside of range
  36790. */
  36791. RollingAverage.prototype.history = function (i) {
  36792. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36793. return 0;
  36794. }
  36795. var i0 = this._wrapPosition(this._pos - 1.0);
  36796. return this._samples[this._wrapPosition(i0 - i)];
  36797. };
  36798. /**
  36799. * Returns true if enough samples have been taken to completely fill the sliding window
  36800. * @return true if sample-set saturated
  36801. */
  36802. RollingAverage.prototype.isSaturated = function () {
  36803. return this._sampleCount >= this._samples.length;
  36804. };
  36805. /**
  36806. * Resets the rolling average (equivalent to 0 samples taken so far)
  36807. */
  36808. RollingAverage.prototype.reset = function () {
  36809. this.average = 0;
  36810. this.variance = 0;
  36811. this._sampleCount = 0;
  36812. this._pos = 0;
  36813. this._m2 = 0;
  36814. };
  36815. /**
  36816. * Wraps a value around the sample range boundaries
  36817. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36818. * @return Wrapped position in sample range
  36819. */
  36820. RollingAverage.prototype._wrapPosition = function (i) {
  36821. var max = this._samples.length;
  36822. return ((i % max) + max) % max;
  36823. };
  36824. return RollingAverage;
  36825. }());
  36826. BABYLON.RollingAverage = RollingAverage;
  36827. })(BABYLON || (BABYLON = {}));
  36828. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36829. var BABYLON;
  36830. (function (BABYLON) {
  36831. /**
  36832. * This groups together the common properties used for image processing either in direct forward pass
  36833. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36834. * or not.
  36835. */
  36836. var ImageProcessingConfiguration = /** @class */ (function () {
  36837. function ImageProcessingConfiguration() {
  36838. /**
  36839. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36840. */
  36841. this.colorCurves = new BABYLON.ColorCurves();
  36842. this._colorCurvesEnabled = false;
  36843. this._colorGradingEnabled = false;
  36844. this._colorGradingWithGreenDepth = true;
  36845. this._colorGradingBGR = true;
  36846. this._exposure = 1.0;
  36847. this._toneMappingEnabled = false;
  36848. this._contrast = 1.0;
  36849. /**
  36850. * Vignette stretch size.
  36851. */
  36852. this.vignetteStretch = 0;
  36853. /**
  36854. * Vignette centre X Offset.
  36855. */
  36856. this.vignetteCentreX = 0;
  36857. /**
  36858. * Vignette centre Y Offset.
  36859. */
  36860. this.vignetteCentreY = 0;
  36861. /**
  36862. * Vignette weight or intensity of the vignette effect.
  36863. */
  36864. this.vignetteWeight = 1.5;
  36865. /**
  36866. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36867. * if vignetteEnabled is set to true.
  36868. */
  36869. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36870. /**
  36871. * Camera field of view used by the Vignette effect.
  36872. */
  36873. this.vignetteCameraFov = 0.5;
  36874. this._grainEnabled = false;
  36875. this._grainIntensity = 30;
  36876. this._grainAnimated = false;
  36877. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36878. this._vignetteEnabled = false;
  36879. this._applyByPostProcess = false;
  36880. this._isEnabled = true;
  36881. /**
  36882. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36883. * @type {BABYLON.Observable}
  36884. */
  36885. this.onUpdateParameters = new BABYLON.Observable();
  36886. }
  36887. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36888. /**
  36889. * Gets wether the color curves effect is enabled.
  36890. */
  36891. get: function () {
  36892. return this._colorCurvesEnabled;
  36893. },
  36894. /**
  36895. * Sets wether the color curves effect is enabled.
  36896. */
  36897. set: function (value) {
  36898. if (this._colorCurvesEnabled === value) {
  36899. return;
  36900. }
  36901. this._colorCurvesEnabled = value;
  36902. this._updateParameters();
  36903. },
  36904. enumerable: true,
  36905. configurable: true
  36906. });
  36907. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36908. /**
  36909. * Gets wether the color grading effect is enabled.
  36910. */
  36911. get: function () {
  36912. return this._colorGradingEnabled;
  36913. },
  36914. /**
  36915. * Sets wether the color grading effect is enabled.
  36916. */
  36917. set: function (value) {
  36918. if (this._colorGradingEnabled === value) {
  36919. return;
  36920. }
  36921. this._colorGradingEnabled = value;
  36922. this._updateParameters();
  36923. },
  36924. enumerable: true,
  36925. configurable: true
  36926. });
  36927. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36928. /**
  36929. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36930. */
  36931. get: function () {
  36932. return this._colorGradingWithGreenDepth;
  36933. },
  36934. /**
  36935. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36936. */
  36937. set: function (value) {
  36938. if (this._colorGradingWithGreenDepth === value) {
  36939. return;
  36940. }
  36941. this._colorGradingWithGreenDepth = value;
  36942. this._updateParameters();
  36943. },
  36944. enumerable: true,
  36945. configurable: true
  36946. });
  36947. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36948. /**
  36949. * Gets wether the color grading texture contains BGR values.
  36950. */
  36951. get: function () {
  36952. return this._colorGradingBGR;
  36953. },
  36954. /**
  36955. * Sets wether the color grading texture contains BGR values.
  36956. */
  36957. set: function (value) {
  36958. if (this._colorGradingBGR === value) {
  36959. return;
  36960. }
  36961. this._colorGradingBGR = value;
  36962. this._updateParameters();
  36963. },
  36964. enumerable: true,
  36965. configurable: true
  36966. });
  36967. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36968. /**
  36969. * Gets the Exposure used in the effect.
  36970. */
  36971. get: function () {
  36972. return this._exposure;
  36973. },
  36974. /**
  36975. * Sets the Exposure used in the effect.
  36976. */
  36977. set: function (value) {
  36978. if (this._exposure === value) {
  36979. return;
  36980. }
  36981. this._exposure = value;
  36982. this._updateParameters();
  36983. },
  36984. enumerable: true,
  36985. configurable: true
  36986. });
  36987. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36988. /**
  36989. * Gets wether the tone mapping effect is enabled.
  36990. */
  36991. get: function () {
  36992. return this._toneMappingEnabled;
  36993. },
  36994. /**
  36995. * Sets wether the tone mapping effect is enabled.
  36996. */
  36997. set: function (value) {
  36998. if (this._toneMappingEnabled === value) {
  36999. return;
  37000. }
  37001. this._toneMappingEnabled = value;
  37002. this._updateParameters();
  37003. },
  37004. enumerable: true,
  37005. configurable: true
  37006. });
  37007. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37008. /**
  37009. * Gets the contrast used in the effect.
  37010. */
  37011. get: function () {
  37012. return this._contrast;
  37013. },
  37014. /**
  37015. * Sets the contrast used in the effect.
  37016. */
  37017. set: function (value) {
  37018. if (this._contrast === value) {
  37019. return;
  37020. }
  37021. this._contrast = value;
  37022. this._updateParameters();
  37023. },
  37024. enumerable: true,
  37025. configurable: true
  37026. });
  37027. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37028. /**
  37029. * If the grain effect should be enabled.
  37030. */
  37031. get: function () {
  37032. return this._grainEnabled;
  37033. },
  37034. set: function (value) {
  37035. if (this._grainEnabled === value) {
  37036. return;
  37037. }
  37038. this._grainEnabled = value;
  37039. this._updateParameters();
  37040. },
  37041. enumerable: true,
  37042. configurable: true
  37043. });
  37044. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37045. /**
  37046. * Amount of grain to be applied by the grain effect.
  37047. */
  37048. get: function () {
  37049. return this._grainIntensity;
  37050. },
  37051. set: function (value) {
  37052. if (this._grainIntensity === value) {
  37053. return;
  37054. }
  37055. this._grainIntensity = value;
  37056. },
  37057. enumerable: true,
  37058. configurable: true
  37059. });
  37060. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37061. /**
  37062. * If the grain effect should be animated.
  37063. */
  37064. get: function () {
  37065. return this._grainAnimated;
  37066. },
  37067. set: function (value) {
  37068. if (this._grainAnimated === value) {
  37069. return;
  37070. }
  37071. this._grainAnimated = value;
  37072. this._updateParameters();
  37073. },
  37074. enumerable: true,
  37075. configurable: true
  37076. });
  37077. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37078. /**
  37079. * Gets the vignette blend mode allowing different kind of effect.
  37080. */
  37081. get: function () {
  37082. return this._vignetteBlendMode;
  37083. },
  37084. /**
  37085. * Sets the vignette blend mode allowing different kind of effect.
  37086. */
  37087. set: function (value) {
  37088. if (this._vignetteBlendMode === value) {
  37089. return;
  37090. }
  37091. this._vignetteBlendMode = value;
  37092. this._updateParameters();
  37093. },
  37094. enumerable: true,
  37095. configurable: true
  37096. });
  37097. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37098. /**
  37099. * Gets wether the vignette effect is enabled.
  37100. */
  37101. get: function () {
  37102. return this._vignetteEnabled;
  37103. },
  37104. /**
  37105. * Sets wether the vignette effect is enabled.
  37106. */
  37107. set: function (value) {
  37108. if (this._vignetteEnabled === value) {
  37109. return;
  37110. }
  37111. this._vignetteEnabled = value;
  37112. this._updateParameters();
  37113. },
  37114. enumerable: true,
  37115. configurable: true
  37116. });
  37117. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37118. /**
  37119. * Gets wether the image processing is applied through a post process or not.
  37120. */
  37121. get: function () {
  37122. return this._applyByPostProcess;
  37123. },
  37124. /**
  37125. * Sets wether the image processing is applied through a post process or not.
  37126. */
  37127. set: function (value) {
  37128. if (this._applyByPostProcess === value) {
  37129. return;
  37130. }
  37131. this._applyByPostProcess = value;
  37132. this._updateParameters();
  37133. },
  37134. enumerable: true,
  37135. configurable: true
  37136. });
  37137. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37138. /**
  37139. * Gets wether the image processing is enabled or not.
  37140. */
  37141. get: function () {
  37142. return this._isEnabled;
  37143. },
  37144. /**
  37145. * Sets wether the image processing is enabled or not.
  37146. */
  37147. set: function (value) {
  37148. if (this._isEnabled === value) {
  37149. return;
  37150. }
  37151. this._isEnabled = value;
  37152. this._updateParameters();
  37153. },
  37154. enumerable: true,
  37155. configurable: true
  37156. });
  37157. /**
  37158. * Method called each time the image processing information changes requires to recompile the effect.
  37159. */
  37160. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37161. this.onUpdateParameters.notifyObservers(this);
  37162. };
  37163. ImageProcessingConfiguration.prototype.getClassName = function () {
  37164. return "ImageProcessingConfiguration";
  37165. };
  37166. /**
  37167. * Prepare the list of uniforms associated with the Image Processing effects.
  37168. * @param uniformsList The list of uniforms used in the effect
  37169. * @param defines the list of defines currently in use
  37170. */
  37171. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37172. if (defines.EXPOSURE) {
  37173. uniforms.push("exposureLinear");
  37174. }
  37175. if (defines.CONTRAST) {
  37176. uniforms.push("contrast");
  37177. }
  37178. if (defines.COLORGRADING) {
  37179. uniforms.push("colorTransformSettings");
  37180. }
  37181. if (defines.VIGNETTE) {
  37182. uniforms.push("vInverseScreenSize");
  37183. uniforms.push("vignetteSettings1");
  37184. uniforms.push("vignetteSettings2");
  37185. }
  37186. if (defines.COLORCURVES) {
  37187. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37188. }
  37189. if (defines.GRAIN) {
  37190. uniforms.push("grainVarianceAmount");
  37191. uniforms.push("grainAnimatedSeed");
  37192. }
  37193. };
  37194. /**
  37195. * Prepare the list of samplers associated with the Image Processing effects.
  37196. * @param uniformsList The list of uniforms used in the effect
  37197. * @param defines the list of defines currently in use
  37198. */
  37199. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37200. if (defines.COLORGRADING) {
  37201. samplersList.push("txColorTransform");
  37202. }
  37203. };
  37204. /**
  37205. * Prepare the list of defines associated to the shader.
  37206. * @param defines the list of defines to complete
  37207. */
  37208. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37209. if (forPostProcess === void 0) { forPostProcess = false; }
  37210. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37211. defines.VIGNETTE = false;
  37212. defines.TONEMAPPING = false;
  37213. defines.CONTRAST = false;
  37214. defines.EXPOSURE = false;
  37215. defines.COLORCURVES = false;
  37216. defines.COLORGRADING = false;
  37217. defines.COLORGRADING3D = false;
  37218. defines.IMAGEPROCESSING = false;
  37219. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37220. return;
  37221. }
  37222. defines.VIGNETTE = this.vignetteEnabled;
  37223. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37224. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37225. defines.TONEMAPPING = this.toneMappingEnabled;
  37226. defines.CONTRAST = (this.contrast !== 1.0);
  37227. defines.EXPOSURE = (this.exposure !== 1.0);
  37228. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37229. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37230. if (defines.COLORGRADING) {
  37231. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37232. }
  37233. else {
  37234. defines.COLORGRADING3D = false;
  37235. }
  37236. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37237. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37238. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37239. defines.GRAIN = this.grainEnabled;
  37240. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37241. };
  37242. /**
  37243. * Returns true if all the image processing information are ready.
  37244. */
  37245. ImageProcessingConfiguration.prototype.isReady = function () {
  37246. // Color Grading texure can not be none blocking.
  37247. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37248. };
  37249. /**
  37250. * Binds the image processing to the shader.
  37251. * @param effect The effect to bind to
  37252. */
  37253. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37254. if (aspectRatio === void 0) { aspectRatio = 1; }
  37255. // Color Curves
  37256. if (this._colorCurvesEnabled && this.colorCurves) {
  37257. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37258. }
  37259. // Vignette
  37260. if (this._vignetteEnabled) {
  37261. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37262. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37263. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37264. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37265. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37266. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37267. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37268. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37269. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37270. var vignettePower = -2.0 * this.vignetteWeight;
  37271. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37272. }
  37273. // Exposure
  37274. effect.setFloat("exposureLinear", this.exposure);
  37275. // Contrast
  37276. effect.setFloat("contrast", this.contrast);
  37277. // Color transform settings
  37278. if (this.colorGradingTexture) {
  37279. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37280. var textureSize = this.colorGradingTexture.getSize().height;
  37281. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37282. 0.5 / textureSize, // textureOffset
  37283. textureSize, // textureSize
  37284. this.colorGradingTexture.level // weight
  37285. );
  37286. }
  37287. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37288. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37289. };
  37290. /**
  37291. * Clones the current image processing instance.
  37292. * @return The cloned image processing
  37293. */
  37294. ImageProcessingConfiguration.prototype.clone = function () {
  37295. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37296. };
  37297. /**
  37298. * Serializes the current image processing instance to a json representation.
  37299. * @return a JSON representation
  37300. */
  37301. ImageProcessingConfiguration.prototype.serialize = function () {
  37302. return BABYLON.SerializationHelper.Serialize(this);
  37303. };
  37304. /**
  37305. * Parses the image processing from a json representation.
  37306. * @param source the JSON source to parse
  37307. * @return The parsed image processing
  37308. */
  37309. ImageProcessingConfiguration.Parse = function (source) {
  37310. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37311. };
  37312. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37313. /**
  37314. * Used to apply the vignette as a mix with the pixel color.
  37315. */
  37316. get: function () {
  37317. return this._VIGNETTEMODE_MULTIPLY;
  37318. },
  37319. enumerable: true,
  37320. configurable: true
  37321. });
  37322. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37323. /**
  37324. * Used to apply the vignette as a replacement of the pixel color.
  37325. */
  37326. get: function () {
  37327. return this._VIGNETTEMODE_OPAQUE;
  37328. },
  37329. enumerable: true,
  37330. configurable: true
  37331. });
  37332. // Static constants associated to the image processing.
  37333. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37334. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37335. __decorate([
  37336. BABYLON.serializeAsColorCurves()
  37337. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37338. __decorate([
  37339. BABYLON.serialize()
  37340. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37341. __decorate([
  37342. BABYLON.serializeAsTexture()
  37343. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37344. __decorate([
  37345. BABYLON.serialize()
  37346. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37347. __decorate([
  37348. BABYLON.serialize()
  37349. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37350. __decorate([
  37351. BABYLON.serialize()
  37352. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37353. __decorate([
  37354. BABYLON.serialize()
  37355. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37356. __decorate([
  37357. BABYLON.serialize()
  37358. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37359. __decorate([
  37360. BABYLON.serialize()
  37361. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37362. __decorate([
  37363. BABYLON.serialize()
  37364. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37365. __decorate([
  37366. BABYLON.serialize()
  37367. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37368. __decorate([
  37369. BABYLON.serialize()
  37370. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37371. __decorate([
  37372. BABYLON.serialize()
  37373. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37374. __decorate([
  37375. BABYLON.serializeAsColor4()
  37376. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37377. __decorate([
  37378. BABYLON.serialize()
  37379. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37380. __decorate([
  37381. BABYLON.serialize()
  37382. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37383. __decorate([
  37384. BABYLON.serialize()
  37385. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37386. __decorate([
  37387. BABYLON.serialize()
  37388. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37389. __decorate([
  37390. BABYLON.serialize()
  37391. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37392. __decorate([
  37393. BABYLON.serialize()
  37394. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37395. __decorate([
  37396. BABYLON.serialize()
  37397. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37398. __decorate([
  37399. BABYLON.serialize()
  37400. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37401. return ImageProcessingConfiguration;
  37402. }());
  37403. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37404. })(BABYLON || (BABYLON = {}));
  37405. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37406. var BABYLON;
  37407. (function (BABYLON) {
  37408. /**
  37409. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37410. * It can help converting any input color in a desired output one. This can then be used to create effects
  37411. * from sepia, black and white to sixties or futuristic rendering...
  37412. *
  37413. * The only supported format is currently 3dl.
  37414. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37415. */
  37416. var ColorGradingTexture = /** @class */ (function (_super) {
  37417. __extends(ColorGradingTexture, _super);
  37418. /**
  37419. * Instantiates a ColorGradingTexture from the following parameters.
  37420. *
  37421. * @param url The location of the color gradind data (currently only supporting 3dl)
  37422. * @param scene The scene the texture will be used in
  37423. */
  37424. function ColorGradingTexture(url, scene) {
  37425. var _this = _super.call(this, scene) || this;
  37426. if (!url) {
  37427. return _this;
  37428. }
  37429. _this._engine = scene.getEngine();
  37430. _this._textureMatrix = BABYLON.Matrix.Identity();
  37431. _this.name = url;
  37432. _this.url = url;
  37433. _this.hasAlpha = false;
  37434. _this.isCube = false;
  37435. _this.is3D = _this._engine.webGLVersion > 1;
  37436. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37437. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37438. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37439. _this.anisotropicFilteringLevel = 1;
  37440. _this._texture = _this._getFromCache(url, true);
  37441. if (!_this._texture) {
  37442. if (!scene.useDelayedTextureLoading) {
  37443. _this.loadTexture();
  37444. }
  37445. else {
  37446. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37447. }
  37448. }
  37449. return _this;
  37450. }
  37451. /**
  37452. * Returns the texture matrix used in most of the material.
  37453. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37454. */
  37455. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37456. return this._textureMatrix;
  37457. };
  37458. /**
  37459. * Occurs when the file being loaded is a .3dl LUT file.
  37460. */
  37461. ColorGradingTexture.prototype.load3dlTexture = function () {
  37462. var engine = this._engine;
  37463. var texture;
  37464. if (engine.webGLVersion === 1) {
  37465. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37466. }
  37467. else {
  37468. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37469. }
  37470. this._texture = texture;
  37471. var callback = function (text) {
  37472. if (typeof text !== "string") {
  37473. return;
  37474. }
  37475. var data = null;
  37476. var tempData = null;
  37477. var line;
  37478. var lines = text.split('\n');
  37479. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37480. var maxColor = 0;
  37481. for (var i = 0; i < lines.length; i++) {
  37482. line = lines[i];
  37483. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37484. continue;
  37485. if (line.indexOf('#') === 0)
  37486. continue;
  37487. var words = line.split(" ");
  37488. if (size === 0) {
  37489. // Number of space + one
  37490. size = words.length;
  37491. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37492. tempData = new Float32Array(size * size * size * 4);
  37493. continue;
  37494. }
  37495. if (size != 0) {
  37496. var r = Math.max(parseInt(words[0]), 0);
  37497. var g = Math.max(parseInt(words[1]), 0);
  37498. var b = Math.max(parseInt(words[2]), 0);
  37499. maxColor = Math.max(r, maxColor);
  37500. maxColor = Math.max(g, maxColor);
  37501. maxColor = Math.max(b, maxColor);
  37502. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37503. if (tempData) {
  37504. tempData[pixelStorageIndex + 0] = r;
  37505. tempData[pixelStorageIndex + 1] = g;
  37506. tempData[pixelStorageIndex + 2] = b;
  37507. }
  37508. pixelIndexSlice++;
  37509. if (pixelIndexSlice % size == 0) {
  37510. pixelIndexH++;
  37511. pixelIndexSlice = 0;
  37512. if (pixelIndexH % size == 0) {
  37513. pixelIndexW++;
  37514. pixelIndexH = 0;
  37515. }
  37516. }
  37517. }
  37518. }
  37519. if (tempData && data) {
  37520. for (var i = 0; i < tempData.length; i++) {
  37521. if (i > 0 && (i + 1) % 4 === 0) {
  37522. data[i] = 255;
  37523. }
  37524. else {
  37525. var value = tempData[i];
  37526. data[i] = (value / maxColor * 255);
  37527. }
  37528. }
  37529. }
  37530. if (texture.is3D) {
  37531. texture.updateSize(size, size, size);
  37532. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37533. }
  37534. else {
  37535. texture.updateSize(size * size, size);
  37536. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37537. }
  37538. };
  37539. var scene = this.getScene();
  37540. if (scene) {
  37541. scene._loadFile(this.url, callback);
  37542. }
  37543. else {
  37544. this._engine._loadFile(this.url, callback);
  37545. }
  37546. return this._texture;
  37547. };
  37548. /**
  37549. * Starts the loading process of the texture.
  37550. */
  37551. ColorGradingTexture.prototype.loadTexture = function () {
  37552. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37553. this.load3dlTexture();
  37554. }
  37555. };
  37556. /**
  37557. * Clones the color gradind texture.
  37558. */
  37559. ColorGradingTexture.prototype.clone = function () {
  37560. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37561. // Base texture
  37562. newTexture.level = this.level;
  37563. return newTexture;
  37564. };
  37565. /**
  37566. * Called during delayed load for textures.
  37567. */
  37568. ColorGradingTexture.prototype.delayLoad = function () {
  37569. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37570. return;
  37571. }
  37572. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37573. this._texture = this._getFromCache(this.url, true);
  37574. if (!this._texture) {
  37575. this.loadTexture();
  37576. }
  37577. };
  37578. /**
  37579. * Parses a color grading texture serialized by Babylon.
  37580. * @param parsedTexture The texture information being parsedTexture
  37581. * @param scene The scene to load the texture in
  37582. * @param rootUrl The root url of the data assets to load
  37583. * @return A color gradind texture
  37584. */
  37585. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37586. var texture = null;
  37587. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37588. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37589. texture.name = parsedTexture.name;
  37590. texture.level = parsedTexture.level;
  37591. }
  37592. return texture;
  37593. };
  37594. /**
  37595. * Serializes the LUT texture to json format.
  37596. */
  37597. ColorGradingTexture.prototype.serialize = function () {
  37598. if (!this.name) {
  37599. return null;
  37600. }
  37601. var serializationObject = {};
  37602. serializationObject.name = this.name;
  37603. serializationObject.level = this.level;
  37604. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37605. return serializationObject;
  37606. };
  37607. /**
  37608. * Empty line regex stored for GC.
  37609. */
  37610. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37611. return ColorGradingTexture;
  37612. }(BABYLON.BaseTexture));
  37613. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37614. })(BABYLON || (BABYLON = {}));
  37615. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37616. var BABYLON;
  37617. (function (BABYLON) {
  37618. /**
  37619. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37620. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37621. * 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;
  37622. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37623. */
  37624. var ColorCurves = /** @class */ (function () {
  37625. function ColorCurves() {
  37626. this._dirty = true;
  37627. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37628. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37629. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37630. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37631. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37632. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37633. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37634. this._globalHue = 30;
  37635. this._globalDensity = 0;
  37636. this._globalSaturation = 0;
  37637. this._globalExposure = 0;
  37638. this._highlightsHue = 30;
  37639. this._highlightsDensity = 0;
  37640. this._highlightsSaturation = 0;
  37641. this._highlightsExposure = 0;
  37642. this._midtonesHue = 30;
  37643. this._midtonesDensity = 0;
  37644. this._midtonesSaturation = 0;
  37645. this._midtonesExposure = 0;
  37646. this._shadowsHue = 30;
  37647. this._shadowsDensity = 0;
  37648. this._shadowsSaturation = 0;
  37649. this._shadowsExposure = 0;
  37650. }
  37651. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37652. /**
  37653. * Gets the global Hue value.
  37654. * 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).
  37655. */
  37656. get: function () {
  37657. return this._globalHue;
  37658. },
  37659. /**
  37660. * Sets the global Hue value.
  37661. * 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).
  37662. */
  37663. set: function (value) {
  37664. this._globalHue = value;
  37665. this._dirty = true;
  37666. },
  37667. enumerable: true,
  37668. configurable: true
  37669. });
  37670. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37671. /**
  37672. * Gets the global Density value.
  37673. * 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.
  37674. * Values less than zero provide a filter of opposite hue.
  37675. */
  37676. get: function () {
  37677. return this._globalDensity;
  37678. },
  37679. /**
  37680. * Sets the global Density value.
  37681. * 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.
  37682. * Values less than zero provide a filter of opposite hue.
  37683. */
  37684. set: function (value) {
  37685. this._globalDensity = value;
  37686. this._dirty = true;
  37687. },
  37688. enumerable: true,
  37689. configurable: true
  37690. });
  37691. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37692. /**
  37693. * Gets the global Saturation value.
  37694. * 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.
  37695. */
  37696. get: function () {
  37697. return this._globalSaturation;
  37698. },
  37699. /**
  37700. * Sets the global Saturation value.
  37701. * 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.
  37702. */
  37703. set: function (value) {
  37704. this._globalSaturation = value;
  37705. this._dirty = true;
  37706. },
  37707. enumerable: true,
  37708. configurable: true
  37709. });
  37710. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37711. /**
  37712. * Gets the highlights Hue value.
  37713. * 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).
  37714. */
  37715. get: function () {
  37716. return this._highlightsHue;
  37717. },
  37718. /**
  37719. * Sets the highlights Hue value.
  37720. * 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).
  37721. */
  37722. set: function (value) {
  37723. this._highlightsHue = value;
  37724. this._dirty = true;
  37725. },
  37726. enumerable: true,
  37727. configurable: true
  37728. });
  37729. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37730. /**
  37731. * Gets the highlights Density value.
  37732. * 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.
  37733. * Values less than zero provide a filter of opposite hue.
  37734. */
  37735. get: function () {
  37736. return this._highlightsDensity;
  37737. },
  37738. /**
  37739. * Sets the highlights Density value.
  37740. * 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.
  37741. * Values less than zero provide a filter of opposite hue.
  37742. */
  37743. set: function (value) {
  37744. this._highlightsDensity = value;
  37745. this._dirty = true;
  37746. },
  37747. enumerable: true,
  37748. configurable: true
  37749. });
  37750. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37751. /**
  37752. * Gets the highlights Saturation value.
  37753. * 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.
  37754. */
  37755. get: function () {
  37756. return this._highlightsSaturation;
  37757. },
  37758. /**
  37759. * Sets the highlights Saturation value.
  37760. * 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.
  37761. */
  37762. set: function (value) {
  37763. this._highlightsSaturation = value;
  37764. this._dirty = true;
  37765. },
  37766. enumerable: true,
  37767. configurable: true
  37768. });
  37769. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37770. /**
  37771. * Gets the highlights Exposure value.
  37772. * 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.
  37773. */
  37774. get: function () {
  37775. return this._highlightsExposure;
  37776. },
  37777. /**
  37778. * Sets the highlights Exposure value.
  37779. * 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.
  37780. */
  37781. set: function (value) {
  37782. this._highlightsExposure = value;
  37783. this._dirty = true;
  37784. },
  37785. enumerable: true,
  37786. configurable: true
  37787. });
  37788. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37789. /**
  37790. * Gets the midtones Hue value.
  37791. * 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).
  37792. */
  37793. get: function () {
  37794. return this._midtonesHue;
  37795. },
  37796. /**
  37797. * Sets the midtones Hue value.
  37798. * 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).
  37799. */
  37800. set: function (value) {
  37801. this._midtonesHue = value;
  37802. this._dirty = true;
  37803. },
  37804. enumerable: true,
  37805. configurable: true
  37806. });
  37807. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37808. /**
  37809. * Gets the midtones Density value.
  37810. * 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.
  37811. * Values less than zero provide a filter of opposite hue.
  37812. */
  37813. get: function () {
  37814. return this._midtonesDensity;
  37815. },
  37816. /**
  37817. * Sets the midtones Density value.
  37818. * 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.
  37819. * Values less than zero provide a filter of opposite hue.
  37820. */
  37821. set: function (value) {
  37822. this._midtonesDensity = value;
  37823. this._dirty = true;
  37824. },
  37825. enumerable: true,
  37826. configurable: true
  37827. });
  37828. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37829. /**
  37830. * Gets the midtones Saturation value.
  37831. * 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.
  37832. */
  37833. get: function () {
  37834. return this._midtonesSaturation;
  37835. },
  37836. /**
  37837. * Sets the midtones Saturation value.
  37838. * 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.
  37839. */
  37840. set: function (value) {
  37841. this._midtonesSaturation = value;
  37842. this._dirty = true;
  37843. },
  37844. enumerable: true,
  37845. configurable: true
  37846. });
  37847. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37848. /**
  37849. * Gets the midtones Exposure value.
  37850. * 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.
  37851. */
  37852. get: function () {
  37853. return this._midtonesExposure;
  37854. },
  37855. /**
  37856. * Sets the midtones Exposure value.
  37857. * 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.
  37858. */
  37859. set: function (value) {
  37860. this._midtonesExposure = value;
  37861. this._dirty = true;
  37862. },
  37863. enumerable: true,
  37864. configurable: true
  37865. });
  37866. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37867. /**
  37868. * Gets the shadows Hue value.
  37869. * 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).
  37870. */
  37871. get: function () {
  37872. return this._shadowsHue;
  37873. },
  37874. /**
  37875. * Sets the shadows Hue value.
  37876. * 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).
  37877. */
  37878. set: function (value) {
  37879. this._shadowsHue = value;
  37880. this._dirty = true;
  37881. },
  37882. enumerable: true,
  37883. configurable: true
  37884. });
  37885. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37886. /**
  37887. * Gets the shadows Density value.
  37888. * 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.
  37889. * Values less than zero provide a filter of opposite hue.
  37890. */
  37891. get: function () {
  37892. return this._shadowsDensity;
  37893. },
  37894. /**
  37895. * Sets the shadows Density value.
  37896. * 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.
  37897. * Values less than zero provide a filter of opposite hue.
  37898. */
  37899. set: function (value) {
  37900. this._shadowsDensity = value;
  37901. this._dirty = true;
  37902. },
  37903. enumerable: true,
  37904. configurable: true
  37905. });
  37906. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37907. /**
  37908. * Gets the shadows Saturation value.
  37909. * 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.
  37910. */
  37911. get: function () {
  37912. return this._shadowsSaturation;
  37913. },
  37914. /**
  37915. * Sets the shadows Saturation value.
  37916. * 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.
  37917. */
  37918. set: function (value) {
  37919. this._shadowsSaturation = value;
  37920. this._dirty = true;
  37921. },
  37922. enumerable: true,
  37923. configurable: true
  37924. });
  37925. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37926. /**
  37927. * Gets the shadows Exposure value.
  37928. * 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.
  37929. */
  37930. get: function () {
  37931. return this._shadowsExposure;
  37932. },
  37933. /**
  37934. * Sets the shadows Exposure value.
  37935. * 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.
  37936. */
  37937. set: function (value) {
  37938. this._shadowsExposure = value;
  37939. this._dirty = true;
  37940. },
  37941. enumerable: true,
  37942. configurable: true
  37943. });
  37944. ColorCurves.prototype.getClassName = function () {
  37945. return "ColorCurves";
  37946. };
  37947. /**
  37948. * Binds the color curves to the shader.
  37949. * @param colorCurves The color curve to bind
  37950. * @param effect The effect to bind to
  37951. */
  37952. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37953. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37954. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37955. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37956. if (colorCurves._dirty) {
  37957. colorCurves._dirty = false;
  37958. // Fill in global info.
  37959. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37960. // Compute highlights info.
  37961. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37962. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37963. // Compute midtones info.
  37964. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37965. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37966. // Compute shadows info.
  37967. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37968. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37969. // Compute deltas (neutral is midtones).
  37970. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37971. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37972. }
  37973. if (effect) {
  37974. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37975. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37976. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37977. }
  37978. };
  37979. /**
  37980. * Prepare the list of uniforms associated with the ColorCurves effects.
  37981. * @param uniformsList The list of uniforms used in the effect
  37982. */
  37983. ColorCurves.PrepareUniforms = function (uniformsList) {
  37984. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37985. };
  37986. /**
  37987. * Returns color grading data based on a hue, density, saturation and exposure value.
  37988. * @param filterHue The hue of the color filter.
  37989. * @param filterDensity The density of the color filter.
  37990. * @param saturation The saturation.
  37991. * @param exposure The exposure.
  37992. * @param result The result data container.
  37993. */
  37994. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37995. if (hue == null) {
  37996. return;
  37997. }
  37998. hue = ColorCurves.clamp(hue, 0, 360);
  37999. density = ColorCurves.clamp(density, -100, 100);
  38000. saturation = ColorCurves.clamp(saturation, -100, 100);
  38001. exposure = ColorCurves.clamp(exposure, -100, 100);
  38002. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38003. // so that the maximum filter density is only 50% control. This provides fine control
  38004. // for small values and reasonable range.
  38005. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38006. density *= 0.5;
  38007. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38008. if (density < 0) {
  38009. density *= -1;
  38010. hue = (hue + 180) % 360;
  38011. }
  38012. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38013. result.scaleToRef(2, result);
  38014. result.a = 1 + 0.01 * saturation;
  38015. };
  38016. /**
  38017. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38018. * @param value The input slider value in range [-100,100].
  38019. * @returns Adjusted value.
  38020. */
  38021. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38022. value /= 100;
  38023. var x = Math.abs(value);
  38024. x = Math.pow(x, 2);
  38025. if (value < 0) {
  38026. x *= -1;
  38027. }
  38028. x *= 100;
  38029. return x;
  38030. };
  38031. /**
  38032. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38033. * @param hue The hue (H) input.
  38034. * @param saturation The saturation (S) input.
  38035. * @param brightness The brightness (B) input.
  38036. * @result An RGBA color represented as Vector4.
  38037. */
  38038. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38039. var h = ColorCurves.clamp(hue, 0, 360);
  38040. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38041. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38042. if (s === 0) {
  38043. result.r = v;
  38044. result.g = v;
  38045. result.b = v;
  38046. }
  38047. else {
  38048. // sector 0 to 5
  38049. h /= 60;
  38050. var i = Math.floor(h);
  38051. // fractional part of h
  38052. var f = h - i;
  38053. var p = v * (1 - s);
  38054. var q = v * (1 - s * f);
  38055. var t = v * (1 - s * (1 - f));
  38056. switch (i) {
  38057. case 0:
  38058. result.r = v;
  38059. result.g = t;
  38060. result.b = p;
  38061. break;
  38062. case 1:
  38063. result.r = q;
  38064. result.g = v;
  38065. result.b = p;
  38066. break;
  38067. case 2:
  38068. result.r = p;
  38069. result.g = v;
  38070. result.b = t;
  38071. break;
  38072. case 3:
  38073. result.r = p;
  38074. result.g = q;
  38075. result.b = v;
  38076. break;
  38077. case 4:
  38078. result.r = t;
  38079. result.g = p;
  38080. result.b = v;
  38081. break;
  38082. default:// case 5:
  38083. result.r = v;
  38084. result.g = p;
  38085. result.b = q;
  38086. break;
  38087. }
  38088. }
  38089. result.a = 1;
  38090. };
  38091. /**
  38092. * Returns a value clamped between min and max
  38093. * @param value The value to clamp
  38094. * @param min The minimum of value
  38095. * @param max The maximum of value
  38096. * @returns The clamped value.
  38097. */
  38098. ColorCurves.clamp = function (value, min, max) {
  38099. return Math.min(Math.max(value, min), max);
  38100. };
  38101. /**
  38102. * Clones the current color curve instance.
  38103. * @return The cloned curves
  38104. */
  38105. ColorCurves.prototype.clone = function () {
  38106. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38107. };
  38108. /**
  38109. * Serializes the current color curve instance to a json representation.
  38110. * @return a JSON representation
  38111. */
  38112. ColorCurves.prototype.serialize = function () {
  38113. return BABYLON.SerializationHelper.Serialize(this);
  38114. };
  38115. /**
  38116. * Parses the color curve from a json representation.
  38117. * @param source the JSON source to parse
  38118. * @return The parsed curves
  38119. */
  38120. ColorCurves.Parse = function (source) {
  38121. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38122. };
  38123. __decorate([
  38124. BABYLON.serialize()
  38125. ], ColorCurves.prototype, "_globalHue", void 0);
  38126. __decorate([
  38127. BABYLON.serialize()
  38128. ], ColorCurves.prototype, "_globalDensity", void 0);
  38129. __decorate([
  38130. BABYLON.serialize()
  38131. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38132. __decorate([
  38133. BABYLON.serialize()
  38134. ], ColorCurves.prototype, "_globalExposure", void 0);
  38135. __decorate([
  38136. BABYLON.serialize()
  38137. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38138. __decorate([
  38139. BABYLON.serialize()
  38140. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38141. __decorate([
  38142. BABYLON.serialize()
  38143. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38144. __decorate([
  38145. BABYLON.serialize()
  38146. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38147. __decorate([
  38148. BABYLON.serialize()
  38149. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38150. __decorate([
  38151. BABYLON.serialize()
  38152. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38153. __decorate([
  38154. BABYLON.serialize()
  38155. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38156. __decorate([
  38157. BABYLON.serialize()
  38158. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38159. return ColorCurves;
  38160. }());
  38161. BABYLON.ColorCurves = ColorCurves;
  38162. })(BABYLON || (BABYLON = {}));
  38163. //# sourceMappingURL=babylon.colorCurves.js.map
  38164. //# sourceMappingURL=babylon.behavior.js.map
  38165. var BABYLON;
  38166. (function (BABYLON) {
  38167. /**
  38168. * "Static Class" containing the most commonly used helper while dealing with material for
  38169. * rendering purpose.
  38170. *
  38171. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38172. *
  38173. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38174. */
  38175. var MaterialHelper = /** @class */ (function () {
  38176. function MaterialHelper() {
  38177. }
  38178. /**
  38179. * Bind the current view position to an effect.
  38180. * @param effect The effect to be bound
  38181. * @param scene The scene the eyes position is used from
  38182. */
  38183. MaterialHelper.BindEyePosition = function (effect, scene) {
  38184. if (scene._forcedViewPosition) {
  38185. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38186. return;
  38187. }
  38188. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38189. };
  38190. /**
  38191. * Helps preparing the defines values about the UVs in used in the effect.
  38192. * UVs are shared as much as we can accross chanels in the shaders.
  38193. * @param texture The texture we are preparing the UVs for
  38194. * @param defines The defines to update
  38195. * @param key The chanel key "diffuse", "specular"... used in the shader
  38196. */
  38197. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38198. defines._needUVs = true;
  38199. defines[key] = true;
  38200. if (texture.getTextureMatrix().isIdentity(true)) {
  38201. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38202. if (texture.coordinatesIndex === 0) {
  38203. defines["MAINUV1"] = true;
  38204. }
  38205. else {
  38206. defines["MAINUV2"] = true;
  38207. }
  38208. }
  38209. else {
  38210. defines[key + "DIRECTUV"] = 0;
  38211. }
  38212. };
  38213. /**
  38214. * Binds a texture matrix value to its corrsponding uniform
  38215. * @param texture The texture to bind the matrix for
  38216. * @param uniformBuffer The uniform buffer receivin the data
  38217. * @param key The chanel key "diffuse", "specular"... used in the shader
  38218. */
  38219. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38220. var matrix = texture.getTextureMatrix();
  38221. if (!matrix.isIdentity(true)) {
  38222. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38223. }
  38224. };
  38225. /**
  38226. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38227. * @param mesh defines the current mesh
  38228. * @param scene defines the current scene
  38229. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38230. * @param pointsCloud defines if point cloud rendering has to be turned on
  38231. * @param fogEnabled defines if fog has to be turned on
  38232. * @param alphaTest defines if alpha testing has to be turned on
  38233. * @param defines defines the current list of defines
  38234. */
  38235. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38236. if (defines._areMiscDirty) {
  38237. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38238. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38239. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38240. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38241. defines["ALPHATEST"] = alphaTest;
  38242. }
  38243. };
  38244. /**
  38245. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38246. * @param scene defines the current scene
  38247. * @param engine defines the current engine
  38248. * @param defines specifies the list of active defines
  38249. * @param useInstances defines if instances have to be turned on
  38250. * @param useClipPlane defines if clip plane have to be turned on
  38251. */
  38252. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38253. if (useClipPlane === void 0) { useClipPlane = null; }
  38254. var changed = false;
  38255. if (useClipPlane == null) {
  38256. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38257. }
  38258. if (defines["CLIPPLANE"] !== useClipPlane) {
  38259. defines["CLIPPLANE"] = useClipPlane;
  38260. changed = true;
  38261. }
  38262. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38263. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38264. changed = true;
  38265. }
  38266. if (defines["INSTANCES"] !== useInstances) {
  38267. defines["INSTANCES"] = useInstances;
  38268. changed = true;
  38269. }
  38270. if (changed) {
  38271. defines.markAsUnprocessed();
  38272. }
  38273. };
  38274. /**
  38275. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38276. * @param mesh The mesh containing the geometry data we will draw
  38277. * @param defines The defines to update
  38278. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38279. * @param useBones Precise whether bones should be used or not (override mesh info)
  38280. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38281. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38282. * @returns false if defines are considered not dirty and have not been checked
  38283. */
  38284. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38285. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38286. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38287. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38288. return false;
  38289. }
  38290. defines._normals = defines._needNormals;
  38291. defines._uvs = defines._needUVs;
  38292. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38293. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38294. defines["TANGENT"] = true;
  38295. }
  38296. if (defines._needUVs) {
  38297. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38298. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38299. }
  38300. else {
  38301. defines["UV1"] = false;
  38302. defines["UV2"] = false;
  38303. }
  38304. if (useVertexColor) {
  38305. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38306. defines["VERTEXCOLOR"] = hasVertexColors;
  38307. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38308. }
  38309. if (useBones) {
  38310. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38311. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38312. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38313. }
  38314. else {
  38315. defines["NUM_BONE_INFLUENCERS"] = 0;
  38316. defines["BonesPerMesh"] = 0;
  38317. }
  38318. }
  38319. if (useMorphTargets) {
  38320. var manager = mesh.morphTargetManager;
  38321. if (manager) {
  38322. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38323. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38324. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38325. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38326. }
  38327. else {
  38328. defines["MORPHTARGETS_TANGENT"] = false;
  38329. defines["MORPHTARGETS_NORMAL"] = false;
  38330. defines["MORPHTARGETS"] = false;
  38331. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38332. }
  38333. }
  38334. return true;
  38335. };
  38336. /**
  38337. * Prepares the defines related to the light information passed in parameter
  38338. * @param scene The scene we are intending to draw
  38339. * @param mesh The mesh the effect is compiling for
  38340. * @param defines The defines to update
  38341. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38342. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38343. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38344. * @returns true if normals will be required for the rest of the effect
  38345. */
  38346. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38347. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38348. if (disableLighting === void 0) { disableLighting = false; }
  38349. if (!defines._areLightsDirty) {
  38350. return defines._needNormals;
  38351. }
  38352. var lightIndex = 0;
  38353. var needNormals = false;
  38354. var needRebuild = false;
  38355. var lightmapMode = false;
  38356. var shadowEnabled = false;
  38357. var specularEnabled = false;
  38358. if (scene.lightsEnabled && !disableLighting) {
  38359. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38360. var light = _a[_i];
  38361. needNormals = true;
  38362. if (defines["LIGHT" + lightIndex] === undefined) {
  38363. needRebuild = true;
  38364. }
  38365. defines["LIGHT" + lightIndex] = true;
  38366. defines["SPOTLIGHT" + lightIndex] = false;
  38367. defines["HEMILIGHT" + lightIndex] = false;
  38368. defines["POINTLIGHT" + lightIndex] = false;
  38369. defines["DIRLIGHT" + lightIndex] = false;
  38370. var type;
  38371. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38372. type = "SPOTLIGHT" + lightIndex;
  38373. var spotLight = light;
  38374. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38375. }
  38376. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38377. type = "HEMILIGHT" + lightIndex;
  38378. }
  38379. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38380. type = "POINTLIGHT" + lightIndex;
  38381. }
  38382. else {
  38383. type = "DIRLIGHT" + lightIndex;
  38384. }
  38385. defines[type] = true;
  38386. // Specular
  38387. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38388. specularEnabled = true;
  38389. }
  38390. // Shadows
  38391. defines["SHADOW" + lightIndex] = false;
  38392. defines["SHADOWPCF" + lightIndex] = false;
  38393. defines["SHADOWESM" + lightIndex] = false;
  38394. defines["SHADOWCUBE" + lightIndex] = false;
  38395. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38396. var shadowGenerator = light.getShadowGenerator();
  38397. if (shadowGenerator) {
  38398. shadowEnabled = true;
  38399. shadowGenerator.prepareDefines(defines, lightIndex);
  38400. }
  38401. }
  38402. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38403. lightmapMode = true;
  38404. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38405. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38406. }
  38407. else {
  38408. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38409. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38410. }
  38411. lightIndex++;
  38412. if (lightIndex === maxSimultaneousLights)
  38413. break;
  38414. }
  38415. }
  38416. defines["SPECULARTERM"] = specularEnabled;
  38417. defines["SHADOWS"] = shadowEnabled;
  38418. // Resetting all other lights if any
  38419. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38420. if (defines["LIGHT" + index] !== undefined) {
  38421. defines["LIGHT" + index] = false;
  38422. defines["HEMILIGHT" + lightIndex] = false;
  38423. defines["POINTLIGHT" + lightIndex] = false;
  38424. defines["DIRLIGHT" + lightIndex] = false;
  38425. defines["SPOTLIGHT" + lightIndex] = false;
  38426. defines["SHADOW" + lightIndex] = false;
  38427. }
  38428. }
  38429. var caps = scene.getEngine().getCaps();
  38430. if (defines["SHADOWFLOAT"] === undefined) {
  38431. needRebuild = true;
  38432. }
  38433. defines["SHADOWFLOAT"] = shadowEnabled &&
  38434. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38435. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38436. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38437. if (needRebuild) {
  38438. defines.rebuild();
  38439. }
  38440. return needNormals;
  38441. };
  38442. /**
  38443. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38444. * that won t be acctive due to defines being turned off.
  38445. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38446. * @param samplersList The samplers list
  38447. * @param defines The defines helping in the list generation
  38448. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38449. */
  38450. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38451. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38452. var uniformsList;
  38453. var uniformBuffersList = null;
  38454. if (uniformsListOrOptions.uniformsNames) {
  38455. var options = uniformsListOrOptions;
  38456. uniformsList = options.uniformsNames;
  38457. uniformBuffersList = options.uniformBuffersNames;
  38458. samplersList = options.samplers;
  38459. defines = options.defines;
  38460. maxSimultaneousLights = options.maxSimultaneousLights;
  38461. }
  38462. else {
  38463. uniformsList = uniformsListOrOptions;
  38464. if (!samplersList) {
  38465. samplersList = [];
  38466. }
  38467. }
  38468. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38469. if (!defines["LIGHT" + lightIndex]) {
  38470. break;
  38471. }
  38472. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38473. if (uniformBuffersList) {
  38474. uniformBuffersList.push("Light" + lightIndex);
  38475. }
  38476. samplersList.push("shadowSampler" + lightIndex);
  38477. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38478. samplersList.push("projectionLightSampler" + lightIndex);
  38479. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38480. }
  38481. }
  38482. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38483. uniformsList.push("morphTargetInfluences");
  38484. }
  38485. };
  38486. /**
  38487. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38488. * @param defines The defines to update while falling back
  38489. * @param fallbacks The authorized effect fallbacks
  38490. * @param maxSimultaneousLights The maximum number of lights allowed
  38491. * @param rank the current rank of the Effect
  38492. * @returns The newly affected rank
  38493. */
  38494. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38495. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38496. if (rank === void 0) { rank = 0; }
  38497. var lightFallbackRank = 0;
  38498. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38499. if (!defines["LIGHT" + lightIndex]) {
  38500. break;
  38501. }
  38502. if (lightIndex > 0) {
  38503. lightFallbackRank = rank + lightIndex;
  38504. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38505. }
  38506. if (!defines["SHADOWS"]) {
  38507. if (defines["SHADOW" + lightIndex]) {
  38508. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38509. }
  38510. if (defines["SHADOWPCF" + lightIndex]) {
  38511. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38512. }
  38513. if (defines["SHADOWESM" + lightIndex]) {
  38514. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38515. }
  38516. }
  38517. }
  38518. return lightFallbackRank++;
  38519. };
  38520. /**
  38521. * Prepares the list of attributes required for morph targets according to the effect defines.
  38522. * @param attribs The current list of supported attribs
  38523. * @param mesh The mesh to prepare the morph targets attributes for
  38524. * @param defines The current Defines of the effect
  38525. */
  38526. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38527. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38528. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38529. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38530. var manager = mesh.morphTargetManager;
  38531. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38532. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38533. for (var index = 0; index < influencers; index++) {
  38534. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38535. if (normal) {
  38536. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38537. }
  38538. if (tangent) {
  38539. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38540. }
  38541. if (attribs.length > maxAttributesCount) {
  38542. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38543. }
  38544. }
  38545. }
  38546. };
  38547. /**
  38548. * Prepares the list of attributes required for bones according to the effect defines.
  38549. * @param attribs The current list of supported attribs
  38550. * @param mesh The mesh to prepare the bones attributes for
  38551. * @param defines The current Defines of the effect
  38552. * @param fallbacks The current efffect fallback strategy
  38553. */
  38554. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38555. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38556. fallbacks.addCPUSkinningFallback(0, mesh);
  38557. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38558. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38559. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38560. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38561. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38562. }
  38563. }
  38564. };
  38565. /**
  38566. * Prepares the list of attributes required for instances according to the effect defines.
  38567. * @param attribs The current list of supported attribs
  38568. * @param defines The current Defines of the effect
  38569. */
  38570. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38571. if (defines["INSTANCES"]) {
  38572. attribs.push("world0");
  38573. attribs.push("world1");
  38574. attribs.push("world2");
  38575. attribs.push("world3");
  38576. }
  38577. };
  38578. /**
  38579. * Binds the light shadow information to the effect for the given mesh.
  38580. * @param light The light containing the generator
  38581. * @param scene The scene the lights belongs to
  38582. * @param mesh The mesh we are binding the information to render
  38583. * @param lightIndex The light index in the effect used to render the mesh
  38584. * @param effect The effect we are binding the data to
  38585. */
  38586. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38587. if (light.shadowEnabled && mesh.receiveShadows) {
  38588. var shadowGenerator = light.getShadowGenerator();
  38589. if (shadowGenerator) {
  38590. shadowGenerator.bindShadowLight(lightIndex, effect);
  38591. }
  38592. }
  38593. };
  38594. /**
  38595. * Binds the light information to the effect.
  38596. * @param light The light containing the generator
  38597. * @param effect The effect we are binding the data to
  38598. * @param lightIndex The light index in the effect used to render
  38599. */
  38600. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38601. light.transferToEffect(effect, lightIndex + "");
  38602. };
  38603. /**
  38604. * Binds the lights information from the scene to the effect for the given mesh.
  38605. * @param scene The scene the lights belongs to
  38606. * @param mesh The mesh we are binding the information to render
  38607. * @param effect The effect we are binding the data to
  38608. * @param defines The generated defines for the effect
  38609. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38610. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38611. */
  38612. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38613. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38614. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38615. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38616. for (var i = 0; i < len; i++) {
  38617. var light = mesh._lightSources[i];
  38618. var iAsString = i.toString();
  38619. var scaledIntensity = light.getScaledIntensity();
  38620. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38621. MaterialHelper.BindLightProperties(light, effect, i);
  38622. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38623. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38624. if (defines["SPECULARTERM"]) {
  38625. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38626. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38627. }
  38628. // Shadows
  38629. if (scene.shadowsEnabled) {
  38630. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38631. }
  38632. light._uniformBuffer.update();
  38633. }
  38634. };
  38635. /**
  38636. * Binds the fog information from the scene to the effect for the given mesh.
  38637. * @param scene The scene the lights belongs to
  38638. * @param mesh The mesh we are binding the information to render
  38639. * @param effect The effect we are binding the data to
  38640. */
  38641. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38642. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38643. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38644. effect.setColor3("vFogColor", scene.fogColor);
  38645. }
  38646. };
  38647. /**
  38648. * Binds the bones information from the mesh to the effect.
  38649. * @param mesh The mesh we are binding the information to render
  38650. * @param effect The effect we are binding the data to
  38651. */
  38652. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38653. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38654. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38655. if (matrices && effect) {
  38656. effect.setMatrices("mBones", matrices);
  38657. }
  38658. }
  38659. };
  38660. /**
  38661. * Binds the morph targets information from the mesh to the effect.
  38662. * @param abstractMesh The mesh we are binding the information to render
  38663. * @param effect The effect we are binding the data to
  38664. */
  38665. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38666. var manager = abstractMesh.morphTargetManager;
  38667. if (!abstractMesh || !manager) {
  38668. return;
  38669. }
  38670. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38671. };
  38672. /**
  38673. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38674. * @param defines The generated defines used in the effect
  38675. * @param effect The effect we are binding the data to
  38676. * @param scene The scene we are willing to render with logarithmic scale for
  38677. */
  38678. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38679. if (defines["LOGARITHMICDEPTH"]) {
  38680. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38681. }
  38682. };
  38683. /**
  38684. * Binds the clip plane information from the scene to the effect.
  38685. * @param scene The scene the clip plane information are extracted from
  38686. * @param effect The effect we are binding the data to
  38687. */
  38688. MaterialHelper.BindClipPlane = function (effect, scene) {
  38689. if (scene.clipPlane) {
  38690. var clipPlane = scene.clipPlane;
  38691. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38692. }
  38693. };
  38694. return MaterialHelper;
  38695. }());
  38696. BABYLON.MaterialHelper = MaterialHelper;
  38697. })(BABYLON || (BABYLON = {}));
  38698. //# sourceMappingURL=babylon.materialHelper.js.map
  38699. var BABYLON;
  38700. (function (BABYLON) {
  38701. var PushMaterial = /** @class */ (function (_super) {
  38702. __extends(PushMaterial, _super);
  38703. function PushMaterial(name, scene) {
  38704. var _this = _super.call(this, name, scene) || this;
  38705. _this._normalMatrix = new BABYLON.Matrix();
  38706. _this.storeEffectOnSubMeshes = true;
  38707. return _this;
  38708. }
  38709. PushMaterial.prototype.getEffect = function () {
  38710. return this._activeEffect;
  38711. };
  38712. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38713. if (!mesh) {
  38714. return false;
  38715. }
  38716. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38717. return true;
  38718. }
  38719. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38720. };
  38721. /**
  38722. * Binds the given world matrix to the active effect
  38723. *
  38724. * @param world the matrix to bind
  38725. */
  38726. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38727. this._activeEffect.setMatrix("world", world);
  38728. };
  38729. /**
  38730. * Binds the given normal matrix to the active effect
  38731. *
  38732. * @param normalMatrix the matrix to bind
  38733. */
  38734. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38735. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38736. };
  38737. PushMaterial.prototype.bind = function (world, mesh) {
  38738. if (!mesh) {
  38739. return;
  38740. }
  38741. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38742. };
  38743. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38744. if (effect === void 0) { effect = null; }
  38745. _super.prototype._afterBind.call(this, mesh);
  38746. this.getScene()._cachedEffect = effect;
  38747. };
  38748. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38749. if (visibility === void 0) { visibility = 1; }
  38750. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38751. };
  38752. return PushMaterial;
  38753. }(BABYLON.Material));
  38754. BABYLON.PushMaterial = PushMaterial;
  38755. })(BABYLON || (BABYLON = {}));
  38756. //# sourceMappingURL=babylon.pushMaterial.js.map
  38757. var BABYLON;
  38758. (function (BABYLON) {
  38759. /** @ignore */
  38760. var StandardMaterialDefines = /** @class */ (function (_super) {
  38761. __extends(StandardMaterialDefines, _super);
  38762. function StandardMaterialDefines() {
  38763. var _this = _super.call(this) || this;
  38764. _this.MAINUV1 = false;
  38765. _this.MAINUV2 = false;
  38766. _this.DIFFUSE = false;
  38767. _this.DIFFUSEDIRECTUV = 0;
  38768. _this.AMBIENT = false;
  38769. _this.AMBIENTDIRECTUV = 0;
  38770. _this.OPACITY = false;
  38771. _this.OPACITYDIRECTUV = 0;
  38772. _this.OPACITYRGB = false;
  38773. _this.REFLECTION = false;
  38774. _this.EMISSIVE = false;
  38775. _this.EMISSIVEDIRECTUV = 0;
  38776. _this.SPECULAR = false;
  38777. _this.SPECULARDIRECTUV = 0;
  38778. _this.BUMP = false;
  38779. _this.BUMPDIRECTUV = 0;
  38780. _this.PARALLAX = false;
  38781. _this.PARALLAXOCCLUSION = false;
  38782. _this.SPECULAROVERALPHA = false;
  38783. _this.CLIPPLANE = false;
  38784. _this.ALPHATEST = false;
  38785. _this.DEPTHPREPASS = false;
  38786. _this.ALPHAFROMDIFFUSE = false;
  38787. _this.POINTSIZE = false;
  38788. _this.FOG = false;
  38789. _this.SPECULARTERM = false;
  38790. _this.DIFFUSEFRESNEL = false;
  38791. _this.OPACITYFRESNEL = false;
  38792. _this.REFLECTIONFRESNEL = false;
  38793. _this.REFRACTIONFRESNEL = false;
  38794. _this.EMISSIVEFRESNEL = false;
  38795. _this.FRESNEL = false;
  38796. _this.NORMAL = false;
  38797. _this.UV1 = false;
  38798. _this.UV2 = false;
  38799. _this.VERTEXCOLOR = false;
  38800. _this.VERTEXALPHA = false;
  38801. _this.NUM_BONE_INFLUENCERS = 0;
  38802. _this.BonesPerMesh = 0;
  38803. _this.INSTANCES = false;
  38804. _this.GLOSSINESS = false;
  38805. _this.ROUGHNESS = false;
  38806. _this.EMISSIVEASILLUMINATION = false;
  38807. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38808. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38809. _this.LIGHTMAP = false;
  38810. _this.LIGHTMAPDIRECTUV = 0;
  38811. _this.OBJECTSPACE_NORMALMAP = false;
  38812. _this.USELIGHTMAPASSHADOWMAP = false;
  38813. _this.REFLECTIONMAP_3D = false;
  38814. _this.REFLECTIONMAP_SPHERICAL = false;
  38815. _this.REFLECTIONMAP_PLANAR = false;
  38816. _this.REFLECTIONMAP_CUBIC = false;
  38817. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38818. _this.REFLECTIONMAP_PROJECTION = false;
  38819. _this.REFLECTIONMAP_SKYBOX = false;
  38820. _this.REFLECTIONMAP_EXPLICIT = false;
  38821. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38822. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38823. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38824. _this.INVERTCUBICMAP = false;
  38825. _this.LOGARITHMICDEPTH = false;
  38826. _this.REFRACTION = false;
  38827. _this.REFRACTIONMAP_3D = false;
  38828. _this.REFLECTIONOVERALPHA = false;
  38829. _this.TWOSIDEDLIGHTING = false;
  38830. _this.SHADOWFLOAT = false;
  38831. _this.MORPHTARGETS = false;
  38832. _this.MORPHTARGETS_NORMAL = false;
  38833. _this.MORPHTARGETS_TANGENT = false;
  38834. _this.NUM_MORPH_INFLUENCERS = 0;
  38835. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38836. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38837. _this.IMAGEPROCESSING = false;
  38838. _this.VIGNETTE = false;
  38839. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38840. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38841. _this.TONEMAPPING = false;
  38842. _this.CONTRAST = false;
  38843. _this.COLORCURVES = false;
  38844. _this.COLORGRADING = false;
  38845. _this.COLORGRADING3D = false;
  38846. _this.SAMPLER3DGREENDEPTH = false;
  38847. _this.SAMPLER3DBGRMAP = false;
  38848. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38849. _this.EXPOSURE = false;
  38850. _this.GRAIN = false;
  38851. _this.rebuild();
  38852. return _this;
  38853. }
  38854. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38855. var modes = [
  38856. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38857. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38858. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38859. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38860. ];
  38861. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38862. var mode = modes_1[_i];
  38863. this[mode] = (mode === modeToEnable);
  38864. }
  38865. };
  38866. return StandardMaterialDefines;
  38867. }(BABYLON.MaterialDefines));
  38868. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38869. var StandardMaterial = /** @class */ (function (_super) {
  38870. __extends(StandardMaterial, _super);
  38871. function StandardMaterial(name, scene) {
  38872. var _this = _super.call(this, name, scene) || this;
  38873. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38874. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38875. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38876. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38877. _this.specularPower = 64;
  38878. _this._useAlphaFromDiffuseTexture = false;
  38879. _this._useEmissiveAsIllumination = false;
  38880. _this._linkEmissiveWithDiffuse = false;
  38881. _this._useSpecularOverAlpha = false;
  38882. _this._useReflectionOverAlpha = false;
  38883. _this._disableLighting = false;
  38884. _this._useObjectSpaceNormalMap = false;
  38885. _this._useParallax = false;
  38886. _this._useParallaxOcclusion = false;
  38887. _this.parallaxScaleBias = 0.05;
  38888. _this._roughness = 0;
  38889. _this.indexOfRefraction = 0.98;
  38890. _this.invertRefractionY = true;
  38891. _this._useLightmapAsShadowmap = false;
  38892. _this._useReflectionFresnelFromSpecular = false;
  38893. _this._useGlossinessFromSpecularMapAlpha = false;
  38894. _this._maxSimultaneousLights = 4;
  38895. /**
  38896. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38897. */
  38898. _this._invertNormalMapX = false;
  38899. /**
  38900. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38901. */
  38902. _this._invertNormalMapY = false;
  38903. /**
  38904. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38905. */
  38906. _this._twoSidedLighting = false;
  38907. _this._renderTargets = new BABYLON.SmartArray(16);
  38908. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38909. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38910. // Setup the default processing configuration to the scene.
  38911. _this._attachImageProcessingConfiguration(null);
  38912. _this.getRenderTargetTextures = function () {
  38913. _this._renderTargets.reset();
  38914. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38915. _this._renderTargets.push(_this._reflectionTexture);
  38916. }
  38917. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38918. _this._renderTargets.push(_this._refractionTexture);
  38919. }
  38920. return _this._renderTargets;
  38921. };
  38922. return _this;
  38923. }
  38924. ;
  38925. ;
  38926. ;
  38927. ;
  38928. ;
  38929. ;
  38930. ;
  38931. ;
  38932. ;
  38933. ;
  38934. ;
  38935. ;
  38936. ;
  38937. ;
  38938. ;
  38939. ;
  38940. ;
  38941. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38942. /**
  38943. * Gets the image processing configuration used either in this material.
  38944. */
  38945. get: function () {
  38946. return this._imageProcessingConfiguration;
  38947. },
  38948. /**
  38949. * Sets the Default image processing configuration used either in the this material.
  38950. *
  38951. * If sets to null, the scene one is in use.
  38952. */
  38953. set: function (value) {
  38954. this._attachImageProcessingConfiguration(value);
  38955. // Ensure the effect will be rebuilt.
  38956. this._markAllSubMeshesAsTexturesDirty();
  38957. },
  38958. enumerable: true,
  38959. configurable: true
  38960. });
  38961. /**
  38962. * Attaches a new image processing configuration to the Standard Material.
  38963. * @param configuration
  38964. */
  38965. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38966. var _this = this;
  38967. if (configuration === this._imageProcessingConfiguration) {
  38968. return;
  38969. }
  38970. // Detaches observer.
  38971. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38972. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38973. }
  38974. // Pick the scene configuration if needed.
  38975. if (!configuration) {
  38976. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38977. }
  38978. else {
  38979. this._imageProcessingConfiguration = configuration;
  38980. }
  38981. // Attaches observer.
  38982. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38983. _this._markAllSubMeshesAsImageProcessingDirty();
  38984. });
  38985. };
  38986. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38987. /**
  38988. * Gets wether the color curves effect is enabled.
  38989. */
  38990. get: function () {
  38991. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38992. },
  38993. /**
  38994. * Sets wether the color curves effect is enabled.
  38995. */
  38996. set: function (value) {
  38997. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38998. },
  38999. enumerable: true,
  39000. configurable: true
  39001. });
  39002. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39003. /**
  39004. * Gets wether the color grading effect is enabled.
  39005. */
  39006. get: function () {
  39007. return this.imageProcessingConfiguration.colorGradingEnabled;
  39008. },
  39009. /**
  39010. * Gets wether the color grading effect is enabled.
  39011. */
  39012. set: function (value) {
  39013. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39014. },
  39015. enumerable: true,
  39016. configurable: true
  39017. });
  39018. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39019. /**
  39020. * Gets wether tonemapping is enabled or not.
  39021. */
  39022. get: function () {
  39023. return this._imageProcessingConfiguration.toneMappingEnabled;
  39024. },
  39025. /**
  39026. * Sets wether tonemapping is enabled or not
  39027. */
  39028. set: function (value) {
  39029. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39030. },
  39031. enumerable: true,
  39032. configurable: true
  39033. });
  39034. ;
  39035. ;
  39036. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39037. /**
  39038. * The camera exposure used on this material.
  39039. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39040. * This corresponds to a photographic exposure.
  39041. */
  39042. get: function () {
  39043. return this._imageProcessingConfiguration.exposure;
  39044. },
  39045. /**
  39046. * The camera exposure used on this material.
  39047. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39048. * This corresponds to a photographic exposure.
  39049. */
  39050. set: function (value) {
  39051. this._imageProcessingConfiguration.exposure = value;
  39052. },
  39053. enumerable: true,
  39054. configurable: true
  39055. });
  39056. ;
  39057. ;
  39058. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39059. /**
  39060. * Gets The camera contrast used on this material.
  39061. */
  39062. get: function () {
  39063. return this._imageProcessingConfiguration.contrast;
  39064. },
  39065. /**
  39066. * Sets The camera contrast used on this material.
  39067. */
  39068. set: function (value) {
  39069. this._imageProcessingConfiguration.contrast = value;
  39070. },
  39071. enumerable: true,
  39072. configurable: true
  39073. });
  39074. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39075. /**
  39076. * Gets the Color Grading 2D Lookup Texture.
  39077. */
  39078. get: function () {
  39079. return this._imageProcessingConfiguration.colorGradingTexture;
  39080. },
  39081. /**
  39082. * Sets the Color Grading 2D Lookup Texture.
  39083. */
  39084. set: function (value) {
  39085. this._imageProcessingConfiguration.colorGradingTexture = value;
  39086. },
  39087. enumerable: true,
  39088. configurable: true
  39089. });
  39090. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39091. /**
  39092. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39093. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39094. * 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;
  39095. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39096. */
  39097. get: function () {
  39098. return this._imageProcessingConfiguration.colorCurves;
  39099. },
  39100. /**
  39101. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39102. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39103. * 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;
  39104. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39105. */
  39106. set: function (value) {
  39107. this._imageProcessingConfiguration.colorCurves = value;
  39108. },
  39109. enumerable: true,
  39110. configurable: true
  39111. });
  39112. StandardMaterial.prototype.getClassName = function () {
  39113. return "StandardMaterial";
  39114. };
  39115. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39116. get: function () {
  39117. return this._useLogarithmicDepth;
  39118. },
  39119. set: function (value) {
  39120. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39121. this._markAllSubMeshesAsMiscDirty();
  39122. },
  39123. enumerable: true,
  39124. configurable: true
  39125. });
  39126. StandardMaterial.prototype.needAlphaBlending = function () {
  39127. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39128. };
  39129. StandardMaterial.prototype.needAlphaTesting = function () {
  39130. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39131. };
  39132. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39133. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39134. };
  39135. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39136. return this._diffuseTexture;
  39137. };
  39138. /**
  39139. * Child classes can use it to update shaders
  39140. */
  39141. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39142. if (useInstances === void 0) { useInstances = false; }
  39143. if (subMesh.effect && this.isFrozen) {
  39144. if (this._wasPreviouslyReady && subMesh.effect) {
  39145. return true;
  39146. }
  39147. }
  39148. if (!subMesh._materialDefines) {
  39149. subMesh._materialDefines = new StandardMaterialDefines();
  39150. }
  39151. var scene = this.getScene();
  39152. var defines = subMesh._materialDefines;
  39153. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39154. if (defines._renderId === scene.getRenderId()) {
  39155. return true;
  39156. }
  39157. }
  39158. var engine = scene.getEngine();
  39159. // Lights
  39160. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39161. // Textures
  39162. if (defines._areTexturesDirty) {
  39163. defines._needUVs = false;
  39164. defines.MAINUV1 = false;
  39165. defines.MAINUV2 = false;
  39166. if (scene.texturesEnabled) {
  39167. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39168. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39169. return false;
  39170. }
  39171. else {
  39172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39173. }
  39174. }
  39175. else {
  39176. defines.DIFFUSE = false;
  39177. }
  39178. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39179. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39180. return false;
  39181. }
  39182. else {
  39183. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39184. }
  39185. }
  39186. else {
  39187. defines.AMBIENT = false;
  39188. }
  39189. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39190. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39191. return false;
  39192. }
  39193. else {
  39194. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39195. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39196. }
  39197. }
  39198. else {
  39199. defines.OPACITY = false;
  39200. }
  39201. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39202. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39203. return false;
  39204. }
  39205. else {
  39206. defines._needNormals = true;
  39207. defines.REFLECTION = true;
  39208. defines.ROUGHNESS = (this._roughness > 0);
  39209. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39210. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39211. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39212. switch (this._reflectionTexture.coordinatesMode) {
  39213. case BABYLON.Texture.CUBIC_MODE:
  39214. case BABYLON.Texture.INVCUBIC_MODE:
  39215. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39216. break;
  39217. case BABYLON.Texture.EXPLICIT_MODE:
  39218. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39219. break;
  39220. case BABYLON.Texture.PLANAR_MODE:
  39221. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39222. break;
  39223. case BABYLON.Texture.PROJECTION_MODE:
  39224. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39225. break;
  39226. case BABYLON.Texture.SKYBOX_MODE:
  39227. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39228. break;
  39229. case BABYLON.Texture.SPHERICAL_MODE:
  39230. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39231. break;
  39232. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39233. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39234. break;
  39235. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39236. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39237. break;
  39238. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39239. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39240. break;
  39241. }
  39242. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39243. }
  39244. }
  39245. else {
  39246. defines.REFLECTION = false;
  39247. }
  39248. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39249. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39250. return false;
  39251. }
  39252. else {
  39253. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39254. }
  39255. }
  39256. else {
  39257. defines.EMISSIVE = false;
  39258. }
  39259. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39260. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39261. return false;
  39262. }
  39263. else {
  39264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39265. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39266. }
  39267. }
  39268. else {
  39269. defines.LIGHTMAP = false;
  39270. }
  39271. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39272. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39273. return false;
  39274. }
  39275. else {
  39276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39277. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39278. }
  39279. }
  39280. else {
  39281. defines.SPECULAR = false;
  39282. }
  39283. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39284. // Bump texure can not be not blocking.
  39285. if (!this._bumpTexture.isReady()) {
  39286. return false;
  39287. }
  39288. else {
  39289. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39290. defines.PARALLAX = this._useParallax;
  39291. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39292. }
  39293. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39294. }
  39295. else {
  39296. defines.BUMP = false;
  39297. }
  39298. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39299. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39300. return false;
  39301. }
  39302. else {
  39303. defines._needUVs = true;
  39304. defines.REFRACTION = true;
  39305. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39306. }
  39307. }
  39308. else {
  39309. defines.REFRACTION = false;
  39310. }
  39311. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39312. }
  39313. else {
  39314. defines.DIFFUSE = false;
  39315. defines.AMBIENT = false;
  39316. defines.OPACITY = false;
  39317. defines.REFLECTION = false;
  39318. defines.EMISSIVE = false;
  39319. defines.LIGHTMAP = false;
  39320. defines.BUMP = false;
  39321. defines.REFRACTION = false;
  39322. }
  39323. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39324. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39325. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39326. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39327. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39328. }
  39329. if (defines._areImageProcessingDirty) {
  39330. if (!this._imageProcessingConfiguration.isReady()) {
  39331. return false;
  39332. }
  39333. this._imageProcessingConfiguration.prepareDefines(defines);
  39334. }
  39335. if (defines._areFresnelDirty) {
  39336. if (StandardMaterial.FresnelEnabled) {
  39337. // Fresnel
  39338. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39339. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39340. this._reflectionFresnelParameters) {
  39341. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39342. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39343. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39344. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39345. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39346. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39347. defines._needNormals = true;
  39348. defines.FRESNEL = true;
  39349. }
  39350. }
  39351. else {
  39352. defines.FRESNEL = false;
  39353. }
  39354. }
  39355. // Misc.
  39356. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39357. // Attribs
  39358. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39359. // Values that need to be evaluated on every frame
  39360. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39361. // Get correct effect
  39362. if (defines.isDirty) {
  39363. defines.markAsProcessed();
  39364. scene.resetCachedMaterial();
  39365. // Fallbacks
  39366. var fallbacks = new BABYLON.EffectFallbacks();
  39367. if (defines.REFLECTION) {
  39368. fallbacks.addFallback(0, "REFLECTION");
  39369. }
  39370. if (defines.SPECULAR) {
  39371. fallbacks.addFallback(0, "SPECULAR");
  39372. }
  39373. if (defines.BUMP) {
  39374. fallbacks.addFallback(0, "BUMP");
  39375. }
  39376. if (defines.PARALLAX) {
  39377. fallbacks.addFallback(1, "PARALLAX");
  39378. }
  39379. if (defines.PARALLAXOCCLUSION) {
  39380. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39381. }
  39382. if (defines.SPECULAROVERALPHA) {
  39383. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39384. }
  39385. if (defines.FOG) {
  39386. fallbacks.addFallback(1, "FOG");
  39387. }
  39388. if (defines.POINTSIZE) {
  39389. fallbacks.addFallback(0, "POINTSIZE");
  39390. }
  39391. if (defines.LOGARITHMICDEPTH) {
  39392. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39393. }
  39394. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39395. if (defines.SPECULARTERM) {
  39396. fallbacks.addFallback(0, "SPECULARTERM");
  39397. }
  39398. if (defines.DIFFUSEFRESNEL) {
  39399. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39400. }
  39401. if (defines.OPACITYFRESNEL) {
  39402. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39403. }
  39404. if (defines.REFLECTIONFRESNEL) {
  39405. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39406. }
  39407. if (defines.EMISSIVEFRESNEL) {
  39408. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39409. }
  39410. if (defines.FRESNEL) {
  39411. fallbacks.addFallback(4, "FRESNEL");
  39412. }
  39413. //Attributes
  39414. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39415. if (defines.NORMAL) {
  39416. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39417. }
  39418. if (defines.UV1) {
  39419. attribs.push(BABYLON.VertexBuffer.UVKind);
  39420. }
  39421. if (defines.UV2) {
  39422. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39423. }
  39424. if (defines.VERTEXCOLOR) {
  39425. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39426. }
  39427. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39428. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39429. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39430. var shaderName = "default";
  39431. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39432. "vFogInfos", "vFogColor", "pointSize",
  39433. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39434. "mBones",
  39435. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39436. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39437. "vReflectionPosition", "vReflectionSize",
  39438. "logarithmicDepthConstant", "vTangentSpaceParams"
  39439. ];
  39440. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39441. var uniformBuffers = ["Material", "Scene"];
  39442. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39443. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39444. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39445. uniformsNames: uniforms,
  39446. uniformBuffersNames: uniformBuffers,
  39447. samplers: samplers,
  39448. defines: defines,
  39449. maxSimultaneousLights: this._maxSimultaneousLights
  39450. });
  39451. if (this.customShaderNameResolve) {
  39452. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39453. }
  39454. var join = defines.toString();
  39455. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39456. attributes: attribs,
  39457. uniformsNames: uniforms,
  39458. uniformBuffersNames: uniformBuffers,
  39459. samplers: samplers,
  39460. defines: join,
  39461. fallbacks: fallbacks,
  39462. onCompiled: this.onCompiled,
  39463. onError: this.onError,
  39464. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39465. }, engine), defines);
  39466. this.buildUniformLayout();
  39467. }
  39468. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39469. return false;
  39470. }
  39471. defines._renderId = scene.getRenderId();
  39472. this._wasPreviouslyReady = true;
  39473. return true;
  39474. };
  39475. StandardMaterial.prototype.buildUniformLayout = function () {
  39476. // Order is important !
  39477. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39478. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39479. this._uniformBuffer.addUniform("opacityParts", 4);
  39480. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39481. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39482. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39483. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39484. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39485. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39486. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39487. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39488. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39489. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39490. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39491. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39492. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39493. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39494. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39495. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39496. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39497. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39498. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39499. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39500. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39501. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39502. this._uniformBuffer.addUniform("specularMatrix", 16);
  39503. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39504. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39505. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39506. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39507. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39508. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39509. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39510. this._uniformBuffer.addUniform("pointSize", 1);
  39511. this._uniformBuffer.create();
  39512. };
  39513. StandardMaterial.prototype.unbind = function () {
  39514. if (this._activeEffect) {
  39515. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39516. this._activeEffect.setTexture("reflection2DSampler", null);
  39517. }
  39518. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39519. this._activeEffect.setTexture("refraction2DSampler", null);
  39520. }
  39521. }
  39522. _super.prototype.unbind.call(this);
  39523. };
  39524. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39525. var scene = this.getScene();
  39526. var defines = subMesh._materialDefines;
  39527. if (!defines) {
  39528. return;
  39529. }
  39530. var effect = subMesh.effect;
  39531. if (!effect) {
  39532. return;
  39533. }
  39534. this._activeEffect = effect;
  39535. // Matrices
  39536. this.bindOnlyWorldMatrix(world);
  39537. // Normal Matrix
  39538. if (defines.OBJECTSPACE_NORMALMAP) {
  39539. world.toNormalMatrix(this._normalMatrix);
  39540. this.bindOnlyNormalMatrix(this._normalMatrix);
  39541. }
  39542. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39543. // Bones
  39544. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39545. if (mustRebind) {
  39546. this._uniformBuffer.bindToEffect(effect, "Material");
  39547. this.bindViewProjection(effect);
  39548. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39549. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39550. // Fresnel
  39551. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39552. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39553. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39554. }
  39555. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39556. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39557. }
  39558. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39559. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39560. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39561. }
  39562. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39563. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39564. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39565. }
  39566. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39567. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39568. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39569. }
  39570. }
  39571. // Textures
  39572. if (scene.texturesEnabled) {
  39573. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39574. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39575. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39576. }
  39577. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39578. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39579. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39580. }
  39581. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39582. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39583. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39584. }
  39585. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39586. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39587. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39588. if (this._reflectionTexture.boundingBoxSize) {
  39589. var cubeTexture = this._reflectionTexture;
  39590. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39591. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39592. }
  39593. }
  39594. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39595. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39596. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39597. }
  39598. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39599. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39600. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39601. }
  39602. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39603. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39604. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39605. }
  39606. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39607. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39608. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39609. if (scene._mirroredCameraPosition) {
  39610. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39611. }
  39612. else {
  39613. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39614. }
  39615. }
  39616. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39617. var depth = 1.0;
  39618. if (!this._refractionTexture.isCube) {
  39619. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39620. if (this._refractionTexture.depth) {
  39621. depth = this._refractionTexture.depth;
  39622. }
  39623. }
  39624. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39625. }
  39626. }
  39627. // Point size
  39628. if (this.pointsCloud) {
  39629. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39630. }
  39631. if (defines.SPECULARTERM) {
  39632. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39633. }
  39634. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39635. // Diffuse
  39636. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39637. }
  39638. // Textures
  39639. if (scene.texturesEnabled) {
  39640. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39641. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39642. }
  39643. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39644. effect.setTexture("ambientSampler", this._ambientTexture);
  39645. }
  39646. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39647. effect.setTexture("opacitySampler", this._opacityTexture);
  39648. }
  39649. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39650. if (this._reflectionTexture.isCube) {
  39651. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39652. }
  39653. else {
  39654. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39655. }
  39656. }
  39657. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39658. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39659. }
  39660. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39661. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39662. }
  39663. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39664. effect.setTexture("specularSampler", this._specularTexture);
  39665. }
  39666. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39667. effect.setTexture("bumpSampler", this._bumpTexture);
  39668. }
  39669. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39670. var depth = 1.0;
  39671. if (this._refractionTexture.isCube) {
  39672. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39673. }
  39674. else {
  39675. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39676. }
  39677. }
  39678. }
  39679. // Clip plane
  39680. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39681. // Colors
  39682. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39683. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39684. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39685. }
  39686. if (mustRebind || !this.isFrozen) {
  39687. // Lights
  39688. if (scene.lightsEnabled && !this._disableLighting) {
  39689. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39690. }
  39691. // View
  39692. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39693. this.bindView(effect);
  39694. }
  39695. // Fog
  39696. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39697. // Morph targets
  39698. if (defines.NUM_MORPH_INFLUENCERS) {
  39699. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39700. }
  39701. // Log. depth
  39702. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39703. // image processing
  39704. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39705. this._imageProcessingConfiguration.bind(this._activeEffect);
  39706. }
  39707. }
  39708. this._uniformBuffer.update();
  39709. this._afterBind(mesh, this._activeEffect);
  39710. };
  39711. StandardMaterial.prototype.getAnimatables = function () {
  39712. var results = [];
  39713. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39714. results.push(this._diffuseTexture);
  39715. }
  39716. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39717. results.push(this._ambientTexture);
  39718. }
  39719. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39720. results.push(this._opacityTexture);
  39721. }
  39722. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39723. results.push(this._reflectionTexture);
  39724. }
  39725. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39726. results.push(this._emissiveTexture);
  39727. }
  39728. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39729. results.push(this._specularTexture);
  39730. }
  39731. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39732. results.push(this._bumpTexture);
  39733. }
  39734. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39735. results.push(this._lightmapTexture);
  39736. }
  39737. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39738. results.push(this._refractionTexture);
  39739. }
  39740. return results;
  39741. };
  39742. StandardMaterial.prototype.getActiveTextures = function () {
  39743. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39744. if (this._diffuseTexture) {
  39745. activeTextures.push(this._diffuseTexture);
  39746. }
  39747. if (this._ambientTexture) {
  39748. activeTextures.push(this._ambientTexture);
  39749. }
  39750. if (this._opacityTexture) {
  39751. activeTextures.push(this._opacityTexture);
  39752. }
  39753. if (this._reflectionTexture) {
  39754. activeTextures.push(this._reflectionTexture);
  39755. }
  39756. if (this._emissiveTexture) {
  39757. activeTextures.push(this._emissiveTexture);
  39758. }
  39759. if (this._specularTexture) {
  39760. activeTextures.push(this._specularTexture);
  39761. }
  39762. if (this._bumpTexture) {
  39763. activeTextures.push(this._bumpTexture);
  39764. }
  39765. if (this._lightmapTexture) {
  39766. activeTextures.push(this._lightmapTexture);
  39767. }
  39768. if (this._refractionTexture) {
  39769. activeTextures.push(this._refractionTexture);
  39770. }
  39771. return activeTextures;
  39772. };
  39773. StandardMaterial.prototype.hasTexture = function (texture) {
  39774. if (_super.prototype.hasTexture.call(this, texture)) {
  39775. return true;
  39776. }
  39777. if (this._diffuseTexture === texture) {
  39778. return true;
  39779. }
  39780. if (this._ambientTexture === texture) {
  39781. return true;
  39782. }
  39783. if (this._opacityTexture === texture) {
  39784. return true;
  39785. }
  39786. if (this._reflectionTexture === texture) {
  39787. return true;
  39788. }
  39789. if (this._emissiveTexture === texture) {
  39790. return true;
  39791. }
  39792. if (this._specularTexture === texture) {
  39793. return true;
  39794. }
  39795. if (this._bumpTexture === texture) {
  39796. return true;
  39797. }
  39798. if (this._lightmapTexture === texture) {
  39799. return true;
  39800. }
  39801. if (this._refractionTexture === texture) {
  39802. return true;
  39803. }
  39804. return false;
  39805. };
  39806. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39807. if (forceDisposeTextures) {
  39808. if (this._diffuseTexture) {
  39809. this._diffuseTexture.dispose();
  39810. }
  39811. if (this._ambientTexture) {
  39812. this._ambientTexture.dispose();
  39813. }
  39814. if (this._opacityTexture) {
  39815. this._opacityTexture.dispose();
  39816. }
  39817. if (this._reflectionTexture) {
  39818. this._reflectionTexture.dispose();
  39819. }
  39820. if (this._emissiveTexture) {
  39821. this._emissiveTexture.dispose();
  39822. }
  39823. if (this._specularTexture) {
  39824. this._specularTexture.dispose();
  39825. }
  39826. if (this._bumpTexture) {
  39827. this._bumpTexture.dispose();
  39828. }
  39829. if (this._lightmapTexture) {
  39830. this._lightmapTexture.dispose();
  39831. }
  39832. if (this._refractionTexture) {
  39833. this._refractionTexture.dispose();
  39834. }
  39835. }
  39836. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39837. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39838. }
  39839. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39840. };
  39841. StandardMaterial.prototype.clone = function (name) {
  39842. var _this = this;
  39843. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39844. result.name = name;
  39845. result.id = name;
  39846. return result;
  39847. };
  39848. StandardMaterial.prototype.serialize = function () {
  39849. return BABYLON.SerializationHelper.Serialize(this);
  39850. };
  39851. // Statics
  39852. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39853. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39854. };
  39855. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39856. get: function () {
  39857. return StandardMaterial._DiffuseTextureEnabled;
  39858. },
  39859. set: function (value) {
  39860. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39861. return;
  39862. }
  39863. StandardMaterial._DiffuseTextureEnabled = value;
  39864. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39865. },
  39866. enumerable: true,
  39867. configurable: true
  39868. });
  39869. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39870. get: function () {
  39871. return StandardMaterial._AmbientTextureEnabled;
  39872. },
  39873. set: function (value) {
  39874. if (StandardMaterial._AmbientTextureEnabled === value) {
  39875. return;
  39876. }
  39877. StandardMaterial._AmbientTextureEnabled = value;
  39878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39879. },
  39880. enumerable: true,
  39881. configurable: true
  39882. });
  39883. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39884. get: function () {
  39885. return StandardMaterial._OpacityTextureEnabled;
  39886. },
  39887. set: function (value) {
  39888. if (StandardMaterial._OpacityTextureEnabled === value) {
  39889. return;
  39890. }
  39891. StandardMaterial._OpacityTextureEnabled = value;
  39892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39893. },
  39894. enumerable: true,
  39895. configurable: true
  39896. });
  39897. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39898. get: function () {
  39899. return StandardMaterial._ReflectionTextureEnabled;
  39900. },
  39901. set: function (value) {
  39902. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39903. return;
  39904. }
  39905. StandardMaterial._ReflectionTextureEnabled = value;
  39906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39907. },
  39908. enumerable: true,
  39909. configurable: true
  39910. });
  39911. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39912. get: function () {
  39913. return StandardMaterial._EmissiveTextureEnabled;
  39914. },
  39915. set: function (value) {
  39916. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39917. return;
  39918. }
  39919. StandardMaterial._EmissiveTextureEnabled = value;
  39920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39921. },
  39922. enumerable: true,
  39923. configurable: true
  39924. });
  39925. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39926. get: function () {
  39927. return StandardMaterial._SpecularTextureEnabled;
  39928. },
  39929. set: function (value) {
  39930. if (StandardMaterial._SpecularTextureEnabled === value) {
  39931. return;
  39932. }
  39933. StandardMaterial._SpecularTextureEnabled = value;
  39934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39935. },
  39936. enumerable: true,
  39937. configurable: true
  39938. });
  39939. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39940. get: function () {
  39941. return StandardMaterial._BumpTextureEnabled;
  39942. },
  39943. set: function (value) {
  39944. if (StandardMaterial._BumpTextureEnabled === value) {
  39945. return;
  39946. }
  39947. StandardMaterial._BumpTextureEnabled = value;
  39948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39949. },
  39950. enumerable: true,
  39951. configurable: true
  39952. });
  39953. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39954. get: function () {
  39955. return StandardMaterial._LightmapTextureEnabled;
  39956. },
  39957. set: function (value) {
  39958. if (StandardMaterial._LightmapTextureEnabled === value) {
  39959. return;
  39960. }
  39961. StandardMaterial._LightmapTextureEnabled = value;
  39962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39963. },
  39964. enumerable: true,
  39965. configurable: true
  39966. });
  39967. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39968. get: function () {
  39969. return StandardMaterial._RefractionTextureEnabled;
  39970. },
  39971. set: function (value) {
  39972. if (StandardMaterial._RefractionTextureEnabled === value) {
  39973. return;
  39974. }
  39975. StandardMaterial._RefractionTextureEnabled = value;
  39976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39977. },
  39978. enumerable: true,
  39979. configurable: true
  39980. });
  39981. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39982. get: function () {
  39983. return StandardMaterial._ColorGradingTextureEnabled;
  39984. },
  39985. set: function (value) {
  39986. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39987. return;
  39988. }
  39989. StandardMaterial._ColorGradingTextureEnabled = value;
  39990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39991. },
  39992. enumerable: true,
  39993. configurable: true
  39994. });
  39995. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39996. get: function () {
  39997. return StandardMaterial._FresnelEnabled;
  39998. },
  39999. set: function (value) {
  40000. if (StandardMaterial._FresnelEnabled === value) {
  40001. return;
  40002. }
  40003. StandardMaterial._FresnelEnabled = value;
  40004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40005. },
  40006. enumerable: true,
  40007. configurable: true
  40008. });
  40009. // Flags used to enable or disable a type of texture for all Standard Materials
  40010. StandardMaterial._DiffuseTextureEnabled = true;
  40011. StandardMaterial._AmbientTextureEnabled = true;
  40012. StandardMaterial._OpacityTextureEnabled = true;
  40013. StandardMaterial._ReflectionTextureEnabled = true;
  40014. StandardMaterial._EmissiveTextureEnabled = true;
  40015. StandardMaterial._SpecularTextureEnabled = true;
  40016. StandardMaterial._BumpTextureEnabled = true;
  40017. StandardMaterial._LightmapTextureEnabled = true;
  40018. StandardMaterial._RefractionTextureEnabled = true;
  40019. StandardMaterial._ColorGradingTextureEnabled = true;
  40020. StandardMaterial._FresnelEnabled = true;
  40021. __decorate([
  40022. BABYLON.serializeAsTexture("diffuseTexture")
  40023. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40024. __decorate([
  40025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40026. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40027. __decorate([
  40028. BABYLON.serializeAsTexture("ambientTexture")
  40029. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40030. __decorate([
  40031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40032. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40033. __decorate([
  40034. BABYLON.serializeAsTexture("opacityTexture")
  40035. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40036. __decorate([
  40037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40038. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40039. __decorate([
  40040. BABYLON.serializeAsTexture("reflectionTexture")
  40041. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40042. __decorate([
  40043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40044. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40045. __decorate([
  40046. BABYLON.serializeAsTexture("emissiveTexture")
  40047. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40048. __decorate([
  40049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40050. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40051. __decorate([
  40052. BABYLON.serializeAsTexture("specularTexture")
  40053. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40054. __decorate([
  40055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40056. ], StandardMaterial.prototype, "specularTexture", void 0);
  40057. __decorate([
  40058. BABYLON.serializeAsTexture("bumpTexture")
  40059. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40060. __decorate([
  40061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40062. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40063. __decorate([
  40064. BABYLON.serializeAsTexture("lightmapTexture")
  40065. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40066. __decorate([
  40067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40068. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40069. __decorate([
  40070. BABYLON.serializeAsTexture("refractionTexture")
  40071. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40072. __decorate([
  40073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40074. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40075. __decorate([
  40076. BABYLON.serializeAsColor3("ambient")
  40077. ], StandardMaterial.prototype, "ambientColor", void 0);
  40078. __decorate([
  40079. BABYLON.serializeAsColor3("diffuse")
  40080. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40081. __decorate([
  40082. BABYLON.serializeAsColor3("specular")
  40083. ], StandardMaterial.prototype, "specularColor", void 0);
  40084. __decorate([
  40085. BABYLON.serializeAsColor3("emissive")
  40086. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40087. __decorate([
  40088. BABYLON.serialize()
  40089. ], StandardMaterial.prototype, "specularPower", void 0);
  40090. __decorate([
  40091. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40092. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40093. __decorate([
  40094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40095. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40096. __decorate([
  40097. BABYLON.serialize("useEmissiveAsIllumination")
  40098. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40099. __decorate([
  40100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40101. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40102. __decorate([
  40103. BABYLON.serialize("linkEmissiveWithDiffuse")
  40104. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40105. __decorate([
  40106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40107. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40108. __decorate([
  40109. BABYLON.serialize("useSpecularOverAlpha")
  40110. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40111. __decorate([
  40112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40113. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40114. __decorate([
  40115. BABYLON.serialize("useReflectionOverAlpha")
  40116. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40117. __decorate([
  40118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40119. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40120. __decorate([
  40121. BABYLON.serialize("disableLighting")
  40122. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40123. __decorate([
  40124. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40125. ], StandardMaterial.prototype, "disableLighting", void 0);
  40126. __decorate([
  40127. BABYLON.serialize("useObjectSpaceNormalMap")
  40128. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40129. __decorate([
  40130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40131. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40132. __decorate([
  40133. BABYLON.serialize("useParallax")
  40134. ], StandardMaterial.prototype, "_useParallax", void 0);
  40135. __decorate([
  40136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40137. ], StandardMaterial.prototype, "useParallax", void 0);
  40138. __decorate([
  40139. BABYLON.serialize("useParallaxOcclusion")
  40140. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40141. __decorate([
  40142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40143. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40144. __decorate([
  40145. BABYLON.serialize()
  40146. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40147. __decorate([
  40148. BABYLON.serialize("roughness")
  40149. ], StandardMaterial.prototype, "_roughness", void 0);
  40150. __decorate([
  40151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40152. ], StandardMaterial.prototype, "roughness", void 0);
  40153. __decorate([
  40154. BABYLON.serialize()
  40155. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40156. __decorate([
  40157. BABYLON.serialize()
  40158. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40159. __decorate([
  40160. BABYLON.serialize("useLightmapAsShadowmap")
  40161. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40162. __decorate([
  40163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40164. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40165. __decorate([
  40166. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40167. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40168. __decorate([
  40169. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40170. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40171. __decorate([
  40172. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40173. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40174. __decorate([
  40175. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40176. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40177. __decorate([
  40178. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40179. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40180. __decorate([
  40181. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40182. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40183. __decorate([
  40184. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40185. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40186. __decorate([
  40187. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40188. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40189. __decorate([
  40190. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40191. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40192. __decorate([
  40193. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40194. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40195. __decorate([
  40196. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40197. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40198. __decorate([
  40199. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40200. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40201. __decorate([
  40202. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40203. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40204. __decorate([
  40205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40206. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40207. __decorate([
  40208. BABYLON.serialize("maxSimultaneousLights")
  40209. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40210. __decorate([
  40211. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40212. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40213. __decorate([
  40214. BABYLON.serialize("invertNormalMapX")
  40215. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40216. __decorate([
  40217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40218. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40219. __decorate([
  40220. BABYLON.serialize("invertNormalMapY")
  40221. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40222. __decorate([
  40223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40224. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40225. __decorate([
  40226. BABYLON.serialize("twoSidedLighting")
  40227. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40228. __decorate([
  40229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40230. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40231. __decorate([
  40232. BABYLON.serialize()
  40233. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40234. return StandardMaterial;
  40235. }(BABYLON.PushMaterial));
  40236. BABYLON.StandardMaterial = StandardMaterial;
  40237. })(BABYLON || (BABYLON = {}));
  40238. //# sourceMappingURL=babylon.standardMaterial.js.map
  40239. var BABYLON;
  40240. (function (BABYLON) {
  40241. /**
  40242. * Manages the defines for the PBR Material.
  40243. */
  40244. var PBRMaterialDefines = /** @class */ (function (_super) {
  40245. __extends(PBRMaterialDefines, _super);
  40246. /**
  40247. * Initializes the PBR Material defines.
  40248. */
  40249. function PBRMaterialDefines() {
  40250. var _this = _super.call(this) || this;
  40251. _this.PBR = true;
  40252. _this.MAINUV1 = false;
  40253. _this.MAINUV2 = false;
  40254. _this.UV1 = false;
  40255. _this.UV2 = false;
  40256. _this.ALBEDO = false;
  40257. _this.ALBEDODIRECTUV = 0;
  40258. _this.VERTEXCOLOR = false;
  40259. _this.AMBIENT = false;
  40260. _this.AMBIENTDIRECTUV = 0;
  40261. _this.AMBIENTINGRAYSCALE = false;
  40262. _this.OPACITY = false;
  40263. _this.VERTEXALPHA = false;
  40264. _this.OPACITYDIRECTUV = 0;
  40265. _this.OPACITYRGB = false;
  40266. _this.ALPHATEST = false;
  40267. _this.DEPTHPREPASS = false;
  40268. _this.ALPHABLEND = false;
  40269. _this.ALPHAFROMALBEDO = false;
  40270. _this.ALPHATESTVALUE = 0.5;
  40271. _this.SPECULAROVERALPHA = false;
  40272. _this.RADIANCEOVERALPHA = false;
  40273. _this.ALPHAFRESNEL = false;
  40274. _this.LINEARALPHAFRESNEL = false;
  40275. _this.PREMULTIPLYALPHA = false;
  40276. _this.EMISSIVE = false;
  40277. _this.EMISSIVEDIRECTUV = 0;
  40278. _this.REFLECTIVITY = false;
  40279. _this.REFLECTIVITYDIRECTUV = 0;
  40280. _this.SPECULARTERM = false;
  40281. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40282. _this.MICROSURFACEAUTOMATIC = false;
  40283. _this.LODBASEDMICROSFURACE = false;
  40284. _this.MICROSURFACEMAP = false;
  40285. _this.MICROSURFACEMAPDIRECTUV = 0;
  40286. _this.METALLICWORKFLOW = false;
  40287. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40288. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40289. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40290. _this.AOSTOREINMETALMAPRED = false;
  40291. _this.ENVIRONMENTBRDF = false;
  40292. _this.NORMAL = false;
  40293. _this.TANGENT = false;
  40294. _this.BUMP = false;
  40295. _this.BUMPDIRECTUV = 0;
  40296. _this.OBJECTSPACE_NORMALMAP = false;
  40297. _this.PARALLAX = false;
  40298. _this.PARALLAXOCCLUSION = false;
  40299. _this.NORMALXYSCALE = true;
  40300. _this.LIGHTMAP = false;
  40301. _this.LIGHTMAPDIRECTUV = 0;
  40302. _this.USELIGHTMAPASSHADOWMAP = false;
  40303. _this.REFLECTION = false;
  40304. _this.REFLECTIONMAP_3D = false;
  40305. _this.REFLECTIONMAP_SPHERICAL = false;
  40306. _this.REFLECTIONMAP_PLANAR = false;
  40307. _this.REFLECTIONMAP_CUBIC = false;
  40308. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40309. _this.REFLECTIONMAP_PROJECTION = false;
  40310. _this.REFLECTIONMAP_SKYBOX = false;
  40311. _this.REFLECTIONMAP_EXPLICIT = false;
  40312. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40313. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40314. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40315. _this.INVERTCUBICMAP = false;
  40316. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40317. _this.USESPHERICALINVERTEX = false;
  40318. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40319. _this.LODINREFLECTIONALPHA = false;
  40320. _this.GAMMAREFLECTION = false;
  40321. _this.RADIANCEOCCLUSION = false;
  40322. _this.HORIZONOCCLUSION = false;
  40323. _this.REFRACTION = false;
  40324. _this.REFRACTIONMAP_3D = false;
  40325. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40326. _this.LODINREFRACTIONALPHA = false;
  40327. _this.GAMMAREFRACTION = false;
  40328. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40329. _this.INSTANCES = false;
  40330. _this.NUM_BONE_INFLUENCERS = 0;
  40331. _this.BonesPerMesh = 0;
  40332. _this.NONUNIFORMSCALING = false;
  40333. _this.MORPHTARGETS = false;
  40334. _this.MORPHTARGETS_NORMAL = false;
  40335. _this.MORPHTARGETS_TANGENT = false;
  40336. _this.NUM_MORPH_INFLUENCERS = 0;
  40337. _this.IMAGEPROCESSING = false;
  40338. _this.VIGNETTE = false;
  40339. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40340. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40341. _this.TONEMAPPING = false;
  40342. _this.CONTRAST = false;
  40343. _this.COLORCURVES = false;
  40344. _this.COLORGRADING = false;
  40345. _this.COLORGRADING3D = false;
  40346. _this.SAMPLER3DGREENDEPTH = false;
  40347. _this.SAMPLER3DBGRMAP = false;
  40348. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40349. _this.EXPOSURE = false;
  40350. _this.GRAIN = false;
  40351. _this.USEPHYSICALLIGHTFALLOFF = false;
  40352. _this.TWOSIDEDLIGHTING = false;
  40353. _this.SHADOWFLOAT = false;
  40354. _this.CLIPPLANE = false;
  40355. _this.POINTSIZE = false;
  40356. _this.FOG = false;
  40357. _this.LOGARITHMICDEPTH = false;
  40358. _this.FORCENORMALFORWARD = false;
  40359. _this.rebuild();
  40360. return _this;
  40361. }
  40362. /**
  40363. * Resets the PBR Material defines.
  40364. */
  40365. PBRMaterialDefines.prototype.reset = function () {
  40366. _super.prototype.reset.call(this);
  40367. this.ALPHATESTVALUE = 0.5;
  40368. this.PBR = true;
  40369. };
  40370. return PBRMaterialDefines;
  40371. }(BABYLON.MaterialDefines));
  40372. /**
  40373. * The Physically based material base class of BJS.
  40374. *
  40375. * This offers the main features of a standard PBR material.
  40376. * For more information, please refer to the documentation :
  40377. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40378. */
  40379. var PBRBaseMaterial = /** @class */ (function (_super) {
  40380. __extends(PBRBaseMaterial, _super);
  40381. /**
  40382. * Instantiates a new PBRMaterial instance.
  40383. *
  40384. * @param name The material name
  40385. * @param scene The scene the material will be use in.
  40386. */
  40387. function PBRBaseMaterial(name, scene) {
  40388. var _this = _super.call(this, name, scene) || this;
  40389. /**
  40390. * Intensity of the direct lights e.g. the four lights available in your scene.
  40391. * This impacts both the direct diffuse and specular highlights.
  40392. */
  40393. _this._directIntensity = 1.0;
  40394. /**
  40395. * Intensity of the emissive part of the material.
  40396. * This helps controlling the emissive effect without modifying the emissive color.
  40397. */
  40398. _this._emissiveIntensity = 1.0;
  40399. /**
  40400. * Intensity of the environment e.g. how much the environment will light the object
  40401. * either through harmonics for rough material or through the refelction for shiny ones.
  40402. */
  40403. _this._environmentIntensity = 1.0;
  40404. /**
  40405. * This is a special control allowing the reduction of the specular highlights coming from the
  40406. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40407. */
  40408. _this._specularIntensity = 1.0;
  40409. /**
  40410. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40411. */
  40412. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40413. /**
  40414. * Debug Control allowing disabling the bump map on this material.
  40415. */
  40416. _this._disableBumpMap = false;
  40417. /**
  40418. * AKA Occlusion Texture Intensity in other nomenclature.
  40419. */
  40420. _this._ambientTextureStrength = 1.0;
  40421. /**
  40422. * The color of a material in ambient lighting.
  40423. */
  40424. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40425. /**
  40426. * AKA Diffuse Color in other nomenclature.
  40427. */
  40428. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40429. /**
  40430. * AKA Specular Color in other nomenclature.
  40431. */
  40432. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40433. /**
  40434. * The color applied when light is reflected from a material.
  40435. */
  40436. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40437. /**
  40438. * The color applied when light is emitted from a material.
  40439. */
  40440. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40441. /**
  40442. * AKA Glossiness in other nomenclature.
  40443. */
  40444. _this._microSurface = 0.9;
  40445. /**
  40446. * source material index of refraction (IOR)' / 'destination material IOR.
  40447. */
  40448. _this._indexOfRefraction = 0.66;
  40449. /**
  40450. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40451. */
  40452. _this._invertRefractionY = false;
  40453. /**
  40454. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40455. * Materials half opaque for instance using refraction could benefit from this control.
  40456. */
  40457. _this._linkRefractionWithTransparency = false;
  40458. /**
  40459. * Specifies that the material will use the light map as a show map.
  40460. */
  40461. _this._useLightmapAsShadowmap = false;
  40462. /**
  40463. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40464. * makes the reflect vector face the model (under horizon).
  40465. */
  40466. _this._useHorizonOcclusion = true;
  40467. /**
  40468. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40469. * too much the area relying on ambient texture to define their ambient occlusion.
  40470. */
  40471. _this._useRadianceOcclusion = true;
  40472. /**
  40473. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40474. */
  40475. _this._useAlphaFromAlbedoTexture = false;
  40476. /**
  40477. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40478. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40479. */
  40480. _this._useSpecularOverAlpha = true;
  40481. /**
  40482. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40483. */
  40484. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40485. /**
  40486. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40487. */
  40488. _this._useRoughnessFromMetallicTextureAlpha = true;
  40489. /**
  40490. * Specifies if the metallic texture contains the roughness information in its green channel.
  40491. */
  40492. _this._useRoughnessFromMetallicTextureGreen = false;
  40493. /**
  40494. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40495. */
  40496. _this._useMetallnessFromMetallicTextureBlue = false;
  40497. /**
  40498. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40499. */
  40500. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40501. /**
  40502. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40503. */
  40504. _this._useAmbientInGrayScale = false;
  40505. /**
  40506. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40507. * The material will try to infer what glossiness each pixel should be.
  40508. */
  40509. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40510. /**
  40511. * BJS is using an harcoded light falloff based on a manually sets up range.
  40512. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40513. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40514. */
  40515. _this._usePhysicalLightFalloff = true;
  40516. /**
  40517. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40518. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40519. */
  40520. _this._useRadianceOverAlpha = true;
  40521. /**
  40522. * Allows using an object space normal map (instead of tangent space).
  40523. */
  40524. _this._useObjectSpaceNormalMap = false;
  40525. /**
  40526. * Allows using the bump map in parallax mode.
  40527. */
  40528. _this._useParallax = false;
  40529. /**
  40530. * Allows using the bump map in parallax occlusion mode.
  40531. */
  40532. _this._useParallaxOcclusion = false;
  40533. /**
  40534. * Controls the scale bias of the parallax mode.
  40535. */
  40536. _this._parallaxScaleBias = 0.05;
  40537. /**
  40538. * If sets to true, disables all the lights affecting the material.
  40539. */
  40540. _this._disableLighting = false;
  40541. /**
  40542. * Number of Simultaneous lights allowed on the material.
  40543. */
  40544. _this._maxSimultaneousLights = 4;
  40545. /**
  40546. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40547. */
  40548. _this._invertNormalMapX = false;
  40549. /**
  40550. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40551. */
  40552. _this._invertNormalMapY = false;
  40553. /**
  40554. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40555. */
  40556. _this._twoSidedLighting = false;
  40557. /**
  40558. * Defines the alpha limits in alpha test mode.
  40559. */
  40560. _this._alphaCutOff = 0.4;
  40561. /**
  40562. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40563. */
  40564. _this._forceAlphaTest = false;
  40565. /**
  40566. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40567. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40568. */
  40569. _this._useAlphaFresnel = false;
  40570. /**
  40571. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40572. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40573. */
  40574. _this._useLinearAlphaFresnel = false;
  40575. /**
  40576. * The transparency mode of the material.
  40577. */
  40578. _this._transparencyMode = null;
  40579. /**
  40580. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40581. * from cos thetav and roughness:
  40582. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40583. */
  40584. _this._environmentBRDFTexture = null;
  40585. /**
  40586. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40587. */
  40588. _this._forceIrradianceInFragment = false;
  40589. /**
  40590. * Force normal to face away from face.
  40591. */
  40592. _this._forceNormalForward = false;
  40593. /**
  40594. * Stores the available render targets.
  40595. */
  40596. _this._renderTargets = new BABYLON.SmartArray(16);
  40597. /**
  40598. * Sets the global ambient color for the material used in lighting calculations.
  40599. */
  40600. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40601. // Setup the default processing configuration to the scene.
  40602. _this._attachImageProcessingConfiguration(null);
  40603. _this.getRenderTargetTextures = function () {
  40604. _this._renderTargets.reset();
  40605. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40606. _this._renderTargets.push(_this._reflectionTexture);
  40607. }
  40608. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40609. _this._renderTargets.push(_this._refractionTexture);
  40610. }
  40611. return _this._renderTargets;
  40612. };
  40613. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40614. return _this;
  40615. }
  40616. /**
  40617. * Attaches a new image processing configuration to the PBR Material.
  40618. * @param configuration
  40619. */
  40620. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40621. var _this = this;
  40622. if (configuration === this._imageProcessingConfiguration) {
  40623. return;
  40624. }
  40625. // Detaches observer.
  40626. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40627. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40628. }
  40629. // Pick the scene configuration if needed.
  40630. if (!configuration) {
  40631. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40632. }
  40633. else {
  40634. this._imageProcessingConfiguration = configuration;
  40635. }
  40636. // Attaches observer.
  40637. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40638. _this._markAllSubMeshesAsImageProcessingDirty();
  40639. });
  40640. };
  40641. /**
  40642. * Gets the name of the material class.
  40643. */
  40644. PBRBaseMaterial.prototype.getClassName = function () {
  40645. return "PBRBaseMaterial";
  40646. };
  40647. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40648. /**
  40649. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40650. */
  40651. get: function () {
  40652. return this._useLogarithmicDepth;
  40653. },
  40654. /**
  40655. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40656. */
  40657. set: function (value) {
  40658. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40659. },
  40660. enumerable: true,
  40661. configurable: true
  40662. });
  40663. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40664. /**
  40665. * Gets the current transparency mode.
  40666. */
  40667. get: function () {
  40668. return this._transparencyMode;
  40669. },
  40670. /**
  40671. * Sets the transparency mode of the material.
  40672. */
  40673. set: function (value) {
  40674. if (this._transparencyMode === value) {
  40675. return;
  40676. }
  40677. this._transparencyMode = value;
  40678. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40679. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40680. },
  40681. enumerable: true,
  40682. configurable: true
  40683. });
  40684. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40685. /**
  40686. * Returns true if alpha blending should be disabled.
  40687. */
  40688. get: function () {
  40689. return (this._linkRefractionWithTransparency ||
  40690. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40691. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40692. },
  40693. enumerable: true,
  40694. configurable: true
  40695. });
  40696. /**
  40697. * Specifies whether or not this material should be rendered in alpha blend mode.
  40698. */
  40699. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40700. if (this._disableAlphaBlending) {
  40701. return false;
  40702. }
  40703. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40704. };
  40705. /**
  40706. * Specifies if the mesh will require alpha blending.
  40707. * @param mesh - BJS mesh.
  40708. */
  40709. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40710. if (this._disableAlphaBlending) {
  40711. return false;
  40712. }
  40713. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40714. };
  40715. /**
  40716. * Specifies whether or not this material should be rendered in alpha test mode.
  40717. */
  40718. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40719. if (this._forceAlphaTest) {
  40720. return true;
  40721. }
  40722. if (this._linkRefractionWithTransparency) {
  40723. return false;
  40724. }
  40725. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40726. };
  40727. /**
  40728. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40729. */
  40730. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40731. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40732. };
  40733. /**
  40734. * Gets the texture used for the alpha test.
  40735. */
  40736. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40737. return this._albedoTexture;
  40738. };
  40739. /**
  40740. * Specifies that the submesh is ready to be used.
  40741. * @param mesh - BJS mesh.
  40742. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40743. * @param useInstances - Specifies that instances should be used.
  40744. * @returns - boolean indicating that the submesh is ready or not.
  40745. */
  40746. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40747. if (subMesh.effect && this.isFrozen) {
  40748. if (this._wasPreviouslyReady) {
  40749. return true;
  40750. }
  40751. }
  40752. if (!subMesh._materialDefines) {
  40753. subMesh._materialDefines = new PBRMaterialDefines();
  40754. }
  40755. var defines = subMesh._materialDefines;
  40756. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40757. if (defines._renderId === this.getScene().getRenderId()) {
  40758. return true;
  40759. }
  40760. }
  40761. var scene = this.getScene();
  40762. var engine = scene.getEngine();
  40763. if (defines._areTexturesDirty) {
  40764. if (scene.texturesEnabled) {
  40765. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40766. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40767. return false;
  40768. }
  40769. }
  40770. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40771. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40772. return false;
  40773. }
  40774. }
  40775. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40776. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40777. return false;
  40778. }
  40779. }
  40780. var reflectionTexture = this._getReflectionTexture();
  40781. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40782. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40783. return false;
  40784. }
  40785. }
  40786. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40787. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40788. return false;
  40789. }
  40790. }
  40791. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40792. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40793. return false;
  40794. }
  40795. }
  40796. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40797. if (this._metallicTexture) {
  40798. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40799. return false;
  40800. }
  40801. }
  40802. else if (this._reflectivityTexture) {
  40803. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40804. return false;
  40805. }
  40806. }
  40807. if (this._microSurfaceTexture) {
  40808. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40809. return false;
  40810. }
  40811. }
  40812. }
  40813. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40814. // Bump texture cannot be not blocking.
  40815. if (!this._bumpTexture.isReady()) {
  40816. return false;
  40817. }
  40818. }
  40819. var refractionTexture = this._getRefractionTexture();
  40820. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40821. if (!refractionTexture.isReadyOrNotBlocking()) {
  40822. return false;
  40823. }
  40824. }
  40825. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40826. // This is blocking.
  40827. if (!this._environmentBRDFTexture.isReady()) {
  40828. return false;
  40829. }
  40830. }
  40831. }
  40832. }
  40833. if (defines._areImageProcessingDirty) {
  40834. if (!this._imageProcessingConfiguration.isReady()) {
  40835. return false;
  40836. }
  40837. }
  40838. if (!engine.getCaps().standardDerivatives) {
  40839. var bufferMesh = null;
  40840. if (mesh.getClassName() === "InstancedMesh") {
  40841. bufferMesh = mesh.sourceMesh;
  40842. }
  40843. else if (mesh.getClassName() === "Mesh") {
  40844. bufferMesh = mesh;
  40845. }
  40846. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40847. bufferMesh.createNormals(true);
  40848. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40849. }
  40850. }
  40851. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40852. if (effect) {
  40853. scene.resetCachedMaterial();
  40854. subMesh.setEffect(effect, defines);
  40855. this.buildUniformLayout();
  40856. }
  40857. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40858. return false;
  40859. }
  40860. defines._renderId = scene.getRenderId();
  40861. this._wasPreviouslyReady = true;
  40862. return true;
  40863. };
  40864. /**
  40865. * Specifies if the material uses metallic roughness workflow.
  40866. * @returns boolean specifiying if the material uses metallic roughness workflow.
  40867. */
  40868. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  40869. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  40870. return true;
  40871. }
  40872. return false;
  40873. };
  40874. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40875. if (onCompiled === void 0) { onCompiled = null; }
  40876. if (onError === void 0) { onError = null; }
  40877. if (useInstances === void 0) { useInstances = null; }
  40878. if (useClipPlane === void 0) { useClipPlane = null; }
  40879. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40880. if (!defines.isDirty) {
  40881. return null;
  40882. }
  40883. defines.markAsProcessed();
  40884. var scene = this.getScene();
  40885. var engine = scene.getEngine();
  40886. // Fallbacks
  40887. var fallbacks = new BABYLON.EffectFallbacks();
  40888. var fallbackRank = 0;
  40889. if (defines.USESPHERICALINVERTEX) {
  40890. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40891. }
  40892. if (defines.FOG) {
  40893. fallbacks.addFallback(fallbackRank, "FOG");
  40894. }
  40895. if (defines.POINTSIZE) {
  40896. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40897. }
  40898. if (defines.LOGARITHMICDEPTH) {
  40899. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40900. }
  40901. if (defines.PARALLAX) {
  40902. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40903. }
  40904. if (defines.PARALLAXOCCLUSION) {
  40905. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40906. }
  40907. if (defines.ENVIRONMENTBRDF) {
  40908. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40909. }
  40910. if (defines.TANGENT) {
  40911. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40912. }
  40913. if (defines.BUMP) {
  40914. fallbacks.addFallback(fallbackRank++, "BUMP");
  40915. }
  40916. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40917. if (defines.SPECULARTERM) {
  40918. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40919. }
  40920. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40921. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40922. }
  40923. if (defines.LIGHTMAP) {
  40924. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40925. }
  40926. if (defines.NORMAL) {
  40927. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40928. }
  40929. if (defines.AMBIENT) {
  40930. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40931. }
  40932. if (defines.EMISSIVE) {
  40933. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40934. }
  40935. if (defines.VERTEXCOLOR) {
  40936. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40937. }
  40938. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40939. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40940. }
  40941. if (defines.MORPHTARGETS) {
  40942. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40943. }
  40944. //Attributes
  40945. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40946. if (defines.NORMAL) {
  40947. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40948. }
  40949. if (defines.TANGENT) {
  40950. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40951. }
  40952. if (defines.UV1) {
  40953. attribs.push(BABYLON.VertexBuffer.UVKind);
  40954. }
  40955. if (defines.UV2) {
  40956. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40957. }
  40958. if (defines.VERTEXCOLOR) {
  40959. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40960. }
  40961. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40962. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40963. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40964. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40965. "vFogInfos", "vFogColor", "pointSize",
  40966. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40967. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40968. "mBones",
  40969. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40970. "vLightingIntensity",
  40971. "logarithmicDepthConstant",
  40972. "vSphericalX", "vSphericalY", "vSphericalZ",
  40973. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40974. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40975. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40976. "vTangentSpaceParams"
  40977. ];
  40978. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40979. "bumpSampler", "lightmapSampler", "opacitySampler",
  40980. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40981. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40982. "microSurfaceSampler", "environmentBrdfSampler"];
  40983. var uniformBuffers = ["Material", "Scene"];
  40984. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40985. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40986. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40987. uniformsNames: uniforms,
  40988. uniformBuffersNames: uniformBuffers,
  40989. samplers: samplers,
  40990. defines: defines,
  40991. maxSimultaneousLights: this._maxSimultaneousLights
  40992. });
  40993. var join = defines.toString();
  40994. return engine.createEffect("pbr", {
  40995. attributes: attribs,
  40996. uniformsNames: uniforms,
  40997. uniformBuffersNames: uniformBuffers,
  40998. samplers: samplers,
  40999. defines: join,
  41000. fallbacks: fallbacks,
  41001. onCompiled: onCompiled,
  41002. onError: onError,
  41003. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41004. }, engine);
  41005. };
  41006. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41007. if (useInstances === void 0) { useInstances = null; }
  41008. if (useClipPlane === void 0) { useClipPlane = null; }
  41009. var scene = this.getScene();
  41010. var engine = scene.getEngine();
  41011. // Lights
  41012. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41013. defines._needNormals = true;
  41014. // Textures
  41015. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41016. if (defines._areTexturesDirty) {
  41017. defines._needUVs = false;
  41018. if (scene.texturesEnabled) {
  41019. if (scene.getEngine().getCaps().textureLOD) {
  41020. defines.LODBASEDMICROSFURACE = true;
  41021. }
  41022. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41023. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41024. }
  41025. else {
  41026. defines.ALBEDO = false;
  41027. }
  41028. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41029. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41030. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41031. }
  41032. else {
  41033. defines.AMBIENT = false;
  41034. }
  41035. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41036. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41037. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41038. }
  41039. else {
  41040. defines.OPACITY = false;
  41041. }
  41042. var reflectionTexture = this._getReflectionTexture();
  41043. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41044. defines.REFLECTION = true;
  41045. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41046. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41047. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41048. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41049. defines.INVERTCUBICMAP = true;
  41050. }
  41051. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41052. switch (reflectionTexture.coordinatesMode) {
  41053. case BABYLON.Texture.CUBIC_MODE:
  41054. case BABYLON.Texture.INVCUBIC_MODE:
  41055. defines.REFLECTIONMAP_CUBIC = true;
  41056. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41057. break;
  41058. case BABYLON.Texture.EXPLICIT_MODE:
  41059. defines.REFLECTIONMAP_EXPLICIT = true;
  41060. break;
  41061. case BABYLON.Texture.PLANAR_MODE:
  41062. defines.REFLECTIONMAP_PLANAR = true;
  41063. break;
  41064. case BABYLON.Texture.PROJECTION_MODE:
  41065. defines.REFLECTIONMAP_PROJECTION = true;
  41066. break;
  41067. case BABYLON.Texture.SKYBOX_MODE:
  41068. defines.REFLECTIONMAP_SKYBOX = true;
  41069. break;
  41070. case BABYLON.Texture.SPHERICAL_MODE:
  41071. defines.REFLECTIONMAP_SPHERICAL = true;
  41072. break;
  41073. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41074. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41075. break;
  41076. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41077. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41078. break;
  41079. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41080. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41081. break;
  41082. }
  41083. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41084. if (reflectionTexture.sphericalPolynomial) {
  41085. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41086. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41087. defines.USESPHERICALINVERTEX = false;
  41088. }
  41089. else {
  41090. defines.USESPHERICALINVERTEX = true;
  41091. }
  41092. }
  41093. }
  41094. }
  41095. else {
  41096. defines.REFLECTION = false;
  41097. defines.REFLECTIONMAP_3D = false;
  41098. defines.REFLECTIONMAP_SPHERICAL = false;
  41099. defines.REFLECTIONMAP_PLANAR = false;
  41100. defines.REFLECTIONMAP_CUBIC = false;
  41101. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41102. defines.REFLECTIONMAP_PROJECTION = false;
  41103. defines.REFLECTIONMAP_SKYBOX = false;
  41104. defines.REFLECTIONMAP_EXPLICIT = false;
  41105. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41106. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41107. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41108. defines.INVERTCUBICMAP = false;
  41109. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41110. defines.USESPHERICALINVERTEX = false;
  41111. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41112. defines.LODINREFLECTIONALPHA = false;
  41113. defines.GAMMAREFLECTION = false;
  41114. }
  41115. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41116. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41117. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41118. }
  41119. else {
  41120. defines.LIGHTMAP = false;
  41121. }
  41122. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41124. }
  41125. else {
  41126. defines.EMISSIVE = false;
  41127. }
  41128. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41129. if (this._metallicTexture) {
  41130. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41131. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41132. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41133. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41134. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41135. }
  41136. else if (this._reflectivityTexture) {
  41137. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41138. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41139. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41140. }
  41141. else {
  41142. defines.REFLECTIVITY = false;
  41143. }
  41144. if (this._microSurfaceTexture) {
  41145. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41146. }
  41147. else {
  41148. defines.MICROSURFACEMAP = false;
  41149. }
  41150. }
  41151. else {
  41152. defines.REFLECTIVITY = false;
  41153. defines.MICROSURFACEMAP = false;
  41154. }
  41155. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41156. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41157. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41158. defines.PARALLAX = true;
  41159. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41160. }
  41161. else {
  41162. defines.PARALLAX = false;
  41163. }
  41164. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41165. }
  41166. else {
  41167. defines.BUMP = false;
  41168. }
  41169. var refractionTexture = this._getRefractionTexture();
  41170. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41171. defines.REFRACTION = true;
  41172. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41173. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41174. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41175. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41176. if (this._linkRefractionWithTransparency) {
  41177. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41178. }
  41179. }
  41180. else {
  41181. defines.REFRACTION = false;
  41182. }
  41183. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41184. defines.ENVIRONMENTBRDF = true;
  41185. }
  41186. else {
  41187. defines.ENVIRONMENTBRDF = false;
  41188. }
  41189. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41190. defines.ALPHAFROMALBEDO = true;
  41191. }
  41192. else {
  41193. defines.ALPHAFROMALBEDO = false;
  41194. }
  41195. }
  41196. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41197. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41198. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41199. if (!this.backFaceCulling && this._twoSidedLighting) {
  41200. defines.TWOSIDEDLIGHTING = true;
  41201. }
  41202. else {
  41203. defines.TWOSIDEDLIGHTING = false;
  41204. }
  41205. defines.ALPHATESTVALUE = this._alphaCutOff;
  41206. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41207. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41208. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41209. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41210. }
  41211. if (defines._areImageProcessingDirty) {
  41212. this._imageProcessingConfiguration.prepareDefines(defines);
  41213. }
  41214. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41215. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41216. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41217. // Misc.
  41218. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41219. // Values that need to be evaluated on every frame
  41220. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41221. // Attribs
  41222. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41223. };
  41224. /**
  41225. * Force shader compilation
  41226. */
  41227. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41228. var _this = this;
  41229. var localOptions = __assign({ clipPlane: false }, options);
  41230. var defines = new PBRMaterialDefines();
  41231. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41232. if (effect.isReady()) {
  41233. if (onCompiled) {
  41234. onCompiled(this);
  41235. }
  41236. }
  41237. else {
  41238. effect.onCompileObservable.add(function () {
  41239. if (onCompiled) {
  41240. onCompiled(_this);
  41241. }
  41242. });
  41243. }
  41244. };
  41245. /**
  41246. * Initializes the uniform buffer layout for the shader.
  41247. */
  41248. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41249. // Order is important !
  41250. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41251. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41252. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41253. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41254. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41255. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41256. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41257. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41258. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41259. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41260. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41261. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41262. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41263. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41264. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41265. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41266. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41267. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41268. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41269. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41270. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41271. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41272. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41273. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41274. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41275. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41276. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41277. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41278. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41279. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41280. this._uniformBuffer.addUniform("pointSize", 1);
  41281. this._uniformBuffer.create();
  41282. };
  41283. /**
  41284. * Unbinds the textures.
  41285. */
  41286. PBRBaseMaterial.prototype.unbind = function () {
  41287. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41288. this._uniformBuffer.setTexture("reflectionSampler", null);
  41289. }
  41290. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41291. this._uniformBuffer.setTexture("refractionSampler", null);
  41292. }
  41293. _super.prototype.unbind.call(this);
  41294. };
  41295. /**
  41296. * Binds the submesh data.
  41297. * @param world - The world matrix.
  41298. * @param mesh - The BJS mesh.
  41299. * @param subMesh - A submesh of the BJS mesh.
  41300. */
  41301. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41302. var scene = this.getScene();
  41303. var defines = subMesh._materialDefines;
  41304. if (!defines) {
  41305. return;
  41306. }
  41307. var effect = subMesh.effect;
  41308. if (!effect) {
  41309. return;
  41310. }
  41311. this._activeEffect = effect;
  41312. // Matrices
  41313. this.bindOnlyWorldMatrix(world);
  41314. // Normal Matrix
  41315. if (defines.OBJECTSPACE_NORMALMAP) {
  41316. world.toNormalMatrix(this._normalMatrix);
  41317. this.bindOnlyNormalMatrix(this._normalMatrix);
  41318. }
  41319. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41320. // Bones
  41321. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41322. var reflectionTexture = null;
  41323. if (mustRebind) {
  41324. this._uniformBuffer.bindToEffect(effect, "Material");
  41325. this.bindViewProjection(effect);
  41326. reflectionTexture = this._getReflectionTexture();
  41327. var refractionTexture = this._getRefractionTexture();
  41328. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41329. // Texture uniforms
  41330. if (scene.texturesEnabled) {
  41331. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41332. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41333. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41334. }
  41335. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41336. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41337. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41338. }
  41339. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41340. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41341. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41342. }
  41343. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41344. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41345. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41346. if (reflectionTexture.boundingBoxSize) {
  41347. var cubeTexture = reflectionTexture;
  41348. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41349. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41350. }
  41351. var polynomials = reflectionTexture.sphericalPolynomial;
  41352. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41353. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41354. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41355. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41356. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41357. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41358. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41359. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41360. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41361. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41362. }
  41363. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41364. }
  41365. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41366. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41367. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41368. }
  41369. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41370. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41371. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41372. }
  41373. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41374. if (this._metallicTexture) {
  41375. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41376. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41377. }
  41378. else if (this._reflectivityTexture) {
  41379. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41380. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41381. }
  41382. if (this._microSurfaceTexture) {
  41383. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41384. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41385. }
  41386. }
  41387. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41388. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41389. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41390. if (scene._mirroredCameraPosition) {
  41391. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41392. }
  41393. else {
  41394. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41395. }
  41396. }
  41397. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41398. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41399. var depth = 1.0;
  41400. if (!refractionTexture.isCube) {
  41401. if (refractionTexture.depth) {
  41402. depth = refractionTexture.depth;
  41403. }
  41404. }
  41405. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41406. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41407. }
  41408. }
  41409. // Point size
  41410. if (this.pointsCloud) {
  41411. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41412. }
  41413. // Colors
  41414. if (defines.METALLICWORKFLOW) {
  41415. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41416. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41417. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41418. }
  41419. else {
  41420. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41421. }
  41422. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41423. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41424. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41425. // Misc
  41426. this._lightingInfos.x = this._directIntensity;
  41427. this._lightingInfos.y = this._emissiveIntensity;
  41428. this._lightingInfos.z = this._environmentIntensity;
  41429. this._lightingInfos.w = this._specularIntensity;
  41430. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41431. }
  41432. // Textures
  41433. if (scene.texturesEnabled) {
  41434. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41435. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41436. }
  41437. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41438. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41439. }
  41440. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41441. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41442. }
  41443. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41444. if (defines.LODBASEDMICROSFURACE) {
  41445. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41446. }
  41447. else {
  41448. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41449. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41450. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41451. }
  41452. }
  41453. if (defines.ENVIRONMENTBRDF) {
  41454. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41455. }
  41456. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41457. if (defines.LODBASEDMICROSFURACE) {
  41458. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41459. }
  41460. else {
  41461. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41462. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41463. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41464. }
  41465. }
  41466. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41467. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41468. }
  41469. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41470. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41471. }
  41472. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41473. if (this._metallicTexture) {
  41474. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41475. }
  41476. else if (this._reflectivityTexture) {
  41477. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41478. }
  41479. if (this._microSurfaceTexture) {
  41480. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41481. }
  41482. }
  41483. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41484. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41485. }
  41486. }
  41487. // Clip plane
  41488. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41489. // Colors
  41490. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41491. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41492. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41493. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41494. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41495. }
  41496. if (mustRebind || !this.isFrozen) {
  41497. // Lights
  41498. if (scene.lightsEnabled && !this._disableLighting) {
  41499. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41500. }
  41501. // View
  41502. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41503. this.bindView(effect);
  41504. }
  41505. // Fog
  41506. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41507. // Morph targets
  41508. if (defines.NUM_MORPH_INFLUENCERS) {
  41509. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41510. }
  41511. // image processing
  41512. this._imageProcessingConfiguration.bind(this._activeEffect);
  41513. // Log. depth
  41514. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41515. }
  41516. this._uniformBuffer.update();
  41517. this._afterBind(mesh);
  41518. };
  41519. /**
  41520. * Returns the animatable textures.
  41521. * @returns - Array of animatable textures.
  41522. */
  41523. PBRBaseMaterial.prototype.getAnimatables = function () {
  41524. var results = [];
  41525. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41526. results.push(this._albedoTexture);
  41527. }
  41528. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41529. results.push(this._ambientTexture);
  41530. }
  41531. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41532. results.push(this._opacityTexture);
  41533. }
  41534. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41535. results.push(this._reflectionTexture);
  41536. }
  41537. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41538. results.push(this._emissiveTexture);
  41539. }
  41540. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41541. results.push(this._metallicTexture);
  41542. }
  41543. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41544. results.push(this._reflectivityTexture);
  41545. }
  41546. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41547. results.push(this._bumpTexture);
  41548. }
  41549. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41550. results.push(this._lightmapTexture);
  41551. }
  41552. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41553. results.push(this._refractionTexture);
  41554. }
  41555. return results;
  41556. };
  41557. /**
  41558. * Returns the texture used for reflections.
  41559. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41560. */
  41561. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41562. if (this._reflectionTexture) {
  41563. return this._reflectionTexture;
  41564. }
  41565. return this.getScene().environmentTexture;
  41566. };
  41567. /**
  41568. * Returns the texture used for refraction or null if none is used.
  41569. * @returns - Refection texture if present. If no refraction texture and refraction
  41570. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41571. */
  41572. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41573. if (this._refractionTexture) {
  41574. return this._refractionTexture;
  41575. }
  41576. if (this._linkRefractionWithTransparency) {
  41577. return this.getScene().environmentTexture;
  41578. }
  41579. return null;
  41580. };
  41581. /**
  41582. * Disposes the resources of the material.
  41583. * @param forceDisposeEffect - Forces the disposal of effects.
  41584. * @param forceDisposeTextures - Forces the disposal of all textures.
  41585. */
  41586. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41587. if (forceDisposeTextures) {
  41588. if (this._albedoTexture) {
  41589. this._albedoTexture.dispose();
  41590. }
  41591. if (this._ambientTexture) {
  41592. this._ambientTexture.dispose();
  41593. }
  41594. if (this._opacityTexture) {
  41595. this._opacityTexture.dispose();
  41596. }
  41597. if (this._reflectionTexture) {
  41598. this._reflectionTexture.dispose();
  41599. }
  41600. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41601. this._environmentBRDFTexture.dispose();
  41602. }
  41603. if (this._emissiveTexture) {
  41604. this._emissiveTexture.dispose();
  41605. }
  41606. if (this._metallicTexture) {
  41607. this._metallicTexture.dispose();
  41608. }
  41609. if (this._reflectivityTexture) {
  41610. this._reflectivityTexture.dispose();
  41611. }
  41612. if (this._bumpTexture) {
  41613. this._bumpTexture.dispose();
  41614. }
  41615. if (this._lightmapTexture) {
  41616. this._lightmapTexture.dispose();
  41617. }
  41618. if (this._refractionTexture) {
  41619. this._refractionTexture.dispose();
  41620. }
  41621. }
  41622. this._renderTargets.dispose();
  41623. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41624. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41625. }
  41626. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41627. };
  41628. /**
  41629. * Stores the reflectivity values based on metallic roughness workflow.
  41630. */
  41631. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41632. __decorate([
  41633. BABYLON.serializeAsImageProcessingConfiguration()
  41634. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41635. __decorate([
  41636. BABYLON.serialize()
  41637. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41638. __decorate([
  41639. BABYLON.serialize()
  41640. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41641. return PBRBaseMaterial;
  41642. }(BABYLON.PushMaterial));
  41643. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41644. })(BABYLON || (BABYLON = {}));
  41645. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41646. var BABYLON;
  41647. (function (BABYLON) {
  41648. /**
  41649. * The Physically based simple base material of BJS.
  41650. *
  41651. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41652. * It is used as the base class for both the specGloss and metalRough conventions.
  41653. */
  41654. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41655. __extends(PBRBaseSimpleMaterial, _super);
  41656. /**
  41657. * Instantiates a new PBRMaterial instance.
  41658. *
  41659. * @param name The material name
  41660. * @param scene The scene the material will be use in.
  41661. */
  41662. function PBRBaseSimpleMaterial(name, scene) {
  41663. var _this = _super.call(this, name, scene) || this;
  41664. /**
  41665. * Number of Simultaneous lights allowed on the material.
  41666. */
  41667. _this.maxSimultaneousLights = 4;
  41668. /**
  41669. * If sets to true, disables all the lights affecting the material.
  41670. */
  41671. _this.disableLighting = false;
  41672. /**
  41673. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41674. */
  41675. _this.invertNormalMapX = false;
  41676. /**
  41677. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41678. */
  41679. _this.invertNormalMapY = false;
  41680. /**
  41681. * Emissivie color used to self-illuminate the model.
  41682. */
  41683. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41684. /**
  41685. * Occlusion Channel Strenght.
  41686. */
  41687. _this.occlusionStrength = 1.0;
  41688. _this.useLightmapAsShadowmap = false;
  41689. _this._useAlphaFromAlbedoTexture = true;
  41690. _this._useAmbientInGrayScale = true;
  41691. return _this;
  41692. }
  41693. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41694. /**
  41695. * Gets the current double sided mode.
  41696. */
  41697. get: function () {
  41698. return this._twoSidedLighting;
  41699. },
  41700. /**
  41701. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41702. */
  41703. set: function (value) {
  41704. if (this._twoSidedLighting === value) {
  41705. return;
  41706. }
  41707. this._twoSidedLighting = value;
  41708. this.backFaceCulling = !value;
  41709. this._markAllSubMeshesAsTexturesDirty();
  41710. },
  41711. enumerable: true,
  41712. configurable: true
  41713. });
  41714. /**
  41715. * Return the active textures of the material.
  41716. */
  41717. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41718. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41719. if (this.environmentTexture) {
  41720. activeTextures.push(this.environmentTexture);
  41721. }
  41722. if (this.normalTexture) {
  41723. activeTextures.push(this.normalTexture);
  41724. }
  41725. if (this.emissiveTexture) {
  41726. activeTextures.push(this.emissiveTexture);
  41727. }
  41728. if (this.occlusionTexture) {
  41729. activeTextures.push(this.occlusionTexture);
  41730. }
  41731. if (this.lightmapTexture) {
  41732. activeTextures.push(this.lightmapTexture);
  41733. }
  41734. return activeTextures;
  41735. };
  41736. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41737. if (_super.prototype.hasTexture.call(this, texture)) {
  41738. return true;
  41739. }
  41740. if (this.lightmapTexture === texture) {
  41741. return true;
  41742. }
  41743. return false;
  41744. };
  41745. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41746. return "PBRBaseSimpleMaterial";
  41747. };
  41748. __decorate([
  41749. BABYLON.serialize(),
  41750. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41751. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41752. __decorate([
  41753. BABYLON.serialize(),
  41754. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41755. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41756. __decorate([
  41757. BABYLON.serializeAsTexture(),
  41758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41759. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41760. __decorate([
  41761. BABYLON.serialize(),
  41762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41763. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41764. __decorate([
  41765. BABYLON.serialize(),
  41766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41767. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41768. __decorate([
  41769. BABYLON.serializeAsTexture(),
  41770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41771. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41772. __decorate([
  41773. BABYLON.serializeAsColor3("emissive"),
  41774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41775. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41776. __decorate([
  41777. BABYLON.serializeAsTexture(),
  41778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41779. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41780. __decorate([
  41781. BABYLON.serialize(),
  41782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41783. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41784. __decorate([
  41785. BABYLON.serializeAsTexture(),
  41786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41787. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41788. __decorate([
  41789. BABYLON.serialize(),
  41790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41791. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41792. __decorate([
  41793. BABYLON.serialize()
  41794. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41795. __decorate([
  41796. BABYLON.serializeAsTexture(),
  41797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41798. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41799. __decorate([
  41800. BABYLON.serialize(),
  41801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41802. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41803. return PBRBaseSimpleMaterial;
  41804. }(BABYLON.PBRBaseMaterial));
  41805. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41806. })(BABYLON || (BABYLON = {}));
  41807. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41808. var BABYLON;
  41809. (function (BABYLON) {
  41810. /**
  41811. * The Physically based material of BJS.
  41812. *
  41813. * This offers the main features of a standard PBR material.
  41814. * For more information, please refer to the documentation :
  41815. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41816. */
  41817. var PBRMaterial = /** @class */ (function (_super) {
  41818. __extends(PBRMaterial, _super);
  41819. /**
  41820. * Instantiates a new PBRMaterial instance.
  41821. *
  41822. * @param name The material name
  41823. * @param scene The scene the material will be use in.
  41824. */
  41825. function PBRMaterial(name, scene) {
  41826. var _this = _super.call(this, name, scene) || this;
  41827. /**
  41828. * Intensity of the direct lights e.g. the four lights available in your scene.
  41829. * This impacts both the direct diffuse and specular highlights.
  41830. */
  41831. _this.directIntensity = 1.0;
  41832. /**
  41833. * Intensity of the emissive part of the material.
  41834. * This helps controlling the emissive effect without modifying the emissive color.
  41835. */
  41836. _this.emissiveIntensity = 1.0;
  41837. /**
  41838. * Intensity of the environment e.g. how much the environment will light the object
  41839. * either through harmonics for rough material or through the refelction for shiny ones.
  41840. */
  41841. _this.environmentIntensity = 1.0;
  41842. /**
  41843. * This is a special control allowing the reduction of the specular highlights coming from the
  41844. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41845. */
  41846. _this.specularIntensity = 1.0;
  41847. /**
  41848. * Debug Control allowing disabling the bump map on this material.
  41849. */
  41850. _this.disableBumpMap = false;
  41851. /**
  41852. * AKA Occlusion Texture Intensity in other nomenclature.
  41853. */
  41854. _this.ambientTextureStrength = 1.0;
  41855. /**
  41856. * The color of a material in ambient lighting.
  41857. */
  41858. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41859. /**
  41860. * AKA Diffuse Color in other nomenclature.
  41861. */
  41862. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41863. /**
  41864. * AKA Specular Color in other nomenclature.
  41865. */
  41866. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41867. /**
  41868. * The color reflected from the material.
  41869. */
  41870. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41871. /**
  41872. * The color emitted from the material.
  41873. */
  41874. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41875. /**
  41876. * AKA Glossiness in other nomenclature.
  41877. */
  41878. _this.microSurface = 1.0;
  41879. /**
  41880. * source material index of refraction (IOR)' / 'destination material IOR.
  41881. */
  41882. _this.indexOfRefraction = 0.66;
  41883. /**
  41884. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41885. */
  41886. _this.invertRefractionY = false;
  41887. /**
  41888. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41889. * Materials half opaque for instance using refraction could benefit from this control.
  41890. */
  41891. _this.linkRefractionWithTransparency = false;
  41892. _this.useLightmapAsShadowmap = false;
  41893. /**
  41894. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41895. */
  41896. _this.useAlphaFromAlbedoTexture = false;
  41897. /**
  41898. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41899. */
  41900. _this.forceAlphaTest = false;
  41901. /**
  41902. * Defines the alpha limits in alpha test mode.
  41903. */
  41904. _this.alphaCutOff = 0.4;
  41905. /**
  41906. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41907. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41908. */
  41909. _this.useSpecularOverAlpha = true;
  41910. /**
  41911. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41912. */
  41913. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41914. /**
  41915. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41916. */
  41917. _this.useRoughnessFromMetallicTextureAlpha = true;
  41918. /**
  41919. * Specifies if the metallic texture contains the roughness information in its green channel.
  41920. */
  41921. _this.useRoughnessFromMetallicTextureGreen = false;
  41922. /**
  41923. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41924. */
  41925. _this.useMetallnessFromMetallicTextureBlue = false;
  41926. /**
  41927. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41928. */
  41929. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41930. /**
  41931. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41932. */
  41933. _this.useAmbientInGrayScale = false;
  41934. /**
  41935. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41936. * The material will try to infer what glossiness each pixel should be.
  41937. */
  41938. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41939. /**
  41940. * BJS is using an harcoded light falloff based on a manually sets up range.
  41941. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41942. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41943. */
  41944. _this.usePhysicalLightFalloff = true;
  41945. /**
  41946. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41947. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41948. */
  41949. _this.useRadianceOverAlpha = true;
  41950. /**
  41951. * Allows using an object space normal map (instead of tangent space).
  41952. */
  41953. _this.useObjectSpaceNormalMap = false;
  41954. /**
  41955. * Allows using the bump map in parallax mode.
  41956. */
  41957. _this.useParallax = false;
  41958. /**
  41959. * Allows using the bump map in parallax occlusion mode.
  41960. */
  41961. _this.useParallaxOcclusion = false;
  41962. /**
  41963. * Controls the scale bias of the parallax mode.
  41964. */
  41965. _this.parallaxScaleBias = 0.05;
  41966. /**
  41967. * If sets to true, disables all the lights affecting the material.
  41968. */
  41969. _this.disableLighting = false;
  41970. /**
  41971. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41972. */
  41973. _this.forceIrradianceInFragment = false;
  41974. /**
  41975. * Number of Simultaneous lights allowed on the material.
  41976. */
  41977. _this.maxSimultaneousLights = 4;
  41978. /**
  41979. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41980. */
  41981. _this.invertNormalMapX = false;
  41982. /**
  41983. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41984. */
  41985. _this.invertNormalMapY = false;
  41986. /**
  41987. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41988. */
  41989. _this.twoSidedLighting = false;
  41990. /**
  41991. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41992. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41993. */
  41994. _this.useAlphaFresnel = false;
  41995. /**
  41996. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41997. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41998. */
  41999. _this.useLinearAlphaFresnel = false;
  42000. /**
  42001. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42002. * And/Or occlude the blended part.
  42003. */
  42004. _this.environmentBRDFTexture = null;
  42005. /**
  42006. * Force normal to face away from face.
  42007. */
  42008. _this.forceNormalForward = false;
  42009. /**
  42010. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42011. * makes the reflect vector face the model (under horizon).
  42012. */
  42013. _this.useHorizonOcclusion = true;
  42014. /**
  42015. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42016. * too much the area relying on ambient texture to define their ambient occlusion.
  42017. */
  42018. _this.useRadianceOcclusion = true;
  42019. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42020. return _this;
  42021. }
  42022. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42023. /**
  42024. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42025. */
  42026. get: function () {
  42027. return this._PBRMATERIAL_OPAQUE;
  42028. },
  42029. enumerable: true,
  42030. configurable: true
  42031. });
  42032. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42033. /**
  42034. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42035. */
  42036. get: function () {
  42037. return this._PBRMATERIAL_ALPHATEST;
  42038. },
  42039. enumerable: true,
  42040. configurable: true
  42041. });
  42042. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42043. /**
  42044. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42045. */
  42046. get: function () {
  42047. return this._PBRMATERIAL_ALPHABLEND;
  42048. },
  42049. enumerable: true,
  42050. configurable: true
  42051. });
  42052. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42053. /**
  42054. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42055. * They are also discarded below the alpha cutoff threshold to improve performances.
  42056. */
  42057. get: function () {
  42058. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42059. },
  42060. enumerable: true,
  42061. configurable: true
  42062. });
  42063. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42064. /**
  42065. * Gets the image processing configuration used either in this material.
  42066. */
  42067. get: function () {
  42068. return this._imageProcessingConfiguration;
  42069. },
  42070. /**
  42071. * Sets the Default image processing configuration used either in the this material.
  42072. *
  42073. * If sets to null, the scene one is in use.
  42074. */
  42075. set: function (value) {
  42076. this._attachImageProcessingConfiguration(value);
  42077. // Ensure the effect will be rebuilt.
  42078. this._markAllSubMeshesAsTexturesDirty();
  42079. },
  42080. enumerable: true,
  42081. configurable: true
  42082. });
  42083. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42084. /**
  42085. * Gets wether the color curves effect is enabled.
  42086. */
  42087. get: function () {
  42088. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42089. },
  42090. /**
  42091. * Sets wether the color curves effect is enabled.
  42092. */
  42093. set: function (value) {
  42094. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42095. },
  42096. enumerable: true,
  42097. configurable: true
  42098. });
  42099. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42100. /**
  42101. * Gets wether the color grading effect is enabled.
  42102. */
  42103. get: function () {
  42104. return this.imageProcessingConfiguration.colorGradingEnabled;
  42105. },
  42106. /**
  42107. * Gets wether the color grading effect is enabled.
  42108. */
  42109. set: function (value) {
  42110. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42111. },
  42112. enumerable: true,
  42113. configurable: true
  42114. });
  42115. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42116. /**
  42117. * Gets wether tonemapping is enabled or not.
  42118. */
  42119. get: function () {
  42120. return this._imageProcessingConfiguration.toneMappingEnabled;
  42121. },
  42122. /**
  42123. * Sets wether tonemapping is enabled or not
  42124. */
  42125. set: function (value) {
  42126. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42127. },
  42128. enumerable: true,
  42129. configurable: true
  42130. });
  42131. ;
  42132. ;
  42133. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42134. /**
  42135. * The camera exposure used on this material.
  42136. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42137. * This corresponds to a photographic exposure.
  42138. */
  42139. get: function () {
  42140. return this._imageProcessingConfiguration.exposure;
  42141. },
  42142. /**
  42143. * The camera exposure used on this material.
  42144. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42145. * This corresponds to a photographic exposure.
  42146. */
  42147. set: function (value) {
  42148. this._imageProcessingConfiguration.exposure = value;
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. ;
  42154. ;
  42155. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42156. /**
  42157. * Gets The camera contrast used on this material.
  42158. */
  42159. get: function () {
  42160. return this._imageProcessingConfiguration.contrast;
  42161. },
  42162. /**
  42163. * Sets The camera contrast used on this material.
  42164. */
  42165. set: function (value) {
  42166. this._imageProcessingConfiguration.contrast = value;
  42167. },
  42168. enumerable: true,
  42169. configurable: true
  42170. });
  42171. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42172. /**
  42173. * Gets the Color Grading 2D Lookup Texture.
  42174. */
  42175. get: function () {
  42176. return this._imageProcessingConfiguration.colorGradingTexture;
  42177. },
  42178. /**
  42179. * Sets the Color Grading 2D Lookup Texture.
  42180. */
  42181. set: function (value) {
  42182. this._imageProcessingConfiguration.colorGradingTexture = value;
  42183. },
  42184. enumerable: true,
  42185. configurable: true
  42186. });
  42187. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42188. /**
  42189. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42190. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42191. * 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;
  42192. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42193. */
  42194. get: function () {
  42195. return this._imageProcessingConfiguration.colorCurves;
  42196. },
  42197. /**
  42198. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42199. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42200. * 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;
  42201. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42202. */
  42203. set: function (value) {
  42204. this._imageProcessingConfiguration.colorCurves = value;
  42205. },
  42206. enumerable: true,
  42207. configurable: true
  42208. });
  42209. /**
  42210. * Returns the name of this material class.
  42211. */
  42212. PBRMaterial.prototype.getClassName = function () {
  42213. return "PBRMaterial";
  42214. };
  42215. /**
  42216. * Returns an array of the actively used textures.
  42217. * @returns - Array of BaseTextures
  42218. */
  42219. PBRMaterial.prototype.getActiveTextures = function () {
  42220. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42221. if (this._albedoTexture) {
  42222. activeTextures.push(this._albedoTexture);
  42223. }
  42224. if (this._ambientTexture) {
  42225. activeTextures.push(this._ambientTexture);
  42226. }
  42227. if (this._opacityTexture) {
  42228. activeTextures.push(this._opacityTexture);
  42229. }
  42230. if (this._reflectionTexture) {
  42231. activeTextures.push(this._reflectionTexture);
  42232. }
  42233. if (this._emissiveTexture) {
  42234. activeTextures.push(this._emissiveTexture);
  42235. }
  42236. if (this._reflectivityTexture) {
  42237. activeTextures.push(this._reflectivityTexture);
  42238. }
  42239. if (this._metallicTexture) {
  42240. activeTextures.push(this._metallicTexture);
  42241. }
  42242. if (this._microSurfaceTexture) {
  42243. activeTextures.push(this._microSurfaceTexture);
  42244. }
  42245. if (this._bumpTexture) {
  42246. activeTextures.push(this._bumpTexture);
  42247. }
  42248. if (this._lightmapTexture) {
  42249. activeTextures.push(this._lightmapTexture);
  42250. }
  42251. if (this._refractionTexture) {
  42252. activeTextures.push(this._refractionTexture);
  42253. }
  42254. return activeTextures;
  42255. };
  42256. /**
  42257. * Checks to see if a texture is used in the material.
  42258. * @param texture - Base texture to use.
  42259. * @returns - Boolean specifying if a texture is used in the material.
  42260. */
  42261. PBRMaterial.prototype.hasTexture = function (texture) {
  42262. if (_super.prototype.hasTexture.call(this, texture)) {
  42263. return true;
  42264. }
  42265. if (this._albedoTexture === texture) {
  42266. return true;
  42267. }
  42268. if (this._ambientTexture === texture) {
  42269. return true;
  42270. }
  42271. if (this._opacityTexture === texture) {
  42272. return true;
  42273. }
  42274. if (this._reflectionTexture === texture) {
  42275. return true;
  42276. }
  42277. if (this._reflectivityTexture === texture) {
  42278. return true;
  42279. }
  42280. if (this._metallicTexture === texture) {
  42281. return true;
  42282. }
  42283. if (this._microSurfaceTexture === texture) {
  42284. return true;
  42285. }
  42286. if (this._bumpTexture === texture) {
  42287. return true;
  42288. }
  42289. if (this._lightmapTexture === texture) {
  42290. return true;
  42291. }
  42292. if (this._refractionTexture === texture) {
  42293. return true;
  42294. }
  42295. return false;
  42296. };
  42297. /**
  42298. * Makes a duplicate of the current material.
  42299. * @param name - name to use for the new material.
  42300. */
  42301. PBRMaterial.prototype.clone = function (name) {
  42302. var _this = this;
  42303. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42304. clone.id = name;
  42305. clone.name = name;
  42306. return clone;
  42307. };
  42308. /**
  42309. * Serializes this PBR Material.
  42310. * @returns - An object with the serialized material.
  42311. */
  42312. PBRMaterial.prototype.serialize = function () {
  42313. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42314. serializationObject.customType = "BABYLON.PBRMaterial";
  42315. return serializationObject;
  42316. };
  42317. // Statics
  42318. /**
  42319. * Parses a PBR Material from a serialized object.
  42320. * @param source - Serialized object.
  42321. * @param scene - BJS scene instance.
  42322. * @param rootUrl - url for the scene object
  42323. * @returns - PBRMaterial
  42324. */
  42325. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42326. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42327. };
  42328. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42329. /**
  42330. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42331. */
  42332. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42333. /**
  42334. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42335. */
  42336. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42337. /**
  42338. * 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.
  42339. * They are also discarded below the alpha cutoff threshold to improve performances.
  42340. */
  42341. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42342. __decorate([
  42343. BABYLON.serialize(),
  42344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42345. ], PBRMaterial.prototype, "directIntensity", void 0);
  42346. __decorate([
  42347. BABYLON.serialize(),
  42348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42349. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42350. __decorate([
  42351. BABYLON.serialize(),
  42352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42353. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42354. __decorate([
  42355. BABYLON.serialize(),
  42356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42357. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42358. __decorate([
  42359. BABYLON.serialize(),
  42360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42361. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42362. __decorate([
  42363. BABYLON.serializeAsTexture(),
  42364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42365. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42366. __decorate([
  42367. BABYLON.serializeAsTexture(),
  42368. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42369. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42370. __decorate([
  42371. BABYLON.serialize(),
  42372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42373. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42374. __decorate([
  42375. BABYLON.serializeAsTexture(),
  42376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42377. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42378. __decorate([
  42379. BABYLON.serializeAsTexture(),
  42380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42381. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42382. __decorate([
  42383. BABYLON.serializeAsTexture(),
  42384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42385. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42386. __decorate([
  42387. BABYLON.serializeAsTexture(),
  42388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42389. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42390. __decorate([
  42391. BABYLON.serializeAsTexture(),
  42392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42393. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42394. __decorate([
  42395. BABYLON.serialize(),
  42396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42397. ], PBRMaterial.prototype, "metallic", void 0);
  42398. __decorate([
  42399. BABYLON.serialize(),
  42400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42401. ], PBRMaterial.prototype, "roughness", void 0);
  42402. __decorate([
  42403. BABYLON.serializeAsTexture(),
  42404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42405. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42406. __decorate([
  42407. BABYLON.serializeAsTexture(),
  42408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42409. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42410. __decorate([
  42411. BABYLON.serializeAsTexture(),
  42412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42413. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42414. __decorate([
  42415. BABYLON.serializeAsTexture(),
  42416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42417. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42418. __decorate([
  42419. BABYLON.serializeAsColor3("ambient"),
  42420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42421. ], PBRMaterial.prototype, "ambientColor", void 0);
  42422. __decorate([
  42423. BABYLON.serializeAsColor3("albedo"),
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42425. ], PBRMaterial.prototype, "albedoColor", void 0);
  42426. __decorate([
  42427. BABYLON.serializeAsColor3("reflectivity"),
  42428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42429. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42430. __decorate([
  42431. BABYLON.serializeAsColor3("reflection"),
  42432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42433. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42434. __decorate([
  42435. BABYLON.serializeAsColor3("emissive"),
  42436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42437. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42438. __decorate([
  42439. BABYLON.serialize(),
  42440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42441. ], PBRMaterial.prototype, "microSurface", void 0);
  42442. __decorate([
  42443. BABYLON.serialize(),
  42444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42445. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42446. __decorate([
  42447. BABYLON.serialize(),
  42448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42449. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42450. __decorate([
  42451. BABYLON.serialize(),
  42452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42453. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42454. __decorate([
  42455. BABYLON.serialize(),
  42456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42457. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42458. __decorate([
  42459. BABYLON.serialize(),
  42460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42461. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42462. __decorate([
  42463. BABYLON.serialize(),
  42464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42465. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42466. __decorate([
  42467. BABYLON.serialize(),
  42468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42469. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42470. __decorate([
  42471. BABYLON.serialize(),
  42472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42473. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42474. __decorate([
  42475. BABYLON.serialize(),
  42476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42477. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42478. __decorate([
  42479. BABYLON.serialize(),
  42480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42481. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42482. __decorate([
  42483. BABYLON.serialize(),
  42484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42485. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42486. __decorate([
  42487. BABYLON.serialize(),
  42488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42489. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42490. __decorate([
  42491. BABYLON.serialize(),
  42492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42493. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42494. __decorate([
  42495. BABYLON.serialize(),
  42496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42497. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42498. __decorate([
  42499. BABYLON.serialize(),
  42500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42501. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42502. __decorate([
  42503. BABYLON.serialize(),
  42504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42505. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42506. __decorate([
  42507. BABYLON.serialize(),
  42508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42509. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42510. __decorate([
  42511. BABYLON.serialize(),
  42512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42513. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42514. __decorate([
  42515. BABYLON.serialize(),
  42516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42517. ], PBRMaterial.prototype, "useParallax", void 0);
  42518. __decorate([
  42519. BABYLON.serialize(),
  42520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42521. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42522. __decorate([
  42523. BABYLON.serialize(),
  42524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42525. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42526. __decorate([
  42527. BABYLON.serialize(),
  42528. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42529. ], PBRMaterial.prototype, "disableLighting", void 0);
  42530. __decorate([
  42531. BABYLON.serialize(),
  42532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42533. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42534. __decorate([
  42535. BABYLON.serialize(),
  42536. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42537. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42538. __decorate([
  42539. BABYLON.serialize(),
  42540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42541. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42542. __decorate([
  42543. BABYLON.serialize(),
  42544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42545. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42546. __decorate([
  42547. BABYLON.serialize(),
  42548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42549. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42550. __decorate([
  42551. BABYLON.serialize(),
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42554. __decorate([
  42555. BABYLON.serialize(),
  42556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42557. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42558. __decorate([
  42559. BABYLON.serializeAsTexture(),
  42560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42561. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42562. __decorate([
  42563. BABYLON.serialize(),
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42566. __decorate([
  42567. BABYLON.serialize(),
  42568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42569. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42570. __decorate([
  42571. BABYLON.serialize(),
  42572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42573. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42574. return PBRMaterial;
  42575. }(BABYLON.PBRBaseMaterial));
  42576. BABYLON.PBRMaterial = PBRMaterial;
  42577. })(BABYLON || (BABYLON = {}));
  42578. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42579. var BABYLON;
  42580. (function (BABYLON) {
  42581. /**
  42582. * The PBR material of BJS following the metal roughness convention.
  42583. *
  42584. * This fits to the PBR convention in the GLTF definition:
  42585. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42586. */
  42587. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42588. __extends(PBRMetallicRoughnessMaterial, _super);
  42589. /**
  42590. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42591. *
  42592. * @param name The material name
  42593. * @param scene The scene the material will be use in.
  42594. */
  42595. function PBRMetallicRoughnessMaterial(name, scene) {
  42596. var _this = _super.call(this, name, scene) || this;
  42597. _this._useRoughnessFromMetallicTextureAlpha = false;
  42598. _this._useRoughnessFromMetallicTextureGreen = true;
  42599. _this._useMetallnessFromMetallicTextureBlue = true;
  42600. _this.metallic = 1.0;
  42601. _this.roughness = 1.0;
  42602. return _this;
  42603. }
  42604. /**
  42605. * Return the currrent class name of the material.
  42606. */
  42607. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42608. return "PBRMetallicRoughnessMaterial";
  42609. };
  42610. /**
  42611. * Return the active textures of the material.
  42612. */
  42613. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42614. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42615. if (this.baseTexture) {
  42616. activeTextures.push(this.baseTexture);
  42617. }
  42618. if (this.metallicRoughnessTexture) {
  42619. activeTextures.push(this.metallicRoughnessTexture);
  42620. }
  42621. return activeTextures;
  42622. };
  42623. /**
  42624. * Checks to see if a texture is used in the material.
  42625. * @param texture - Base texture to use.
  42626. * @returns - Boolean specifying if a texture is used in the material.
  42627. */
  42628. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42629. if (_super.prototype.hasTexture.call(this, texture)) {
  42630. return true;
  42631. }
  42632. if (this.baseTexture === texture) {
  42633. return true;
  42634. }
  42635. if (this.metallicRoughnessTexture === texture) {
  42636. return true;
  42637. }
  42638. return false;
  42639. };
  42640. /**
  42641. * Makes a duplicate of the current material.
  42642. * @param name - name to use for the new material.
  42643. */
  42644. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42645. var _this = this;
  42646. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42647. clone.id = name;
  42648. clone.name = name;
  42649. return clone;
  42650. };
  42651. /**
  42652. * Serialize the material to a parsable JSON object.
  42653. */
  42654. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42655. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42656. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42657. return serializationObject;
  42658. };
  42659. /**
  42660. * Parses a JSON object correponding to the serialize function.
  42661. */
  42662. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42663. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42664. };
  42665. __decorate([
  42666. BABYLON.serializeAsColor3(),
  42667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42668. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42669. __decorate([
  42670. BABYLON.serializeAsTexture(),
  42671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42672. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42673. __decorate([
  42674. BABYLON.serialize(),
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42676. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42677. __decorate([
  42678. BABYLON.serialize(),
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42680. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42681. __decorate([
  42682. BABYLON.serializeAsTexture(),
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42684. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42685. return PBRMetallicRoughnessMaterial;
  42686. }(BABYLON.PBRBaseSimpleMaterial));
  42687. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42688. })(BABYLON || (BABYLON = {}));
  42689. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42690. var BABYLON;
  42691. (function (BABYLON) {
  42692. /**
  42693. * The PBR material of BJS following the specular glossiness convention.
  42694. *
  42695. * This fits to the PBR convention in the GLTF definition:
  42696. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42697. */
  42698. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42699. __extends(PBRSpecularGlossinessMaterial, _super);
  42700. /**
  42701. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42702. *
  42703. * @param name The material name
  42704. * @param scene The scene the material will be use in.
  42705. */
  42706. function PBRSpecularGlossinessMaterial(name, scene) {
  42707. var _this = _super.call(this, name, scene) || this;
  42708. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42709. return _this;
  42710. }
  42711. /**
  42712. * Return the currrent class name of the material.
  42713. */
  42714. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42715. return "PBRSpecularGlossinessMaterial";
  42716. };
  42717. /**
  42718. * Return the active textures of the material.
  42719. */
  42720. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42721. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42722. if (this.diffuseTexture) {
  42723. activeTextures.push(this.diffuseTexture);
  42724. }
  42725. if (this.specularGlossinessTexture) {
  42726. activeTextures.push(this.specularGlossinessTexture);
  42727. }
  42728. return activeTextures;
  42729. };
  42730. /**
  42731. * Checks to see if a texture is used in the material.
  42732. * @param texture - Base texture to use.
  42733. * @returns - Boolean specifying if a texture is used in the material.
  42734. */
  42735. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42736. if (_super.prototype.hasTexture.call(this, texture)) {
  42737. return true;
  42738. }
  42739. if (this.diffuseTexture === texture) {
  42740. return true;
  42741. }
  42742. if (this.specularGlossinessTexture === texture) {
  42743. return true;
  42744. }
  42745. return false;
  42746. };
  42747. /**
  42748. * Makes a duplicate of the current material.
  42749. * @param name - name to use for the new material.
  42750. */
  42751. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42752. var _this = this;
  42753. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42754. clone.id = name;
  42755. clone.name = name;
  42756. return clone;
  42757. };
  42758. /**
  42759. * Serialize the material to a parsable JSON object.
  42760. */
  42761. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42762. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42763. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42764. return serializationObject;
  42765. };
  42766. /**
  42767. * Parses a JSON object correponding to the serialize function.
  42768. */
  42769. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42770. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42771. };
  42772. __decorate([
  42773. BABYLON.serializeAsColor3("diffuse"),
  42774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42775. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42776. __decorate([
  42777. BABYLON.serializeAsTexture(),
  42778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42779. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42780. __decorate([
  42781. BABYLON.serializeAsColor3("specular"),
  42782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42783. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42784. __decorate([
  42785. BABYLON.serialize(),
  42786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42787. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42788. __decorate([
  42789. BABYLON.serializeAsTexture(),
  42790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42791. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42792. return PBRSpecularGlossinessMaterial;
  42793. }(BABYLON.PBRBaseSimpleMaterial));
  42794. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42795. })(BABYLON || (BABYLON = {}));
  42796. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42797. var BABYLON;
  42798. (function (BABYLON) {
  42799. BABYLON.CameraInputTypes = {};
  42800. var CameraInputsManager = /** @class */ (function () {
  42801. function CameraInputsManager(camera) {
  42802. this.attached = {};
  42803. this.camera = camera;
  42804. this.checkInputs = function () { };
  42805. }
  42806. /**
  42807. * Add an input method to a camera.
  42808. * builtin inputs example: camera.inputs.addGamepad();
  42809. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42810. * @param input camera input method
  42811. */
  42812. CameraInputsManager.prototype.add = function (input) {
  42813. var type = input.getSimpleName();
  42814. if (this.attached[type]) {
  42815. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42816. return;
  42817. }
  42818. this.attached[type] = input;
  42819. input.camera = this.camera;
  42820. //for checkInputs, we are dynamically creating a function
  42821. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42822. if (input.checkInputs) {
  42823. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42824. }
  42825. if (this.attachedElement) {
  42826. input.attachControl(this.attachedElement);
  42827. }
  42828. };
  42829. /**
  42830. * Remove a specific input method from a camera
  42831. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42832. * @param inputToRemove camera input method
  42833. */
  42834. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42835. for (var cam in this.attached) {
  42836. var input = this.attached[cam];
  42837. if (input === inputToRemove) {
  42838. input.detachControl(this.attachedElement);
  42839. input.camera = null;
  42840. delete this.attached[cam];
  42841. this.rebuildInputCheck();
  42842. }
  42843. }
  42844. };
  42845. CameraInputsManager.prototype.removeByType = function (inputType) {
  42846. for (var cam in this.attached) {
  42847. var input = this.attached[cam];
  42848. if (input.getClassName() === inputType) {
  42849. input.detachControl(this.attachedElement);
  42850. input.camera = null;
  42851. delete this.attached[cam];
  42852. this.rebuildInputCheck();
  42853. }
  42854. }
  42855. };
  42856. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42857. var current = this.checkInputs;
  42858. return function () {
  42859. current();
  42860. fn();
  42861. };
  42862. };
  42863. CameraInputsManager.prototype.attachInput = function (input) {
  42864. if (this.attachedElement) {
  42865. input.attachControl(this.attachedElement, this.noPreventDefault);
  42866. }
  42867. };
  42868. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42869. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42870. if (this.attachedElement) {
  42871. return;
  42872. }
  42873. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42874. this.attachedElement = element;
  42875. this.noPreventDefault = noPreventDefault;
  42876. for (var cam in this.attached) {
  42877. this.attached[cam].attachControl(element, noPreventDefault);
  42878. }
  42879. };
  42880. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42881. if (disconnect === void 0) { disconnect = false; }
  42882. if (this.attachedElement !== element) {
  42883. return;
  42884. }
  42885. for (var cam in this.attached) {
  42886. this.attached[cam].detachControl(element);
  42887. if (disconnect) {
  42888. this.attached[cam].camera = null;
  42889. }
  42890. }
  42891. this.attachedElement = null;
  42892. };
  42893. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42894. this.checkInputs = function () { };
  42895. for (var cam in this.attached) {
  42896. var input = this.attached[cam];
  42897. if (input.checkInputs) {
  42898. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42899. }
  42900. }
  42901. };
  42902. /**
  42903. * Remove all attached input methods from a camera
  42904. */
  42905. CameraInputsManager.prototype.clear = function () {
  42906. if (this.attachedElement) {
  42907. this.detachElement(this.attachedElement, true);
  42908. }
  42909. this.attached = {};
  42910. this.attachedElement = null;
  42911. this.checkInputs = function () { };
  42912. };
  42913. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42914. var inputs = {};
  42915. for (var cam in this.attached) {
  42916. var input = this.attached[cam];
  42917. var res = BABYLON.SerializationHelper.Serialize(input);
  42918. inputs[input.getClassName()] = res;
  42919. }
  42920. serializedCamera.inputsmgr = inputs;
  42921. };
  42922. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42923. var parsedInputs = parsedCamera.inputsmgr;
  42924. if (parsedInputs) {
  42925. this.clear();
  42926. for (var n in parsedInputs) {
  42927. var construct = BABYLON.CameraInputTypes[n];
  42928. if (construct) {
  42929. var parsedinput = parsedInputs[n];
  42930. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42931. this.add(input);
  42932. }
  42933. }
  42934. }
  42935. else {
  42936. //2016-03-08 this part is for managing backward compatibility
  42937. for (var n in this.attached) {
  42938. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42939. if (construct) {
  42940. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42941. this.remove(this.attached[n]);
  42942. this.add(input);
  42943. }
  42944. }
  42945. }
  42946. };
  42947. return CameraInputsManager;
  42948. }());
  42949. BABYLON.CameraInputsManager = CameraInputsManager;
  42950. })(BABYLON || (BABYLON = {}));
  42951. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42952. var BABYLON;
  42953. (function (BABYLON) {
  42954. var TargetCamera = /** @class */ (function (_super) {
  42955. __extends(TargetCamera, _super);
  42956. function TargetCamera(name, position, scene) {
  42957. var _this = _super.call(this, name, position, scene) || this;
  42958. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42959. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42960. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42961. _this.speed = 2.0;
  42962. _this.noRotationConstraint = false;
  42963. _this.lockedTarget = null;
  42964. _this._currentTarget = BABYLON.Vector3.Zero();
  42965. _this._viewMatrix = BABYLON.Matrix.Zero();
  42966. _this._camMatrix = BABYLON.Matrix.Zero();
  42967. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42968. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42969. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42970. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42971. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42972. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42973. _this._tempMatrix = BABYLON.Matrix.Zero();
  42974. return _this;
  42975. }
  42976. TargetCamera.prototype.getFrontPosition = function (distance) {
  42977. this.getWorldMatrix();
  42978. var direction = this.getTarget().subtract(this.position);
  42979. direction.normalize();
  42980. direction.scaleInPlace(distance);
  42981. return this.globalPosition.add(direction);
  42982. };
  42983. TargetCamera.prototype._getLockedTargetPosition = function () {
  42984. if (!this.lockedTarget) {
  42985. return null;
  42986. }
  42987. if (this.lockedTarget.absolutePosition) {
  42988. this.lockedTarget.computeWorldMatrix();
  42989. }
  42990. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42991. };
  42992. TargetCamera.prototype.storeState = function () {
  42993. this._storedPosition = this.position.clone();
  42994. this._storedRotation = this.rotation.clone();
  42995. if (this.rotationQuaternion) {
  42996. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42997. }
  42998. return _super.prototype.storeState.call(this);
  42999. };
  43000. /**
  43001. * Restored camera state. You must call storeState() first
  43002. */
  43003. TargetCamera.prototype._restoreStateValues = function () {
  43004. if (!_super.prototype._restoreStateValues.call(this)) {
  43005. return false;
  43006. }
  43007. this.position = this._storedPosition.clone();
  43008. this.rotation = this._storedRotation.clone();
  43009. if (this.rotationQuaternion) {
  43010. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43011. }
  43012. this.cameraDirection.copyFromFloats(0, 0, 0);
  43013. this.cameraRotation.copyFromFloats(0, 0);
  43014. return true;
  43015. };
  43016. // Cache
  43017. TargetCamera.prototype._initCache = function () {
  43018. _super.prototype._initCache.call(this);
  43019. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43020. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43021. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43022. };
  43023. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43024. if (!ignoreParentClass) {
  43025. _super.prototype._updateCache.call(this);
  43026. }
  43027. var lockedTargetPosition = this._getLockedTargetPosition();
  43028. if (!lockedTargetPosition) {
  43029. this._cache.lockedTarget = null;
  43030. }
  43031. else {
  43032. if (!this._cache.lockedTarget) {
  43033. this._cache.lockedTarget = lockedTargetPosition.clone();
  43034. }
  43035. else {
  43036. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43037. }
  43038. }
  43039. this._cache.rotation.copyFrom(this.rotation);
  43040. if (this.rotationQuaternion)
  43041. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43042. };
  43043. // Synchronized
  43044. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43045. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43046. return false;
  43047. }
  43048. var lockedTargetPosition = this._getLockedTargetPosition();
  43049. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43050. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43051. };
  43052. // Methods
  43053. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43054. var engine = this.getEngine();
  43055. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43056. };
  43057. // Target
  43058. TargetCamera.prototype.setTarget = function (target) {
  43059. this.upVector.normalize();
  43060. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43061. this._camMatrix.invert();
  43062. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43063. var vDir = target.subtract(this.position);
  43064. if (vDir.x >= 0.0) {
  43065. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43066. }
  43067. else {
  43068. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43069. }
  43070. this.rotation.z = 0;
  43071. if (isNaN(this.rotation.x)) {
  43072. this.rotation.x = 0;
  43073. }
  43074. if (isNaN(this.rotation.y)) {
  43075. this.rotation.y = 0;
  43076. }
  43077. if (isNaN(this.rotation.z)) {
  43078. this.rotation.z = 0;
  43079. }
  43080. if (this.rotationQuaternion) {
  43081. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43082. }
  43083. };
  43084. /**
  43085. * Return the current target position of the camera. This value is expressed in local space.
  43086. */
  43087. TargetCamera.prototype.getTarget = function () {
  43088. return this._currentTarget;
  43089. };
  43090. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43091. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43092. };
  43093. TargetCamera.prototype._updatePosition = function () {
  43094. if (this.parent) {
  43095. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43096. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43097. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43098. return;
  43099. }
  43100. this.position.addInPlace(this.cameraDirection);
  43101. };
  43102. TargetCamera.prototype._checkInputs = function () {
  43103. var needToMove = this._decideIfNeedsToMove();
  43104. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43105. // Move
  43106. if (needToMove) {
  43107. this._updatePosition();
  43108. }
  43109. // Rotate
  43110. if (needToRotate) {
  43111. this.rotation.x += this.cameraRotation.x;
  43112. this.rotation.y += this.cameraRotation.y;
  43113. //rotate, if quaternion is set and rotation was used
  43114. if (this.rotationQuaternion) {
  43115. var len = this.rotation.lengthSquared();
  43116. if (len) {
  43117. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43118. }
  43119. }
  43120. if (!this.noRotationConstraint) {
  43121. var limit = (Math.PI / 2) * 0.95;
  43122. if (this.rotation.x > limit)
  43123. this.rotation.x = limit;
  43124. if (this.rotation.x < -limit)
  43125. this.rotation.x = -limit;
  43126. }
  43127. }
  43128. // Inertia
  43129. if (needToMove) {
  43130. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43131. this.cameraDirection.x = 0;
  43132. }
  43133. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43134. this.cameraDirection.y = 0;
  43135. }
  43136. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43137. this.cameraDirection.z = 0;
  43138. }
  43139. this.cameraDirection.scaleInPlace(this.inertia);
  43140. }
  43141. if (needToRotate) {
  43142. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43143. this.cameraRotation.x = 0;
  43144. }
  43145. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43146. this.cameraRotation.y = 0;
  43147. }
  43148. this.cameraRotation.scaleInPlace(this.inertia);
  43149. }
  43150. _super.prototype._checkInputs.call(this);
  43151. };
  43152. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43153. if (this.rotationQuaternion) {
  43154. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43155. }
  43156. else {
  43157. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43158. }
  43159. //update the up vector!
  43160. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43161. };
  43162. TargetCamera.prototype._getViewMatrix = function () {
  43163. if (this.lockedTarget) {
  43164. this.setTarget(this._getLockedTargetPosition());
  43165. }
  43166. // Compute
  43167. this._updateCameraRotationMatrix();
  43168. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43169. // Computing target and final matrix
  43170. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43171. if (this.getScene().useRightHandedSystem) {
  43172. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43173. }
  43174. else {
  43175. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43176. }
  43177. return this._viewMatrix;
  43178. };
  43179. /**
  43180. * @override
  43181. * Override Camera.createRigCamera
  43182. */
  43183. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43184. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43185. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43186. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43187. if (!this.rotationQuaternion) {
  43188. this.rotationQuaternion = new BABYLON.Quaternion();
  43189. }
  43190. rigCamera._cameraRigParams = {};
  43191. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43192. }
  43193. return rigCamera;
  43194. }
  43195. return null;
  43196. };
  43197. /**
  43198. * @override
  43199. * Override Camera._updateRigCameras
  43200. */
  43201. TargetCamera.prototype._updateRigCameras = function () {
  43202. var camLeft = this._rigCameras[0];
  43203. var camRight = this._rigCameras[1];
  43204. switch (this.cameraRigMode) {
  43205. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43206. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43207. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43208. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43209. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43210. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43211. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43212. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43213. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43214. camLeft.setTarget(this.getTarget());
  43215. camRight.setTarget(this.getTarget());
  43216. break;
  43217. case BABYLON.Camera.RIG_MODE_VR:
  43218. if (camLeft.rotationQuaternion) {
  43219. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43220. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43221. }
  43222. else {
  43223. camLeft.rotation.copyFrom(this.rotation);
  43224. camRight.rotation.copyFrom(this.rotation);
  43225. }
  43226. camLeft.position.copyFrom(this.position);
  43227. camRight.position.copyFrom(this.position);
  43228. break;
  43229. }
  43230. _super.prototype._updateRigCameras.call(this);
  43231. };
  43232. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43233. if (!this._rigCamTransformMatrix) {
  43234. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43235. }
  43236. var target = this.getTarget();
  43237. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43238. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43239. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43240. };
  43241. TargetCamera.prototype.getClassName = function () {
  43242. return "TargetCamera";
  43243. };
  43244. __decorate([
  43245. BABYLON.serializeAsVector3()
  43246. ], TargetCamera.prototype, "rotation", void 0);
  43247. __decorate([
  43248. BABYLON.serialize()
  43249. ], TargetCamera.prototype, "speed", void 0);
  43250. __decorate([
  43251. BABYLON.serializeAsMeshReference("lockedTargetId")
  43252. ], TargetCamera.prototype, "lockedTarget", void 0);
  43253. return TargetCamera;
  43254. }(BABYLON.Camera));
  43255. BABYLON.TargetCamera = TargetCamera;
  43256. })(BABYLON || (BABYLON = {}));
  43257. //# sourceMappingURL=babylon.targetCamera.js.map
  43258. var BABYLON;
  43259. (function (BABYLON) {
  43260. var FreeCameraMouseInput = /** @class */ (function () {
  43261. function FreeCameraMouseInput(touchEnabled) {
  43262. if (touchEnabled === void 0) { touchEnabled = true; }
  43263. this.touchEnabled = touchEnabled;
  43264. this.buttons = [0, 1, 2];
  43265. this.angularSensibility = 2000.0;
  43266. this.previousPosition = null;
  43267. }
  43268. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43269. var _this = this;
  43270. var engine = this.camera.getEngine();
  43271. if (!this._pointerInput) {
  43272. this._pointerInput = function (p, s) {
  43273. var evt = p.event;
  43274. if (engine.isInVRExclusivePointerMode) {
  43275. return;
  43276. }
  43277. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43278. return;
  43279. }
  43280. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43281. return;
  43282. }
  43283. var srcElement = (evt.srcElement || evt.target);
  43284. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43285. try {
  43286. srcElement.setPointerCapture(evt.pointerId);
  43287. }
  43288. catch (e) {
  43289. //Nothing to do with the error. Execution will continue.
  43290. }
  43291. _this.previousPosition = {
  43292. x: evt.clientX,
  43293. y: evt.clientY
  43294. };
  43295. if (!noPreventDefault) {
  43296. evt.preventDefault();
  43297. element.focus();
  43298. }
  43299. }
  43300. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43301. try {
  43302. srcElement.releasePointerCapture(evt.pointerId);
  43303. }
  43304. catch (e) {
  43305. //Nothing to do with the error.
  43306. }
  43307. _this.previousPosition = null;
  43308. if (!noPreventDefault) {
  43309. evt.preventDefault();
  43310. }
  43311. }
  43312. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43313. if (!_this.previousPosition || engine.isPointerLock) {
  43314. return;
  43315. }
  43316. var offsetX = evt.clientX - _this.previousPosition.x;
  43317. var offsetY = evt.clientY - _this.previousPosition.y;
  43318. if (_this.camera.getScene().useRightHandedSystem) {
  43319. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43320. }
  43321. else {
  43322. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43323. }
  43324. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43325. _this.previousPosition = {
  43326. x: evt.clientX,
  43327. y: evt.clientY
  43328. };
  43329. if (!noPreventDefault) {
  43330. evt.preventDefault();
  43331. }
  43332. }
  43333. };
  43334. }
  43335. this._onMouseMove = function (evt) {
  43336. if (!engine.isPointerLock) {
  43337. return;
  43338. }
  43339. if (engine.isInVRExclusivePointerMode) {
  43340. return;
  43341. }
  43342. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43343. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43344. if (_this.camera.getScene().useRightHandedSystem) {
  43345. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43346. }
  43347. else {
  43348. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43349. }
  43350. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43351. _this.previousPosition = null;
  43352. if (!noPreventDefault) {
  43353. evt.preventDefault();
  43354. }
  43355. };
  43356. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43357. element.addEventListener("mousemove", this._onMouseMove, false);
  43358. };
  43359. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43360. if (this._observer && element) {
  43361. this.camera.getScene().onPointerObservable.remove(this._observer);
  43362. if (this._onMouseMove) {
  43363. element.removeEventListener("mousemove", this._onMouseMove);
  43364. }
  43365. this._observer = null;
  43366. this._onMouseMove = null;
  43367. this.previousPosition = null;
  43368. }
  43369. };
  43370. FreeCameraMouseInput.prototype.getClassName = function () {
  43371. return "FreeCameraMouseInput";
  43372. };
  43373. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43374. return "mouse";
  43375. };
  43376. __decorate([
  43377. BABYLON.serialize()
  43378. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43379. __decorate([
  43380. BABYLON.serialize()
  43381. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43382. return FreeCameraMouseInput;
  43383. }());
  43384. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43385. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43386. })(BABYLON || (BABYLON = {}));
  43387. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43388. var BABYLON;
  43389. (function (BABYLON) {
  43390. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43391. function FreeCameraKeyboardMoveInput() {
  43392. this._keys = new Array();
  43393. this.keysUp = [38];
  43394. this.keysDown = [40];
  43395. this.keysLeft = [37];
  43396. this.keysRight = [39];
  43397. }
  43398. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43399. var _this = this;
  43400. if (this._onCanvasBlurObserver) {
  43401. return;
  43402. }
  43403. this._scene = this.camera.getScene();
  43404. this._engine = this._scene.getEngine();
  43405. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43406. _this._keys = [];
  43407. });
  43408. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43409. var evt = info.event;
  43410. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43411. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43412. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43413. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43414. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43415. var index = _this._keys.indexOf(evt.keyCode);
  43416. if (index === -1) {
  43417. _this._keys.push(evt.keyCode);
  43418. }
  43419. if (!noPreventDefault) {
  43420. evt.preventDefault();
  43421. }
  43422. }
  43423. }
  43424. else {
  43425. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43426. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43427. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43428. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43429. var index = _this._keys.indexOf(evt.keyCode);
  43430. if (index >= 0) {
  43431. _this._keys.splice(index, 1);
  43432. }
  43433. if (!noPreventDefault) {
  43434. evt.preventDefault();
  43435. }
  43436. }
  43437. }
  43438. });
  43439. };
  43440. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43441. if (this._scene) {
  43442. if (this._onKeyboardObserver) {
  43443. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43444. }
  43445. if (this._onCanvasBlurObserver) {
  43446. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43447. }
  43448. this._onKeyboardObserver = null;
  43449. this._onCanvasBlurObserver = null;
  43450. }
  43451. this._keys = [];
  43452. };
  43453. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43454. if (this._onKeyboardObserver) {
  43455. var camera = this.camera;
  43456. // Keyboard
  43457. for (var index = 0; index < this._keys.length; index++) {
  43458. var keyCode = this._keys[index];
  43459. var speed = camera._computeLocalCameraSpeed();
  43460. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43461. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43462. }
  43463. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43464. camera._localDirection.copyFromFloats(0, 0, speed);
  43465. }
  43466. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43467. camera._localDirection.copyFromFloats(speed, 0, 0);
  43468. }
  43469. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43470. camera._localDirection.copyFromFloats(0, 0, -speed);
  43471. }
  43472. if (camera.getScene().useRightHandedSystem) {
  43473. camera._localDirection.z *= -1;
  43474. }
  43475. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43476. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43477. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43478. }
  43479. }
  43480. };
  43481. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43482. return "FreeCameraKeyboardMoveInput";
  43483. };
  43484. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43485. this._keys = [];
  43486. };
  43487. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43488. return "keyboard";
  43489. };
  43490. __decorate([
  43491. BABYLON.serialize()
  43492. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43493. __decorate([
  43494. BABYLON.serialize()
  43495. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43496. __decorate([
  43497. BABYLON.serialize()
  43498. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43499. __decorate([
  43500. BABYLON.serialize()
  43501. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43502. return FreeCameraKeyboardMoveInput;
  43503. }());
  43504. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43505. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43506. })(BABYLON || (BABYLON = {}));
  43507. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43508. var BABYLON;
  43509. (function (BABYLON) {
  43510. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43511. __extends(FreeCameraInputsManager, _super);
  43512. function FreeCameraInputsManager(camera) {
  43513. return _super.call(this, camera) || this;
  43514. }
  43515. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43516. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43517. return this;
  43518. };
  43519. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43520. if (touchEnabled === void 0) { touchEnabled = true; }
  43521. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43522. return this;
  43523. };
  43524. FreeCameraInputsManager.prototype.addGamepad = function () {
  43525. this.add(new BABYLON.FreeCameraGamepadInput());
  43526. return this;
  43527. };
  43528. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43529. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43530. return this;
  43531. };
  43532. FreeCameraInputsManager.prototype.addTouch = function () {
  43533. this.add(new BABYLON.FreeCameraTouchInput());
  43534. return this;
  43535. };
  43536. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43537. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43538. return this;
  43539. };
  43540. return FreeCameraInputsManager;
  43541. }(BABYLON.CameraInputsManager));
  43542. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43543. })(BABYLON || (BABYLON = {}));
  43544. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43545. var BABYLON;
  43546. (function (BABYLON) {
  43547. var FreeCamera = /** @class */ (function (_super) {
  43548. __extends(FreeCamera, _super);
  43549. function FreeCamera(name, position, scene) {
  43550. var _this = _super.call(this, name, position, scene) || this;
  43551. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43552. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43553. _this.checkCollisions = false;
  43554. _this.applyGravity = false;
  43555. _this._needMoveForGravity = false;
  43556. _this._oldPosition = BABYLON.Vector3.Zero();
  43557. _this._diffPosition = BABYLON.Vector3.Zero();
  43558. _this._newPosition = BABYLON.Vector3.Zero();
  43559. // Collisions
  43560. _this._collisionMask = -1;
  43561. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43562. if (collidedMesh === void 0) { collidedMesh = null; }
  43563. //TODO move this to the collision coordinator!
  43564. if (_this.getScene().workerCollisions)
  43565. newPosition.multiplyInPlace(_this._collider._radius);
  43566. var updatePosition = function (newPos) {
  43567. _this._newPosition.copyFrom(newPos);
  43568. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43569. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43570. _this.position.addInPlace(_this._diffPosition);
  43571. if (_this.onCollide && collidedMesh) {
  43572. _this.onCollide(collidedMesh);
  43573. }
  43574. }
  43575. };
  43576. updatePosition(newPosition);
  43577. };
  43578. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43579. _this.inputs.addKeyboard().addMouse();
  43580. return _this;
  43581. }
  43582. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43583. //-- begin properties for backward compatibility for inputs
  43584. /**
  43585. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43586. * Higher values reduce sensitivity.
  43587. */
  43588. get: function () {
  43589. var mouse = this.inputs.attached["mouse"];
  43590. if (mouse)
  43591. return mouse.angularSensibility;
  43592. return 0;
  43593. },
  43594. /**
  43595. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43596. * Higher values reduce sensitivity.
  43597. */
  43598. set: function (value) {
  43599. var mouse = this.inputs.attached["mouse"];
  43600. if (mouse)
  43601. mouse.angularSensibility = value;
  43602. },
  43603. enumerable: true,
  43604. configurable: true
  43605. });
  43606. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43607. get: function () {
  43608. var keyboard = this.inputs.attached["keyboard"];
  43609. if (keyboard)
  43610. return keyboard.keysUp;
  43611. return [];
  43612. },
  43613. set: function (value) {
  43614. var keyboard = this.inputs.attached["keyboard"];
  43615. if (keyboard)
  43616. keyboard.keysUp = value;
  43617. },
  43618. enumerable: true,
  43619. configurable: true
  43620. });
  43621. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43622. get: function () {
  43623. var keyboard = this.inputs.attached["keyboard"];
  43624. if (keyboard)
  43625. return keyboard.keysDown;
  43626. return [];
  43627. },
  43628. set: function (value) {
  43629. var keyboard = this.inputs.attached["keyboard"];
  43630. if (keyboard)
  43631. keyboard.keysDown = value;
  43632. },
  43633. enumerable: true,
  43634. configurable: true
  43635. });
  43636. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43637. get: function () {
  43638. var keyboard = this.inputs.attached["keyboard"];
  43639. if (keyboard)
  43640. return keyboard.keysLeft;
  43641. return [];
  43642. },
  43643. set: function (value) {
  43644. var keyboard = this.inputs.attached["keyboard"];
  43645. if (keyboard)
  43646. keyboard.keysLeft = value;
  43647. },
  43648. enumerable: true,
  43649. configurable: true
  43650. });
  43651. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43652. get: function () {
  43653. var keyboard = this.inputs.attached["keyboard"];
  43654. if (keyboard)
  43655. return keyboard.keysRight;
  43656. return [];
  43657. },
  43658. set: function (value) {
  43659. var keyboard = this.inputs.attached["keyboard"];
  43660. if (keyboard)
  43661. keyboard.keysRight = value;
  43662. },
  43663. enumerable: true,
  43664. configurable: true
  43665. });
  43666. // Controls
  43667. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43668. this.inputs.attachElement(element, noPreventDefault);
  43669. };
  43670. FreeCamera.prototype.detachControl = function (element) {
  43671. this.inputs.detachElement(element);
  43672. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43673. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43674. };
  43675. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43676. get: function () {
  43677. return this._collisionMask;
  43678. },
  43679. set: function (mask) {
  43680. this._collisionMask = !isNaN(mask) ? mask : -1;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43686. var globalPosition;
  43687. if (this.parent) {
  43688. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43689. }
  43690. else {
  43691. globalPosition = this.position;
  43692. }
  43693. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43694. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43695. if (!this._collider) {
  43696. this._collider = new BABYLON.Collider();
  43697. }
  43698. this._collider._radius = this.ellipsoid;
  43699. this._collider.collisionMask = this._collisionMask;
  43700. //no need for clone, as long as gravity is not on.
  43701. var actualDisplacement = displacement;
  43702. //add gravity to the direction to prevent the dual-collision checking
  43703. if (this.applyGravity) {
  43704. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43705. actualDisplacement = displacement.add(this.getScene().gravity);
  43706. }
  43707. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43708. };
  43709. FreeCamera.prototype._checkInputs = function () {
  43710. if (!this._localDirection) {
  43711. this._localDirection = BABYLON.Vector3.Zero();
  43712. this._transformedDirection = BABYLON.Vector3.Zero();
  43713. }
  43714. this.inputs.checkInputs();
  43715. _super.prototype._checkInputs.call(this);
  43716. };
  43717. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43718. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43719. };
  43720. FreeCamera.prototype._updatePosition = function () {
  43721. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43722. this._collideWithWorld(this.cameraDirection);
  43723. }
  43724. else {
  43725. _super.prototype._updatePosition.call(this);
  43726. }
  43727. };
  43728. FreeCamera.prototype.dispose = function () {
  43729. this.inputs.clear();
  43730. _super.prototype.dispose.call(this);
  43731. };
  43732. FreeCamera.prototype.getClassName = function () {
  43733. return "FreeCamera";
  43734. };
  43735. __decorate([
  43736. BABYLON.serializeAsVector3()
  43737. ], FreeCamera.prototype, "ellipsoid", void 0);
  43738. __decorate([
  43739. BABYLON.serializeAsVector3()
  43740. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43741. __decorate([
  43742. BABYLON.serialize()
  43743. ], FreeCamera.prototype, "checkCollisions", void 0);
  43744. __decorate([
  43745. BABYLON.serialize()
  43746. ], FreeCamera.prototype, "applyGravity", void 0);
  43747. return FreeCamera;
  43748. }(BABYLON.TargetCamera));
  43749. BABYLON.FreeCamera = FreeCamera;
  43750. })(BABYLON || (BABYLON = {}));
  43751. //# sourceMappingURL=babylon.freeCamera.js.map
  43752. var BABYLON;
  43753. (function (BABYLON) {
  43754. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43755. function ArcRotateCameraKeyboardMoveInput() {
  43756. this._keys = new Array();
  43757. this.keysUp = [38];
  43758. this.keysDown = [40];
  43759. this.keysLeft = [37];
  43760. this.keysRight = [39];
  43761. this.keysReset = [220];
  43762. this.panningSensibility = 50.0;
  43763. this.zoomingSensibility = 25.0;
  43764. this.useAltToZoom = true;
  43765. }
  43766. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43767. var _this = this;
  43768. if (this._onCanvasBlurObserver) {
  43769. return;
  43770. }
  43771. this._scene = this.camera.getScene();
  43772. this._engine = this._scene.getEngine();
  43773. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43774. _this._keys = [];
  43775. });
  43776. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43777. var evt = info.event;
  43778. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43779. _this._ctrlPressed = evt.ctrlKey;
  43780. _this._altPressed = evt.altKey;
  43781. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43782. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43783. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43784. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43785. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43786. var index = _this._keys.indexOf(evt.keyCode);
  43787. if (index === -1) {
  43788. _this._keys.push(evt.keyCode);
  43789. }
  43790. if (evt.preventDefault) {
  43791. if (!noPreventDefault) {
  43792. evt.preventDefault();
  43793. }
  43794. }
  43795. }
  43796. }
  43797. else {
  43798. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43799. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43800. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43801. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43802. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43803. var index = _this._keys.indexOf(evt.keyCode);
  43804. if (index >= 0) {
  43805. _this._keys.splice(index, 1);
  43806. }
  43807. if (evt.preventDefault) {
  43808. if (!noPreventDefault) {
  43809. evt.preventDefault();
  43810. }
  43811. }
  43812. }
  43813. }
  43814. });
  43815. };
  43816. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43817. if (this._scene) {
  43818. if (this._onKeyboardObserver) {
  43819. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43820. }
  43821. if (this._onCanvasBlurObserver) {
  43822. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43823. }
  43824. this._onKeyboardObserver = null;
  43825. this._onCanvasBlurObserver = null;
  43826. }
  43827. this._keys = [];
  43828. };
  43829. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43830. if (this._onKeyboardObserver) {
  43831. var camera = this.camera;
  43832. for (var index = 0; index < this._keys.length; index++) {
  43833. var keyCode = this._keys[index];
  43834. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43835. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43836. camera.inertialPanningX -= 1 / this.panningSensibility;
  43837. }
  43838. else {
  43839. camera.inertialAlphaOffset -= 0.01;
  43840. }
  43841. }
  43842. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43843. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43844. camera.inertialPanningY += 1 / this.panningSensibility;
  43845. }
  43846. else if (this._altPressed && this.useAltToZoom) {
  43847. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43848. }
  43849. else {
  43850. camera.inertialBetaOffset -= 0.01;
  43851. }
  43852. }
  43853. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43854. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43855. camera.inertialPanningX += 1 / this.panningSensibility;
  43856. }
  43857. else {
  43858. camera.inertialAlphaOffset += 0.01;
  43859. }
  43860. }
  43861. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43862. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43863. camera.inertialPanningY -= 1 / this.panningSensibility;
  43864. }
  43865. else if (this._altPressed && this.useAltToZoom) {
  43866. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43867. }
  43868. else {
  43869. camera.inertialBetaOffset += 0.01;
  43870. }
  43871. }
  43872. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43873. camera.restoreState();
  43874. }
  43875. }
  43876. }
  43877. };
  43878. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43879. return "ArcRotateCameraKeyboardMoveInput";
  43880. };
  43881. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43882. return "keyboard";
  43883. };
  43884. __decorate([
  43885. BABYLON.serialize()
  43886. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43887. __decorate([
  43888. BABYLON.serialize()
  43889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43890. __decorate([
  43891. BABYLON.serialize()
  43892. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43893. __decorate([
  43894. BABYLON.serialize()
  43895. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43896. __decorate([
  43897. BABYLON.serialize()
  43898. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43899. __decorate([
  43900. BABYLON.serialize()
  43901. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43902. __decorate([
  43903. BABYLON.serialize()
  43904. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43905. __decorate([
  43906. BABYLON.serialize()
  43907. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43908. return ArcRotateCameraKeyboardMoveInput;
  43909. }());
  43910. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43911. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43912. })(BABYLON || (BABYLON = {}));
  43913. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43914. var BABYLON;
  43915. (function (BABYLON) {
  43916. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43917. function ArcRotateCameraMouseWheelInput() {
  43918. this.wheelPrecision = 3.0;
  43919. /**
  43920. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43921. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43922. */
  43923. this.wheelDeltaPercentage = 0;
  43924. }
  43925. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43926. var _this = this;
  43927. this._wheel = function (p, s) {
  43928. //sanity check - this should be a PointerWheel event.
  43929. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43930. return;
  43931. var event = p.event;
  43932. var delta = 0;
  43933. if (event.wheelDelta) {
  43934. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43935. }
  43936. else if (event.detail) {
  43937. delta = -event.detail / _this.wheelPrecision;
  43938. }
  43939. if (delta)
  43940. _this.camera.inertialRadiusOffset += delta;
  43941. if (event.preventDefault) {
  43942. if (!noPreventDefault) {
  43943. event.preventDefault();
  43944. }
  43945. }
  43946. };
  43947. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43948. };
  43949. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43950. if (this._observer && element) {
  43951. this.camera.getScene().onPointerObservable.remove(this._observer);
  43952. this._observer = null;
  43953. this._wheel = null;
  43954. }
  43955. };
  43956. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43957. return "ArcRotateCameraMouseWheelInput";
  43958. };
  43959. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43960. return "mousewheel";
  43961. };
  43962. __decorate([
  43963. BABYLON.serialize()
  43964. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43965. __decorate([
  43966. BABYLON.serialize()
  43967. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43968. return ArcRotateCameraMouseWheelInput;
  43969. }());
  43970. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43971. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43972. })(BABYLON || (BABYLON = {}));
  43973. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43974. var BABYLON;
  43975. (function (BABYLON) {
  43976. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43977. function ArcRotateCameraPointersInput() {
  43978. this.buttons = [0, 1, 2];
  43979. this.angularSensibilityX = 1000.0;
  43980. this.angularSensibilityY = 1000.0;
  43981. this.pinchPrecision = 12.0;
  43982. /**
  43983. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43984. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43985. */
  43986. this.pinchDeltaPercentage = 0;
  43987. this.panningSensibility = 1000.0;
  43988. this.multiTouchPanning = true;
  43989. this.multiTouchPanAndZoom = true;
  43990. this._isPanClick = false;
  43991. this.pinchInwards = true;
  43992. }
  43993. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43994. var _this = this;
  43995. var engine = this.camera.getEngine();
  43996. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43997. var pointA = null;
  43998. var pointB = null;
  43999. var previousPinchSquaredDistance = 0;
  44000. var initialDistance = 0;
  44001. var twoFingerActivityCount = 0;
  44002. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44003. this._pointerInput = function (p, s) {
  44004. var evt = p.event;
  44005. var isTouch = p.event.pointerType === "touch";
  44006. if (engine.isInVRExclusivePointerMode) {
  44007. return;
  44008. }
  44009. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44010. return;
  44011. }
  44012. var srcElement = (evt.srcElement || evt.target);
  44013. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44014. try {
  44015. srcElement.setPointerCapture(evt.pointerId);
  44016. }
  44017. catch (e) {
  44018. //Nothing to do with the error. Execution will continue.
  44019. }
  44020. // Manage panning with pan button click
  44021. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44022. // manage pointers
  44023. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44024. if (pointA === null) {
  44025. pointA = cacheSoloPointer;
  44026. }
  44027. else if (pointB === null) {
  44028. pointB = cacheSoloPointer;
  44029. }
  44030. if (!noPreventDefault) {
  44031. evt.preventDefault();
  44032. element.focus();
  44033. }
  44034. }
  44035. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44036. _this.camera.restoreState();
  44037. }
  44038. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44039. try {
  44040. srcElement.releasePointerCapture(evt.pointerId);
  44041. }
  44042. catch (e) {
  44043. //Nothing to do with the error.
  44044. }
  44045. cacheSoloPointer = null;
  44046. previousPinchSquaredDistance = 0;
  44047. previousMultiTouchPanPosition.isPaning = false;
  44048. previousMultiTouchPanPosition.isPinching = false;
  44049. twoFingerActivityCount = 0;
  44050. initialDistance = 0;
  44051. if (!isTouch) {
  44052. pointB = null; // Mouse and pen are mono pointer
  44053. }
  44054. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44055. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44056. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44057. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44058. if (engine.badOS) {
  44059. pointA = pointB = null;
  44060. }
  44061. else {
  44062. //only remove the impacted pointer in case of multitouch allowing on most
  44063. //platforms switching from rotate to zoom and pan seamlessly.
  44064. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44065. pointA = pointB;
  44066. pointB = null;
  44067. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44068. }
  44069. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44070. pointB = null;
  44071. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44072. }
  44073. else {
  44074. pointA = pointB = null;
  44075. }
  44076. }
  44077. if (!noPreventDefault) {
  44078. evt.preventDefault();
  44079. }
  44080. }
  44081. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44082. if (!noPreventDefault) {
  44083. evt.preventDefault();
  44084. }
  44085. // One button down
  44086. if (pointA && pointB === null && cacheSoloPointer) {
  44087. if (_this.panningSensibility !== 0 &&
  44088. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44089. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44090. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44091. }
  44092. else {
  44093. var offsetX = evt.clientX - cacheSoloPointer.x;
  44094. var offsetY = evt.clientY - cacheSoloPointer.y;
  44095. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44096. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44097. }
  44098. cacheSoloPointer.x = evt.clientX;
  44099. cacheSoloPointer.y = evt.clientY;
  44100. }
  44101. else if (pointA && pointB) {
  44102. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44103. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44104. ed.x = evt.clientX;
  44105. ed.y = evt.clientY;
  44106. var direction = _this.pinchInwards ? 1 : -1;
  44107. var distX = pointA.x - pointB.x;
  44108. var distY = pointA.y - pointB.y;
  44109. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44110. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44111. if (previousPinchSquaredDistance === 0) {
  44112. initialDistance = pinchDistance;
  44113. previousPinchSquaredDistance = pinchSquaredDistance;
  44114. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44115. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44116. return;
  44117. }
  44118. if (_this.multiTouchPanAndZoom) {
  44119. if (_this.pinchDeltaPercentage) {
  44120. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44121. }
  44122. else {
  44123. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44124. (_this.pinchPrecision *
  44125. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44126. direction);
  44127. }
  44128. if (_this.panningSensibility !== 0) {
  44129. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44130. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44131. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44132. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44133. previousMultiTouchPanPosition.x = pointersCenterX;
  44134. previousMultiTouchPanPosition.y = pointersCenterY;
  44135. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44136. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44137. }
  44138. }
  44139. else {
  44140. twoFingerActivityCount++;
  44141. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44142. if (_this.pinchDeltaPercentage) {
  44143. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44144. }
  44145. else {
  44146. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44147. (_this.pinchPrecision *
  44148. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44149. direction);
  44150. }
  44151. previousMultiTouchPanPosition.isPaning = false;
  44152. previousMultiTouchPanPosition.isPinching = true;
  44153. }
  44154. else {
  44155. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44156. if (!previousMultiTouchPanPosition.isPaning) {
  44157. previousMultiTouchPanPosition.isPaning = true;
  44158. previousMultiTouchPanPosition.isPinching = false;
  44159. previousMultiTouchPanPosition.x = ed.x;
  44160. previousMultiTouchPanPosition.y = ed.y;
  44161. return;
  44162. }
  44163. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44164. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44165. }
  44166. }
  44167. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44168. previousMultiTouchPanPosition.x = ed.x;
  44169. previousMultiTouchPanPosition.y = ed.y;
  44170. }
  44171. }
  44172. previousPinchSquaredDistance = pinchSquaredDistance;
  44173. }
  44174. }
  44175. };
  44176. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44177. this._onContextMenu = function (evt) {
  44178. evt.preventDefault();
  44179. };
  44180. if (!this.camera._useCtrlForPanning) {
  44181. element.addEventListener("contextmenu", this._onContextMenu, false);
  44182. }
  44183. this._onLostFocus = function () {
  44184. //this._keys = [];
  44185. pointA = pointB = null;
  44186. previousPinchSquaredDistance = 0;
  44187. previousMultiTouchPanPosition.isPaning = false;
  44188. previousMultiTouchPanPosition.isPinching = false;
  44189. twoFingerActivityCount = 0;
  44190. cacheSoloPointer = null;
  44191. initialDistance = 0;
  44192. };
  44193. this._onMouseMove = function (evt) {
  44194. if (!engine.isPointerLock) {
  44195. return;
  44196. }
  44197. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44198. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44199. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44200. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44201. if (!noPreventDefault) {
  44202. evt.preventDefault();
  44203. }
  44204. };
  44205. this._onGestureStart = function (e) {
  44206. if (window.MSGesture === undefined) {
  44207. return;
  44208. }
  44209. if (!_this._MSGestureHandler) {
  44210. _this._MSGestureHandler = new MSGesture();
  44211. _this._MSGestureHandler.target = element;
  44212. }
  44213. _this._MSGestureHandler.addPointer(e.pointerId);
  44214. };
  44215. this._onGesture = function (e) {
  44216. _this.camera.radius *= e.scale;
  44217. if (e.preventDefault) {
  44218. if (!noPreventDefault) {
  44219. e.stopPropagation();
  44220. e.preventDefault();
  44221. }
  44222. }
  44223. };
  44224. element.addEventListener("mousemove", this._onMouseMove, false);
  44225. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44226. element.addEventListener("MSGestureChange", this._onGesture, false);
  44227. BABYLON.Tools.RegisterTopRootEvents([
  44228. { name: "blur", handler: this._onLostFocus }
  44229. ]);
  44230. };
  44231. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44232. if (this._onLostFocus) {
  44233. BABYLON.Tools.UnregisterTopRootEvents([
  44234. { name: "blur", handler: this._onLostFocus }
  44235. ]);
  44236. }
  44237. if (element && this._observer) {
  44238. this.camera.getScene().onPointerObservable.remove(this._observer);
  44239. this._observer = null;
  44240. if (this._onContextMenu) {
  44241. element.removeEventListener("contextmenu", this._onContextMenu);
  44242. }
  44243. if (this._onMouseMove) {
  44244. element.removeEventListener("mousemove", this._onMouseMove);
  44245. }
  44246. if (this._onGestureStart) {
  44247. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44248. }
  44249. if (this._onGesture) {
  44250. element.removeEventListener("MSGestureChange", this._onGesture);
  44251. }
  44252. this._isPanClick = false;
  44253. this.pinchInwards = true;
  44254. this._onMouseMove = null;
  44255. this._onGestureStart = null;
  44256. this._onGesture = null;
  44257. this._MSGestureHandler = null;
  44258. this._onLostFocus = null;
  44259. this._onContextMenu = null;
  44260. }
  44261. };
  44262. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44263. return "ArcRotateCameraPointersInput";
  44264. };
  44265. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44266. return "pointers";
  44267. };
  44268. __decorate([
  44269. BABYLON.serialize()
  44270. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44271. __decorate([
  44272. BABYLON.serialize()
  44273. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44274. __decorate([
  44275. BABYLON.serialize()
  44276. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44277. __decorate([
  44278. BABYLON.serialize()
  44279. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44280. __decorate([
  44281. BABYLON.serialize()
  44282. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44283. __decorate([
  44284. BABYLON.serialize()
  44285. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44286. __decorate([
  44287. BABYLON.serialize()
  44288. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44289. __decorate([
  44290. BABYLON.serialize()
  44291. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44292. return ArcRotateCameraPointersInput;
  44293. }());
  44294. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44295. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44296. })(BABYLON || (BABYLON = {}));
  44297. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44298. var BABYLON;
  44299. (function (BABYLON) {
  44300. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44301. __extends(ArcRotateCameraInputsManager, _super);
  44302. function ArcRotateCameraInputsManager(camera) {
  44303. return _super.call(this, camera) || this;
  44304. }
  44305. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44306. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44307. return this;
  44308. };
  44309. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44310. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44311. return this;
  44312. };
  44313. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44314. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44315. return this;
  44316. };
  44317. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44318. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44319. return this;
  44320. };
  44321. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44322. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44323. return this;
  44324. };
  44325. return ArcRotateCameraInputsManager;
  44326. }(BABYLON.CameraInputsManager));
  44327. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44328. })(BABYLON || (BABYLON = {}));
  44329. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44330. var BABYLON;
  44331. (function (BABYLON) {
  44332. var ArcRotateCamera = /** @class */ (function (_super) {
  44333. __extends(ArcRotateCamera, _super);
  44334. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44335. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44336. _this.inertialAlphaOffset = 0;
  44337. _this.inertialBetaOffset = 0;
  44338. _this.inertialRadiusOffset = 0;
  44339. _this.lowerAlphaLimit = null;
  44340. _this.upperAlphaLimit = null;
  44341. _this.lowerBetaLimit = 0.01;
  44342. _this.upperBetaLimit = Math.PI;
  44343. _this.lowerRadiusLimit = null;
  44344. _this.upperRadiusLimit = null;
  44345. _this.inertialPanningX = 0;
  44346. _this.inertialPanningY = 0;
  44347. _this.pinchToPanMaxDistance = 20;
  44348. _this.panningDistanceLimit = null;
  44349. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44350. _this.panningInertia = 0.9;
  44351. //-- end properties for backward compatibility for inputs
  44352. _this.zoomOnFactor = 1;
  44353. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44354. _this.allowUpsideDown = true;
  44355. _this._viewMatrix = new BABYLON.Matrix();
  44356. // Panning
  44357. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44358. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44359. _this.checkCollisions = false;
  44360. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44361. _this._previousPosition = BABYLON.Vector3.Zero();
  44362. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44363. _this._newPosition = BABYLON.Vector3.Zero();
  44364. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44365. if (collidedMesh === void 0) { collidedMesh = null; }
  44366. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44367. newPosition.multiplyInPlace(_this._collider._radius);
  44368. }
  44369. if (!collidedMesh) {
  44370. _this._previousPosition.copyFrom(_this.position);
  44371. }
  44372. else {
  44373. _this.setPosition(newPosition);
  44374. if (_this.onCollide) {
  44375. _this.onCollide(collidedMesh);
  44376. }
  44377. }
  44378. // Recompute because of constraints
  44379. var cosa = Math.cos(_this.alpha);
  44380. var sina = Math.sin(_this.alpha);
  44381. var cosb = Math.cos(_this.beta);
  44382. var sinb = Math.sin(_this.beta);
  44383. if (sinb === 0) {
  44384. sinb = 0.0001;
  44385. }
  44386. var target = _this._getTargetPosition();
  44387. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44388. _this.position.copyFrom(_this._newPosition);
  44389. var up = _this.upVector;
  44390. if (_this.allowUpsideDown && _this.beta < 0) {
  44391. up = up.clone();
  44392. up = up.negate();
  44393. }
  44394. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44395. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44396. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44397. _this._collisionTriggered = false;
  44398. };
  44399. _this._target = BABYLON.Vector3.Zero();
  44400. if (target) {
  44401. _this.setTarget(target);
  44402. }
  44403. _this.alpha = alpha;
  44404. _this.beta = beta;
  44405. _this.radius = radius;
  44406. _this.getViewMatrix();
  44407. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44408. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44409. return _this;
  44410. }
  44411. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44412. get: function () {
  44413. return this._target;
  44414. },
  44415. set: function (value) {
  44416. this.setTarget(value);
  44417. },
  44418. enumerable: true,
  44419. configurable: true
  44420. });
  44421. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44422. //-- begin properties for backward compatibility for inputs
  44423. get: function () {
  44424. var pointers = this.inputs.attached["pointers"];
  44425. if (pointers)
  44426. return pointers.angularSensibilityX;
  44427. return 0;
  44428. },
  44429. set: function (value) {
  44430. var pointers = this.inputs.attached["pointers"];
  44431. if (pointers) {
  44432. pointers.angularSensibilityX = value;
  44433. }
  44434. },
  44435. enumerable: true,
  44436. configurable: true
  44437. });
  44438. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44439. get: function () {
  44440. var pointers = this.inputs.attached["pointers"];
  44441. if (pointers)
  44442. return pointers.angularSensibilityY;
  44443. return 0;
  44444. },
  44445. set: function (value) {
  44446. var pointers = this.inputs.attached["pointers"];
  44447. if (pointers) {
  44448. pointers.angularSensibilityY = value;
  44449. }
  44450. },
  44451. enumerable: true,
  44452. configurable: true
  44453. });
  44454. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44455. get: function () {
  44456. var pointers = this.inputs.attached["pointers"];
  44457. if (pointers)
  44458. return pointers.pinchPrecision;
  44459. return 0;
  44460. },
  44461. set: function (value) {
  44462. var pointers = this.inputs.attached["pointers"];
  44463. if (pointers) {
  44464. pointers.pinchPrecision = value;
  44465. }
  44466. },
  44467. enumerable: true,
  44468. configurable: true
  44469. });
  44470. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44471. get: function () {
  44472. var pointers = this.inputs.attached["pointers"];
  44473. if (pointers)
  44474. return pointers.pinchDeltaPercentage;
  44475. return 0;
  44476. },
  44477. set: function (value) {
  44478. var pointers = this.inputs.attached["pointers"];
  44479. if (pointers) {
  44480. pointers.pinchDeltaPercentage = value;
  44481. }
  44482. },
  44483. enumerable: true,
  44484. configurable: true
  44485. });
  44486. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44487. get: function () {
  44488. var pointers = this.inputs.attached["pointers"];
  44489. if (pointers)
  44490. return pointers.panningSensibility;
  44491. return 0;
  44492. },
  44493. set: function (value) {
  44494. var pointers = this.inputs.attached["pointers"];
  44495. if (pointers) {
  44496. pointers.panningSensibility = value;
  44497. }
  44498. },
  44499. enumerable: true,
  44500. configurable: true
  44501. });
  44502. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44503. get: function () {
  44504. var keyboard = this.inputs.attached["keyboard"];
  44505. if (keyboard)
  44506. return keyboard.keysUp;
  44507. return [];
  44508. },
  44509. set: function (value) {
  44510. var keyboard = this.inputs.attached["keyboard"];
  44511. if (keyboard)
  44512. keyboard.keysUp = value;
  44513. },
  44514. enumerable: true,
  44515. configurable: true
  44516. });
  44517. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44518. get: function () {
  44519. var keyboard = this.inputs.attached["keyboard"];
  44520. if (keyboard)
  44521. return keyboard.keysDown;
  44522. return [];
  44523. },
  44524. set: function (value) {
  44525. var keyboard = this.inputs.attached["keyboard"];
  44526. if (keyboard)
  44527. keyboard.keysDown = value;
  44528. },
  44529. enumerable: true,
  44530. configurable: true
  44531. });
  44532. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44533. get: function () {
  44534. var keyboard = this.inputs.attached["keyboard"];
  44535. if (keyboard)
  44536. return keyboard.keysLeft;
  44537. return [];
  44538. },
  44539. set: function (value) {
  44540. var keyboard = this.inputs.attached["keyboard"];
  44541. if (keyboard)
  44542. keyboard.keysLeft = value;
  44543. },
  44544. enumerable: true,
  44545. configurable: true
  44546. });
  44547. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44548. get: function () {
  44549. var keyboard = this.inputs.attached["keyboard"];
  44550. if (keyboard)
  44551. return keyboard.keysRight;
  44552. return [];
  44553. },
  44554. set: function (value) {
  44555. var keyboard = this.inputs.attached["keyboard"];
  44556. if (keyboard)
  44557. keyboard.keysRight = value;
  44558. },
  44559. enumerable: true,
  44560. configurable: true
  44561. });
  44562. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44563. get: function () {
  44564. var mousewheel = this.inputs.attached["mousewheel"];
  44565. if (mousewheel)
  44566. return mousewheel.wheelPrecision;
  44567. return 0;
  44568. },
  44569. set: function (value) {
  44570. var mousewheel = this.inputs.attached["mousewheel"];
  44571. if (mousewheel)
  44572. mousewheel.wheelPrecision = value;
  44573. },
  44574. enumerable: true,
  44575. configurable: true
  44576. });
  44577. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44578. get: function () {
  44579. var mousewheel = this.inputs.attached["mousewheel"];
  44580. if (mousewheel)
  44581. return mousewheel.wheelDeltaPercentage;
  44582. return 0;
  44583. },
  44584. set: function (value) {
  44585. var mousewheel = this.inputs.attached["mousewheel"];
  44586. if (mousewheel)
  44587. mousewheel.wheelDeltaPercentage = value;
  44588. },
  44589. enumerable: true,
  44590. configurable: true
  44591. });
  44592. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44593. get: function () {
  44594. return this._bouncingBehavior;
  44595. },
  44596. enumerable: true,
  44597. configurable: true
  44598. });
  44599. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44600. get: function () {
  44601. return this._bouncingBehavior != null;
  44602. },
  44603. set: function (value) {
  44604. if (value === this.useBouncingBehavior) {
  44605. return;
  44606. }
  44607. if (value) {
  44608. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44609. this.addBehavior(this._bouncingBehavior);
  44610. }
  44611. else if (this._bouncingBehavior) {
  44612. this.removeBehavior(this._bouncingBehavior);
  44613. this._bouncingBehavior = null;
  44614. }
  44615. },
  44616. enumerable: true,
  44617. configurable: true
  44618. });
  44619. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44620. get: function () {
  44621. return this._framingBehavior;
  44622. },
  44623. enumerable: true,
  44624. configurable: true
  44625. });
  44626. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44627. get: function () {
  44628. return this._framingBehavior != null;
  44629. },
  44630. set: function (value) {
  44631. if (value === this.useFramingBehavior) {
  44632. return;
  44633. }
  44634. if (value) {
  44635. this._framingBehavior = new BABYLON.FramingBehavior();
  44636. this.addBehavior(this._framingBehavior);
  44637. }
  44638. else if (this._framingBehavior) {
  44639. this.removeBehavior(this._framingBehavior);
  44640. this._framingBehavior = null;
  44641. }
  44642. },
  44643. enumerable: true,
  44644. configurable: true
  44645. });
  44646. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44647. get: function () {
  44648. return this._autoRotationBehavior;
  44649. },
  44650. enumerable: true,
  44651. configurable: true
  44652. });
  44653. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44654. get: function () {
  44655. return this._autoRotationBehavior != null;
  44656. },
  44657. set: function (value) {
  44658. if (value === this.useAutoRotationBehavior) {
  44659. return;
  44660. }
  44661. if (value) {
  44662. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44663. this.addBehavior(this._autoRotationBehavior);
  44664. }
  44665. else if (this._autoRotationBehavior) {
  44666. this.removeBehavior(this._autoRotationBehavior);
  44667. this._autoRotationBehavior = null;
  44668. }
  44669. },
  44670. enumerable: true,
  44671. configurable: true
  44672. });
  44673. // Cache
  44674. ArcRotateCamera.prototype._initCache = function () {
  44675. _super.prototype._initCache.call(this);
  44676. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44677. this._cache.alpha = undefined;
  44678. this._cache.beta = undefined;
  44679. this._cache.radius = undefined;
  44680. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44681. };
  44682. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44683. if (!ignoreParentClass) {
  44684. _super.prototype._updateCache.call(this);
  44685. }
  44686. this._cache._target.copyFrom(this._getTargetPosition());
  44687. this._cache.alpha = this.alpha;
  44688. this._cache.beta = this.beta;
  44689. this._cache.radius = this.radius;
  44690. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44691. };
  44692. ArcRotateCamera.prototype._getTargetPosition = function () {
  44693. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44694. var pos = this._targetHost.getAbsolutePosition();
  44695. if (this._targetBoundingCenter) {
  44696. pos.addToRef(this._targetBoundingCenter, this._target);
  44697. }
  44698. else {
  44699. this._target.copyFrom(pos);
  44700. }
  44701. }
  44702. var lockedTargetPosition = this._getLockedTargetPosition();
  44703. if (lockedTargetPosition) {
  44704. return lockedTargetPosition;
  44705. }
  44706. return this._target;
  44707. };
  44708. ArcRotateCamera.prototype.storeState = function () {
  44709. this._storedAlpha = this.alpha;
  44710. this._storedBeta = this.beta;
  44711. this._storedRadius = this.radius;
  44712. this._storedTarget = this._getTargetPosition().clone();
  44713. return _super.prototype.storeState.call(this);
  44714. };
  44715. /**
  44716. * Restored camera state. You must call storeState() first
  44717. */
  44718. ArcRotateCamera.prototype._restoreStateValues = function () {
  44719. if (!_super.prototype._restoreStateValues.call(this)) {
  44720. return false;
  44721. }
  44722. this.alpha = this._storedAlpha;
  44723. this.beta = this._storedBeta;
  44724. this.radius = this._storedRadius;
  44725. this.setTarget(this._storedTarget.clone());
  44726. this.inertialAlphaOffset = 0;
  44727. this.inertialBetaOffset = 0;
  44728. this.inertialRadiusOffset = 0;
  44729. this.inertialPanningX = 0;
  44730. this.inertialPanningY = 0;
  44731. return true;
  44732. };
  44733. // Synchronized
  44734. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44735. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44736. return false;
  44737. return this._cache._target.equals(this._getTargetPosition())
  44738. && this._cache.alpha === this.alpha
  44739. && this._cache.beta === this.beta
  44740. && this._cache.radius === this.radius
  44741. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44742. };
  44743. // Methods
  44744. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44745. var _this = this;
  44746. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44747. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44748. this._useCtrlForPanning = useCtrlForPanning;
  44749. this._panningMouseButton = panningMouseButton;
  44750. this.inputs.attachElement(element, noPreventDefault);
  44751. this._reset = function () {
  44752. _this.inertialAlphaOffset = 0;
  44753. _this.inertialBetaOffset = 0;
  44754. _this.inertialRadiusOffset = 0;
  44755. _this.inertialPanningX = 0;
  44756. _this.inertialPanningY = 0;
  44757. };
  44758. };
  44759. ArcRotateCamera.prototype.detachControl = function (element) {
  44760. this.inputs.detachElement(element);
  44761. if (this._reset) {
  44762. this._reset();
  44763. }
  44764. };
  44765. ArcRotateCamera.prototype._checkInputs = function () {
  44766. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44767. if (this._collisionTriggered) {
  44768. return;
  44769. }
  44770. this.inputs.checkInputs();
  44771. // Inertia
  44772. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44773. if (this.getScene().useRightHandedSystem) {
  44774. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44775. }
  44776. else {
  44777. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44778. }
  44779. this.beta += this.inertialBetaOffset;
  44780. this.radius -= this.inertialRadiusOffset;
  44781. this.inertialAlphaOffset *= this.inertia;
  44782. this.inertialBetaOffset *= this.inertia;
  44783. this.inertialRadiusOffset *= this.inertia;
  44784. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44785. this.inertialAlphaOffset = 0;
  44786. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44787. this.inertialBetaOffset = 0;
  44788. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44789. this.inertialRadiusOffset = 0;
  44790. }
  44791. // Panning inertia
  44792. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44793. if (!this._localDirection) {
  44794. this._localDirection = BABYLON.Vector3.Zero();
  44795. this._transformedDirection = BABYLON.Vector3.Zero();
  44796. }
  44797. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44798. this._localDirection.multiplyInPlace(this.panningAxis);
  44799. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44800. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44801. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44802. if (!this.panningAxis.y) {
  44803. this._transformedDirection.y = 0;
  44804. }
  44805. if (!this._targetHost) {
  44806. if (this.panningDistanceLimit) {
  44807. this._transformedDirection.addInPlace(this._target);
  44808. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44809. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44810. this._target.copyFrom(this._transformedDirection);
  44811. }
  44812. }
  44813. else {
  44814. this._target.addInPlace(this._transformedDirection);
  44815. }
  44816. }
  44817. this.inertialPanningX *= this.panningInertia;
  44818. this.inertialPanningY *= this.panningInertia;
  44819. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44820. this.inertialPanningX = 0;
  44821. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44822. this.inertialPanningY = 0;
  44823. }
  44824. // Limits
  44825. this._checkLimits();
  44826. _super.prototype._checkInputs.call(this);
  44827. };
  44828. ArcRotateCamera.prototype._checkLimits = function () {
  44829. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44830. if (this.allowUpsideDown && this.beta > Math.PI) {
  44831. this.beta = this.beta - (2 * Math.PI);
  44832. }
  44833. }
  44834. else {
  44835. if (this.beta < this.lowerBetaLimit) {
  44836. this.beta = this.lowerBetaLimit;
  44837. }
  44838. }
  44839. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44840. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44841. this.beta = this.beta + (2 * Math.PI);
  44842. }
  44843. }
  44844. else {
  44845. if (this.beta > this.upperBetaLimit) {
  44846. this.beta = this.upperBetaLimit;
  44847. }
  44848. }
  44849. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44850. this.alpha = this.lowerAlphaLimit;
  44851. }
  44852. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44853. this.alpha = this.upperAlphaLimit;
  44854. }
  44855. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44856. this.radius = this.lowerRadiusLimit;
  44857. }
  44858. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44859. this.radius = this.upperRadiusLimit;
  44860. }
  44861. };
  44862. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44863. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44864. this.radius = radiusv3.length();
  44865. if (this.radius === 0) {
  44866. this.radius = 0.0001; // Just to avoid division by zero
  44867. }
  44868. // Alpha
  44869. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44870. if (radiusv3.z < 0) {
  44871. this.alpha = 2 * Math.PI - this.alpha;
  44872. }
  44873. // Beta
  44874. this.beta = Math.acos(radiusv3.y / this.radius);
  44875. this._checkLimits();
  44876. };
  44877. ArcRotateCamera.prototype.setPosition = function (position) {
  44878. if (this.position.equals(position)) {
  44879. return;
  44880. }
  44881. this.position.copyFrom(position);
  44882. this.rebuildAnglesAndRadius();
  44883. };
  44884. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44885. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44886. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44887. if (target.getBoundingInfo) {
  44888. if (toBoundingCenter) {
  44889. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44890. }
  44891. else {
  44892. this._targetBoundingCenter = null;
  44893. }
  44894. this._targetHost = target;
  44895. this._target = this._getTargetPosition();
  44896. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44897. }
  44898. else {
  44899. var newTarget = target;
  44900. var currentTarget = this._getTargetPosition();
  44901. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44902. return;
  44903. }
  44904. this._targetHost = null;
  44905. this._target = newTarget;
  44906. this._targetBoundingCenter = null;
  44907. this.onMeshTargetChangedObservable.notifyObservers(null);
  44908. }
  44909. this.rebuildAnglesAndRadius();
  44910. };
  44911. ArcRotateCamera.prototype._getViewMatrix = function () {
  44912. // Compute
  44913. var cosa = Math.cos(this.alpha);
  44914. var sina = Math.sin(this.alpha);
  44915. var cosb = Math.cos(this.beta);
  44916. var sinb = Math.sin(this.beta);
  44917. if (sinb === 0) {
  44918. sinb = 0.0001;
  44919. }
  44920. var target = this._getTargetPosition();
  44921. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44922. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44923. if (!this._collider) {
  44924. this._collider = new BABYLON.Collider();
  44925. }
  44926. this._collider._radius = this.collisionRadius;
  44927. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44928. this._collisionTriggered = true;
  44929. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44930. }
  44931. else {
  44932. this.position.copyFrom(this._newPosition);
  44933. var up = this.upVector;
  44934. if (this.allowUpsideDown && sinb < 0) {
  44935. up = up.clone();
  44936. up = up.negate();
  44937. }
  44938. if (this.getScene().useRightHandedSystem) {
  44939. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44940. }
  44941. else {
  44942. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44943. }
  44944. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44945. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44946. }
  44947. this._currentTarget = target;
  44948. return this._viewMatrix;
  44949. };
  44950. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44951. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44952. meshes = meshes || this.getScene().meshes;
  44953. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44954. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44955. this.radius = distance * this.zoomOnFactor;
  44956. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44957. };
  44958. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44959. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44960. var meshesOrMinMaxVector;
  44961. var distance;
  44962. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44963. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44964. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44965. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44966. }
  44967. else {
  44968. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44969. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44970. distance = minMaxVectorAndDistance.distance;
  44971. }
  44972. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44973. if (!doNotUpdateMaxZ) {
  44974. this.maxZ = distance * 2;
  44975. }
  44976. };
  44977. /**
  44978. * @override
  44979. * Override Camera.createRigCamera
  44980. */
  44981. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44982. var alphaShift = 0;
  44983. switch (this.cameraRigMode) {
  44984. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44985. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44986. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44987. case BABYLON.Camera.RIG_MODE_VR:
  44988. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44989. break;
  44990. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44991. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44992. break;
  44993. }
  44994. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44995. rigCam._cameraRigParams = {};
  44996. return rigCam;
  44997. };
  44998. /**
  44999. * @override
  45000. * Override Camera._updateRigCameras
  45001. */
  45002. ArcRotateCamera.prototype._updateRigCameras = function () {
  45003. var camLeft = this._rigCameras[0];
  45004. var camRight = this._rigCameras[1];
  45005. camLeft.beta = camRight.beta = this.beta;
  45006. camLeft.radius = camRight.radius = this.radius;
  45007. switch (this.cameraRigMode) {
  45008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45011. case BABYLON.Camera.RIG_MODE_VR:
  45012. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45013. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45014. break;
  45015. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45016. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45017. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45018. break;
  45019. }
  45020. _super.prototype._updateRigCameras.call(this);
  45021. };
  45022. ArcRotateCamera.prototype.dispose = function () {
  45023. this.inputs.clear();
  45024. _super.prototype.dispose.call(this);
  45025. };
  45026. ArcRotateCamera.prototype.getClassName = function () {
  45027. return "ArcRotateCamera";
  45028. };
  45029. __decorate([
  45030. BABYLON.serialize()
  45031. ], ArcRotateCamera.prototype, "alpha", void 0);
  45032. __decorate([
  45033. BABYLON.serialize()
  45034. ], ArcRotateCamera.prototype, "beta", void 0);
  45035. __decorate([
  45036. BABYLON.serialize()
  45037. ], ArcRotateCamera.prototype, "radius", void 0);
  45038. __decorate([
  45039. BABYLON.serializeAsVector3("target")
  45040. ], ArcRotateCamera.prototype, "_target", void 0);
  45041. __decorate([
  45042. BABYLON.serialize()
  45043. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45044. __decorate([
  45045. BABYLON.serialize()
  45046. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45047. __decorate([
  45048. BABYLON.serialize()
  45049. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45050. __decorate([
  45051. BABYLON.serialize()
  45052. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45053. __decorate([
  45054. BABYLON.serialize()
  45055. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45056. __decorate([
  45057. BABYLON.serialize()
  45058. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45059. __decorate([
  45060. BABYLON.serialize()
  45061. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45062. __decorate([
  45063. BABYLON.serialize()
  45064. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45065. __decorate([
  45066. BABYLON.serialize()
  45067. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45068. __decorate([
  45069. BABYLON.serialize()
  45070. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45071. __decorate([
  45072. BABYLON.serialize()
  45073. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45074. __decorate([
  45075. BABYLON.serialize()
  45076. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45077. __decorate([
  45078. BABYLON.serialize()
  45079. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45080. __decorate([
  45081. BABYLON.serializeAsVector3()
  45082. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45083. __decorate([
  45084. BABYLON.serialize()
  45085. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45086. __decorate([
  45087. BABYLON.serialize()
  45088. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45089. __decorate([
  45090. BABYLON.serialize()
  45091. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45092. return ArcRotateCamera;
  45093. }(BABYLON.TargetCamera));
  45094. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45095. })(BABYLON || (BABYLON = {}));
  45096. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45097. var BABYLON;
  45098. (function (BABYLON) {
  45099. /**
  45100. * The HemisphericLight simulates the ambient environment light,
  45101. * so the passed direction is the light reflection direction, not the incoming direction.
  45102. */
  45103. var HemisphericLight = /** @class */ (function (_super) {
  45104. __extends(HemisphericLight, _super);
  45105. /**
  45106. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45107. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45108. * The HemisphericLight can't cast shadows.
  45109. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45110. * @param name The friendly name of the light
  45111. * @param direction The direction of the light reflection
  45112. * @param scene The scene the light belongs to
  45113. */
  45114. function HemisphericLight(name, direction, scene) {
  45115. var _this = _super.call(this, name, scene) || this;
  45116. /**
  45117. * The groundColor is the light in the opposite direction to the one specified during creation.
  45118. * 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.
  45119. */
  45120. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45121. _this.direction = direction || BABYLON.Vector3.Up();
  45122. return _this;
  45123. }
  45124. HemisphericLight.prototype._buildUniformLayout = function () {
  45125. this._uniformBuffer.addUniform("vLightData", 4);
  45126. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45127. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45128. this._uniformBuffer.addUniform("vLightGround", 3);
  45129. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45130. this._uniformBuffer.addUniform("depthValues", 2);
  45131. this._uniformBuffer.create();
  45132. };
  45133. /**
  45134. * Returns the string "HemisphericLight".
  45135. * @return The class name
  45136. */
  45137. HemisphericLight.prototype.getClassName = function () {
  45138. return "HemisphericLight";
  45139. };
  45140. /**
  45141. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45142. * Returns the updated direction.
  45143. * @param target The target the direction should point to
  45144. * @return The computed direction
  45145. */
  45146. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45147. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45148. return this.direction;
  45149. };
  45150. /**
  45151. * Returns the shadow generator associated to the light.
  45152. * @returns Always null for hemispheric lights because it does not support shadows.
  45153. */
  45154. HemisphericLight.prototype.getShadowGenerator = function () {
  45155. return null;
  45156. };
  45157. /**
  45158. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45159. * @param effect The effect to update
  45160. * @param lightIndex The index of the light in the effect to update
  45161. * @returns The hemispheric light
  45162. */
  45163. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45164. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45165. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45166. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45167. return this;
  45168. };
  45169. /**
  45170. * @ignore internal use only.
  45171. */
  45172. HemisphericLight.prototype._getWorldMatrix = function () {
  45173. if (!this._worldMatrix) {
  45174. this._worldMatrix = BABYLON.Matrix.Identity();
  45175. }
  45176. return this._worldMatrix;
  45177. };
  45178. /**
  45179. * Returns the integer 3.
  45180. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45181. */
  45182. HemisphericLight.prototype.getTypeID = function () {
  45183. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45184. };
  45185. __decorate([
  45186. BABYLON.serializeAsColor3()
  45187. ], HemisphericLight.prototype, "groundColor", void 0);
  45188. __decorate([
  45189. BABYLON.serializeAsVector3()
  45190. ], HemisphericLight.prototype, "direction", void 0);
  45191. return HemisphericLight;
  45192. }(BABYLON.Light));
  45193. BABYLON.HemisphericLight = HemisphericLight;
  45194. })(BABYLON || (BABYLON = {}));
  45195. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45196. var BABYLON;
  45197. (function (BABYLON) {
  45198. /**
  45199. * Base implementation of @see IShadowLight
  45200. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45201. */
  45202. var ShadowLight = /** @class */ (function (_super) {
  45203. __extends(ShadowLight, _super);
  45204. function ShadowLight() {
  45205. var _this = _super !== null && _super.apply(this, arguments) || this;
  45206. _this._needProjectionMatrixCompute = true;
  45207. return _this;
  45208. }
  45209. ShadowLight.prototype._setPosition = function (value) {
  45210. this._position = value;
  45211. };
  45212. Object.defineProperty(ShadowLight.prototype, "position", {
  45213. /**
  45214. * Sets the position the shadow will be casted from. Also use as the light position for both
  45215. * point and spot lights.
  45216. */
  45217. get: function () {
  45218. return this._position;
  45219. },
  45220. /**
  45221. * Sets the position the shadow will be casted from. Also use as the light position for both
  45222. * point and spot lights.
  45223. */
  45224. set: function (value) {
  45225. this._setPosition(value);
  45226. },
  45227. enumerable: true,
  45228. configurable: true
  45229. });
  45230. ShadowLight.prototype._setDirection = function (value) {
  45231. this._direction = value;
  45232. };
  45233. Object.defineProperty(ShadowLight.prototype, "direction", {
  45234. /**
  45235. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45236. * Also use as the light direction on spot and directional lights.
  45237. */
  45238. get: function () {
  45239. return this._direction;
  45240. },
  45241. /**
  45242. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45243. * Also use as the light direction on spot and directional lights.
  45244. */
  45245. set: function (value) {
  45246. this._setDirection(value);
  45247. },
  45248. enumerable: true,
  45249. configurable: true
  45250. });
  45251. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45252. /**
  45253. * Gets the shadow projection clipping minimum z value.
  45254. */
  45255. get: function () {
  45256. return this._shadowMinZ;
  45257. },
  45258. /**
  45259. * Sets the shadow projection clipping minimum z value.
  45260. */
  45261. set: function (value) {
  45262. this._shadowMinZ = value;
  45263. this.forceProjectionMatrixCompute();
  45264. },
  45265. enumerable: true,
  45266. configurable: true
  45267. });
  45268. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45269. /**
  45270. * Sets the shadow projection clipping maximum z value.
  45271. */
  45272. get: function () {
  45273. return this._shadowMaxZ;
  45274. },
  45275. /**
  45276. * Gets the shadow projection clipping maximum z value.
  45277. */
  45278. set: function (value) {
  45279. this._shadowMaxZ = value;
  45280. this.forceProjectionMatrixCompute();
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. /**
  45286. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45287. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45288. */
  45289. ShadowLight.prototype.computeTransformedInformation = function () {
  45290. if (this.parent && this.parent.getWorldMatrix) {
  45291. if (!this.transformedPosition) {
  45292. this.transformedPosition = BABYLON.Vector3.Zero();
  45293. }
  45294. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45295. // In case the direction is present.
  45296. if (this.direction) {
  45297. if (!this.transformedDirection) {
  45298. this.transformedDirection = BABYLON.Vector3.Zero();
  45299. }
  45300. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45301. }
  45302. return true;
  45303. }
  45304. return false;
  45305. };
  45306. /**
  45307. * Return the depth scale used for the shadow map.
  45308. * @returns the depth scale.
  45309. */
  45310. ShadowLight.prototype.getDepthScale = function () {
  45311. return 50.0;
  45312. };
  45313. /**
  45314. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45315. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45316. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45317. */
  45318. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45319. return this.transformedDirection ? this.transformedDirection : this.direction;
  45320. };
  45321. /**
  45322. * Returns the ShadowLight absolute position in the World.
  45323. * @returns the position vector in world space
  45324. */
  45325. ShadowLight.prototype.getAbsolutePosition = function () {
  45326. return this.transformedPosition ? this.transformedPosition : this.position;
  45327. };
  45328. /**
  45329. * Sets the ShadowLight direction toward the passed target.
  45330. * @param target The point tot target in local space
  45331. * @returns the updated ShadowLight direction
  45332. */
  45333. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45334. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45335. return this.direction;
  45336. };
  45337. /**
  45338. * Returns the light rotation in euler definition.
  45339. * @returns the x y z rotation in local space.
  45340. */
  45341. ShadowLight.prototype.getRotation = function () {
  45342. this.direction.normalize();
  45343. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45344. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45345. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45346. };
  45347. /**
  45348. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45349. * @returns true if a cube texture needs to be use
  45350. */
  45351. ShadowLight.prototype.needCube = function () {
  45352. return false;
  45353. };
  45354. /**
  45355. * Detects if the projection matrix requires to be recomputed this frame.
  45356. * @returns true if it requires to be recomputed otherwise, false.
  45357. */
  45358. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45359. return this._needProjectionMatrixCompute;
  45360. };
  45361. /**
  45362. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45363. */
  45364. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45365. this._needProjectionMatrixCompute = true;
  45366. };
  45367. /**
  45368. * Get the world matrix of the sahdow lights.
  45369. * @ignore Internal Use Only
  45370. */
  45371. ShadowLight.prototype._getWorldMatrix = function () {
  45372. if (!this._worldMatrix) {
  45373. this._worldMatrix = BABYLON.Matrix.Identity();
  45374. }
  45375. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45376. return this._worldMatrix;
  45377. };
  45378. /**
  45379. * Gets the minZ used for shadow according to both the scene and the light.
  45380. * @param activeCamera The camera we are returning the min for
  45381. * @returns the depth min z
  45382. */
  45383. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45384. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45385. };
  45386. /**
  45387. * Gets the maxZ used for shadow according to both the scene and the light.
  45388. * @param activeCamera The camera we are returning the max for
  45389. * @returns the depth max z
  45390. */
  45391. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45392. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45393. };
  45394. /**
  45395. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45396. * @param matrix The materix to updated with the projection information
  45397. * @param viewMatrix The transform matrix of the light
  45398. * @param renderList The list of mesh to render in the map
  45399. * @returns The current light
  45400. */
  45401. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45402. if (this.customProjectionMatrixBuilder) {
  45403. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45404. }
  45405. else {
  45406. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45407. }
  45408. return this;
  45409. };
  45410. __decorate([
  45411. BABYLON.serializeAsVector3()
  45412. ], ShadowLight.prototype, "position", null);
  45413. __decorate([
  45414. BABYLON.serializeAsVector3()
  45415. ], ShadowLight.prototype, "direction", null);
  45416. __decorate([
  45417. BABYLON.serialize()
  45418. ], ShadowLight.prototype, "shadowMinZ", null);
  45419. __decorate([
  45420. BABYLON.serialize()
  45421. ], ShadowLight.prototype, "shadowMaxZ", null);
  45422. return ShadowLight;
  45423. }(BABYLON.Light));
  45424. BABYLON.ShadowLight = ShadowLight;
  45425. })(BABYLON || (BABYLON = {}));
  45426. //# sourceMappingURL=babylon.shadowLight.js.map
  45427. var BABYLON;
  45428. (function (BABYLON) {
  45429. /**
  45430. * A point light is a light defined by an unique point in world space.
  45431. * The light is emitted in every direction from this point.
  45432. * A good example of a point light is a standard light bulb.
  45433. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45434. */
  45435. var PointLight = /** @class */ (function (_super) {
  45436. __extends(PointLight, _super);
  45437. /**
  45438. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45439. * A PointLight emits the light in every direction.
  45440. * It can cast shadows.
  45441. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45442. * ```javascript
  45443. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45444. * ```
  45445. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45446. * @param name The light friendly name
  45447. * @param position The position of the point light in the scene
  45448. * @param scene The scene the lights belongs to
  45449. */
  45450. function PointLight(name, position, scene) {
  45451. var _this = _super.call(this, name, scene) || this;
  45452. _this._shadowAngle = Math.PI / 2;
  45453. _this.position = position;
  45454. return _this;
  45455. }
  45456. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45457. /**
  45458. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45459. * This specifies what angle the shadow will use to be created.
  45460. *
  45461. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45462. */
  45463. get: function () {
  45464. return this._shadowAngle;
  45465. },
  45466. /**
  45467. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45468. * This specifies what angle the shadow will use to be created.
  45469. *
  45470. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45471. */
  45472. set: function (value) {
  45473. this._shadowAngle = value;
  45474. this.forceProjectionMatrixCompute();
  45475. },
  45476. enumerable: true,
  45477. configurable: true
  45478. });
  45479. Object.defineProperty(PointLight.prototype, "direction", {
  45480. /**
  45481. * Gets the direction if it has been set.
  45482. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45483. */
  45484. get: function () {
  45485. return this._direction;
  45486. },
  45487. /**
  45488. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45489. */
  45490. set: function (value) {
  45491. var previousNeedCube = this.needCube();
  45492. this._direction = value;
  45493. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45494. this._shadowGenerator.recreateShadowMap();
  45495. }
  45496. },
  45497. enumerable: true,
  45498. configurable: true
  45499. });
  45500. /**
  45501. * Returns the string "PointLight"
  45502. * @returns the class name
  45503. */
  45504. PointLight.prototype.getClassName = function () {
  45505. return "PointLight";
  45506. };
  45507. /**
  45508. * Returns the integer 0.
  45509. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45510. */
  45511. PointLight.prototype.getTypeID = function () {
  45512. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45513. };
  45514. /**
  45515. * Specifies wether or not the shadowmap should be a cube texture.
  45516. * @returns true if the shadowmap needs to be a cube texture.
  45517. */
  45518. PointLight.prototype.needCube = function () {
  45519. return !this.direction;
  45520. };
  45521. /**
  45522. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45523. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45524. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45525. */
  45526. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45527. if (this.direction) {
  45528. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45529. }
  45530. else {
  45531. switch (faceIndex) {
  45532. case 0:
  45533. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45534. case 1:
  45535. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45536. case 2:
  45537. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45538. case 3:
  45539. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45540. case 4:
  45541. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45542. case 5:
  45543. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45544. }
  45545. }
  45546. return BABYLON.Vector3.Zero();
  45547. };
  45548. /**
  45549. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45550. * - fov = PI / 2
  45551. * - aspect ratio : 1.0
  45552. * - z-near and far equal to the active camera minZ and maxZ.
  45553. * Returns the PointLight.
  45554. */
  45555. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45556. var activeCamera = this.getScene().activeCamera;
  45557. if (!activeCamera) {
  45558. return;
  45559. }
  45560. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45561. };
  45562. PointLight.prototype._buildUniformLayout = function () {
  45563. this._uniformBuffer.addUniform("vLightData", 4);
  45564. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45565. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45566. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45567. this._uniformBuffer.addUniform("depthValues", 2);
  45568. this._uniformBuffer.create();
  45569. };
  45570. /**
  45571. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45572. * @param effect The effect to update
  45573. * @param lightIndex The index of the light in the effect to update
  45574. * @returns The point light
  45575. */
  45576. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45577. if (this.computeTransformedInformation()) {
  45578. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45579. return this;
  45580. }
  45581. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45582. return this;
  45583. };
  45584. __decorate([
  45585. BABYLON.serialize()
  45586. ], PointLight.prototype, "shadowAngle", null);
  45587. return PointLight;
  45588. }(BABYLON.ShadowLight));
  45589. BABYLON.PointLight = PointLight;
  45590. })(BABYLON || (BABYLON = {}));
  45591. //# sourceMappingURL=babylon.pointLight.js.map
  45592. var BABYLON;
  45593. (function (BABYLON) {
  45594. /**
  45595. * A directional light is defined by a direction (what a surprise!).
  45596. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45597. * 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.
  45598. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45599. */
  45600. var DirectionalLight = /** @class */ (function (_super) {
  45601. __extends(DirectionalLight, _super);
  45602. /**
  45603. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45604. * The directional light is emitted from everywhere in the given direction.
  45605. * It can cast shawdows.
  45606. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45607. * @param name The friendly name of the light
  45608. * @param direction The direction of the light
  45609. * @param scene The scene the light belongs to
  45610. */
  45611. function DirectionalLight(name, direction, scene) {
  45612. var _this = _super.call(this, name, scene) || this;
  45613. _this._shadowFrustumSize = 0;
  45614. _this._shadowOrthoScale = 0.5;
  45615. /**
  45616. * Automatically compute the projection matrix to best fit (including all the casters)
  45617. * on each frame.
  45618. */
  45619. _this.autoUpdateExtends = true;
  45620. // Cache
  45621. _this._orthoLeft = Number.MAX_VALUE;
  45622. _this._orthoRight = Number.MIN_VALUE;
  45623. _this._orthoTop = Number.MIN_VALUE;
  45624. _this._orthoBottom = Number.MAX_VALUE;
  45625. _this.position = direction.scale(-1.0);
  45626. _this.direction = direction;
  45627. return _this;
  45628. }
  45629. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45630. /**
  45631. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45632. */
  45633. get: function () {
  45634. return this._shadowFrustumSize;
  45635. },
  45636. /**
  45637. * Specifies a fix frustum size for the shadow generation.
  45638. */
  45639. set: function (value) {
  45640. this._shadowFrustumSize = value;
  45641. this.forceProjectionMatrixCompute();
  45642. },
  45643. enumerable: true,
  45644. configurable: true
  45645. });
  45646. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45647. /**
  45648. * Gets the shadow projection scale against the optimal computed one.
  45649. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45650. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45651. */
  45652. get: function () {
  45653. return this._shadowOrthoScale;
  45654. },
  45655. /**
  45656. * Sets the shadow projection scale against the optimal computed one.
  45657. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45658. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45659. */
  45660. set: function (value) {
  45661. this._shadowOrthoScale = value;
  45662. this.forceProjectionMatrixCompute();
  45663. },
  45664. enumerable: true,
  45665. configurable: true
  45666. });
  45667. /**
  45668. * Returns the string "DirectionalLight".
  45669. * @return The class name
  45670. */
  45671. DirectionalLight.prototype.getClassName = function () {
  45672. return "DirectionalLight";
  45673. };
  45674. /**
  45675. * Returns the integer 1.
  45676. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45677. */
  45678. DirectionalLight.prototype.getTypeID = function () {
  45679. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45680. };
  45681. /**
  45682. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45683. * Returns the DirectionalLight Shadow projection matrix.
  45684. */
  45685. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45686. if (this.shadowFrustumSize > 0) {
  45687. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45688. }
  45689. else {
  45690. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45691. }
  45692. };
  45693. /**
  45694. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45695. * Returns the DirectionalLight Shadow projection matrix.
  45696. */
  45697. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45698. var activeCamera = this.getScene().activeCamera;
  45699. if (!activeCamera) {
  45700. return;
  45701. }
  45702. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45703. };
  45704. /**
  45705. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45706. * Returns the DirectionalLight Shadow projection matrix.
  45707. */
  45708. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45709. var activeCamera = this.getScene().activeCamera;
  45710. if (!activeCamera) {
  45711. return;
  45712. }
  45713. // Check extends
  45714. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45715. var tempVector3 = BABYLON.Vector3.Zero();
  45716. this._orthoLeft = Number.MAX_VALUE;
  45717. this._orthoRight = Number.MIN_VALUE;
  45718. this._orthoTop = Number.MIN_VALUE;
  45719. this._orthoBottom = Number.MAX_VALUE;
  45720. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45721. var mesh = renderList[meshIndex];
  45722. if (!mesh) {
  45723. continue;
  45724. }
  45725. var boundingInfo = mesh.getBoundingInfo();
  45726. var boundingBox = boundingInfo.boundingBox;
  45727. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45728. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45729. if (tempVector3.x < this._orthoLeft)
  45730. this._orthoLeft = tempVector3.x;
  45731. if (tempVector3.y < this._orthoBottom)
  45732. this._orthoBottom = tempVector3.y;
  45733. if (tempVector3.x > this._orthoRight)
  45734. this._orthoRight = tempVector3.x;
  45735. if (tempVector3.y > this._orthoTop)
  45736. this._orthoTop = tempVector3.y;
  45737. }
  45738. }
  45739. }
  45740. var xOffset = this._orthoRight - this._orthoLeft;
  45741. var yOffset = this._orthoTop - this._orthoBottom;
  45742. 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);
  45743. };
  45744. DirectionalLight.prototype._buildUniformLayout = function () {
  45745. this._uniformBuffer.addUniform("vLightData", 4);
  45746. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45747. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45748. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45749. this._uniformBuffer.addUniform("depthValues", 2);
  45750. this._uniformBuffer.create();
  45751. };
  45752. /**
  45753. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45754. * @param effect The effect to update
  45755. * @param lightIndex The index of the light in the effect to update
  45756. * @returns The directional light
  45757. */
  45758. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45759. if (this.computeTransformedInformation()) {
  45760. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45761. return this;
  45762. }
  45763. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45764. return this;
  45765. };
  45766. /**
  45767. * Gets the minZ used for shadow according to both the scene and the light.
  45768. *
  45769. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45770. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45771. * @param activeCamera The camera we are returning the min for
  45772. * @returns the depth min z
  45773. */
  45774. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45775. return 1;
  45776. };
  45777. /**
  45778. * Gets the maxZ used for shadow according to both the scene and the light.
  45779. *
  45780. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45781. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45782. * @param activeCamera The camera we are returning the max for
  45783. * @returns the depth max z
  45784. */
  45785. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45786. return 1;
  45787. };
  45788. __decorate([
  45789. BABYLON.serialize()
  45790. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45791. __decorate([
  45792. BABYLON.serialize()
  45793. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45794. __decorate([
  45795. BABYLON.serialize()
  45796. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45797. return DirectionalLight;
  45798. }(BABYLON.ShadowLight));
  45799. BABYLON.DirectionalLight = DirectionalLight;
  45800. })(BABYLON || (BABYLON = {}));
  45801. //# sourceMappingURL=babylon.directionalLight.js.map
  45802. var BABYLON;
  45803. (function (BABYLON) {
  45804. /**
  45805. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45806. * These values define a cone of light starting from the position, emitting toward the direction.
  45807. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45808. * and the exponent defines the speed of the decay of the light with distance (reach).
  45809. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45810. */
  45811. var SpotLight = /** @class */ (function (_super) {
  45812. __extends(SpotLight, _super);
  45813. /**
  45814. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45815. * It can cast shadows.
  45816. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45817. * @param name The light friendly name
  45818. * @param position The position of the spot light in the scene
  45819. * @param direction The direction of the light in the scene
  45820. * @param angle The cone angle of the light in Radians
  45821. * @param exponent The light decay speed with the distance from the emission spot
  45822. * @param scene The scene the lights belongs to
  45823. */
  45824. function SpotLight(name, position, direction, angle, exponent, scene) {
  45825. var _this = _super.call(this, name, scene) || this;
  45826. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45827. _this._projectionTextureLightNear = 1e-6;
  45828. _this._projectionTextureLightFar = 1000.0;
  45829. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45830. _this._projectionTextureViewLightDirty = true;
  45831. _this._projectionTextureProjectionLightDirty = true;
  45832. _this._projectionTextureDirty = true;
  45833. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45834. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45835. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45836. _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);
  45837. _this.position = position;
  45838. _this.direction = direction;
  45839. _this.angle = angle;
  45840. _this.exponent = exponent;
  45841. return _this;
  45842. }
  45843. Object.defineProperty(SpotLight.prototype, "angle", {
  45844. /**
  45845. * Gets the cone angle of the spot light in Radians.
  45846. */
  45847. get: function () {
  45848. return this._angle;
  45849. },
  45850. /**
  45851. * Sets the cone angle of the spot light in Radians.
  45852. */
  45853. set: function (value) {
  45854. this._angle = value;
  45855. this._projectionTextureProjectionLightDirty = true;
  45856. this.forceProjectionMatrixCompute();
  45857. },
  45858. enumerable: true,
  45859. configurable: true
  45860. });
  45861. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45862. /**
  45863. * Allows scaling the angle of the light for shadow generation only.
  45864. */
  45865. get: function () {
  45866. return this._shadowAngleScale;
  45867. },
  45868. /**
  45869. * Allows scaling the angle of the light for shadow generation only.
  45870. */
  45871. set: function (value) {
  45872. this._shadowAngleScale = value;
  45873. this.forceProjectionMatrixCompute();
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45879. /**
  45880. * Allows reading the projecton texture
  45881. */
  45882. get: function () {
  45883. return this._projectionTextureMatrix;
  45884. },
  45885. enumerable: true,
  45886. configurable: true
  45887. });
  45888. ;
  45889. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45890. /**
  45891. * Gets the near clip of the Spotlight for texture projection.
  45892. */
  45893. get: function () {
  45894. return this._projectionTextureLightNear;
  45895. },
  45896. /**
  45897. * Sets the near clip of the Spotlight for texture projection.
  45898. */
  45899. set: function (value) {
  45900. this._projectionTextureLightNear = value;
  45901. this._projectionTextureProjectionLightDirty = true;
  45902. },
  45903. enumerable: true,
  45904. configurable: true
  45905. });
  45906. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45907. /**
  45908. * Gets the far clip of the Spotlight for texture projection.
  45909. */
  45910. get: function () {
  45911. return this._projectionTextureLightFar;
  45912. },
  45913. /**
  45914. * Sets the far clip of the Spotlight for texture projection.
  45915. */
  45916. set: function (value) {
  45917. this._projectionTextureLightFar = value;
  45918. this._projectionTextureProjectionLightDirty = true;
  45919. },
  45920. enumerable: true,
  45921. configurable: true
  45922. });
  45923. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45924. /**
  45925. * Gets the Up vector of the Spotlight for texture projection.
  45926. */
  45927. get: function () {
  45928. return this._projectionTextureUpDirection;
  45929. },
  45930. /**
  45931. * Sets the Up vector of the Spotlight for texture projection.
  45932. */
  45933. set: function (value) {
  45934. this._projectionTextureUpDirection = value;
  45935. this._projectionTextureProjectionLightDirty = true;
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. ;
  45941. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45942. /**
  45943. * Gets the projection texture of the light.
  45944. */
  45945. get: function () {
  45946. return this._projectionTexture;
  45947. },
  45948. /**
  45949. * Sets the projection texture of the light.
  45950. */
  45951. set: function (value) {
  45952. this._projectionTexture = value;
  45953. this._projectionTextureDirty = true;
  45954. },
  45955. enumerable: true,
  45956. configurable: true
  45957. });
  45958. /**
  45959. * Returns the string "SpotLight".
  45960. * @returns the class name
  45961. */
  45962. SpotLight.prototype.getClassName = function () {
  45963. return "SpotLight";
  45964. };
  45965. /**
  45966. * Returns the integer 2.
  45967. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45968. */
  45969. SpotLight.prototype.getTypeID = function () {
  45970. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45971. };
  45972. /**
  45973. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45974. */
  45975. SpotLight.prototype._setDirection = function (value) {
  45976. _super.prototype._setDirection.call(this, value);
  45977. this._projectionTextureViewLightDirty = true;
  45978. };
  45979. /**
  45980. * Overrides the position setter to recompute the projection texture view light Matrix.
  45981. */
  45982. SpotLight.prototype._setPosition = function (value) {
  45983. _super.prototype._setPosition.call(this, value);
  45984. this._projectionTextureViewLightDirty = true;
  45985. };
  45986. /**
  45987. * 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.
  45988. * Returns the SpotLight.
  45989. */
  45990. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45991. var activeCamera = this.getScene().activeCamera;
  45992. if (!activeCamera) {
  45993. return;
  45994. }
  45995. this._shadowAngleScale = this._shadowAngleScale || 1;
  45996. var angle = this._shadowAngleScale * this._angle;
  45997. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45998. };
  45999. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46000. this._projectionTextureViewLightDirty = false;
  46001. this._projectionTextureDirty = true;
  46002. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46003. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46004. };
  46005. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46006. this._projectionTextureProjectionLightDirty = false;
  46007. this._projectionTextureDirty = true;
  46008. var light_far = this.projectionTextureLightFar;
  46009. var light_near = this.projectionTextureLightNear;
  46010. var P = light_far / (light_far - light_near);
  46011. var Q = -P * light_near;
  46012. var S = 1.0 / Math.tan(this._angle / 2.0);
  46013. var A = 1.0;
  46014. 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);
  46015. };
  46016. /**
  46017. * Main function for light texture projection matrix computing.
  46018. */
  46019. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46020. this._projectionTextureDirty = false;
  46021. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46022. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46023. };
  46024. SpotLight.prototype._buildUniformLayout = function () {
  46025. this._uniformBuffer.addUniform("vLightData", 4);
  46026. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46027. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46028. this._uniformBuffer.addUniform("vLightDirection", 3);
  46029. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46030. this._uniformBuffer.addUniform("depthValues", 2);
  46031. this._uniformBuffer.create();
  46032. };
  46033. /**
  46034. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46035. * @param effect The effect to update
  46036. * @param lightIndex The index of the light in the effect to update
  46037. * @returns The spot light
  46038. */
  46039. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46040. var normalizeDirection;
  46041. if (this.computeTransformedInformation()) {
  46042. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46043. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46044. }
  46045. else {
  46046. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46047. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46048. }
  46049. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46050. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46051. if (this._projectionTextureViewLightDirty) {
  46052. this._computeProjectionTextureViewLightMatrix();
  46053. }
  46054. if (this._projectionTextureProjectionLightDirty) {
  46055. this._computeProjectionTextureProjectionLightMatrix();
  46056. }
  46057. if (this._projectionTextureDirty) {
  46058. this._computeProjectionTextureMatrix();
  46059. }
  46060. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46061. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46062. }
  46063. return this;
  46064. };
  46065. /**
  46066. * Disposes the light and the associated resources.
  46067. */
  46068. SpotLight.prototype.dispose = function () {
  46069. _super.prototype.dispose.call(this);
  46070. if (this._projectionTexture) {
  46071. this._projectionTexture.dispose();
  46072. }
  46073. };
  46074. __decorate([
  46075. BABYLON.serialize()
  46076. ], SpotLight.prototype, "angle", null);
  46077. __decorate([
  46078. BABYLON.serialize()
  46079. ], SpotLight.prototype, "shadowAngleScale", null);
  46080. __decorate([
  46081. BABYLON.serialize()
  46082. ], SpotLight.prototype, "exponent", void 0);
  46083. __decorate([
  46084. BABYLON.serialize()
  46085. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46086. __decorate([
  46087. BABYLON.serialize()
  46088. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46089. __decorate([
  46090. BABYLON.serialize()
  46091. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46092. __decorate([
  46093. BABYLON.serializeAsTexture("projectedLightTexture")
  46094. ], SpotLight.prototype, "_projectionTexture", void 0);
  46095. return SpotLight;
  46096. }(BABYLON.ShadowLight));
  46097. BABYLON.SpotLight = SpotLight;
  46098. })(BABYLON || (BABYLON = {}));
  46099. //# sourceMappingURL=babylon.spotLight.js.map
  46100. var BABYLON;
  46101. (function (BABYLON) {
  46102. /**
  46103. * Class used to override all child animations of a given target
  46104. */
  46105. var AnimationPropertiesOverride = /** @class */ (function () {
  46106. function AnimationPropertiesOverride() {
  46107. /**
  46108. * Gets or sets a value indicating if animation blending must be used
  46109. */
  46110. this.enableBlending = false;
  46111. /**
  46112. * Gets or sets the blending speed to use when enableBlending is true
  46113. */
  46114. this.blendingSpeed = 0.01;
  46115. /**
  46116. * Gets or sets the default loop mode to use
  46117. */
  46118. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46119. }
  46120. return AnimationPropertiesOverride;
  46121. }());
  46122. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46123. })(BABYLON || (BABYLON = {}));
  46124. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46125. var BABYLON;
  46126. (function (BABYLON) {
  46127. var AnimationRange = /** @class */ (function () {
  46128. function AnimationRange(name, from, to) {
  46129. this.name = name;
  46130. this.from = from;
  46131. this.to = to;
  46132. }
  46133. AnimationRange.prototype.clone = function () {
  46134. return new AnimationRange(this.name, this.from, this.to);
  46135. };
  46136. return AnimationRange;
  46137. }());
  46138. BABYLON.AnimationRange = AnimationRange;
  46139. /**
  46140. * Composed of a frame, and an action function
  46141. */
  46142. var AnimationEvent = /** @class */ (function () {
  46143. function AnimationEvent(frame, action, onlyOnce) {
  46144. this.frame = frame;
  46145. this.action = action;
  46146. this.onlyOnce = onlyOnce;
  46147. this.isDone = false;
  46148. }
  46149. return AnimationEvent;
  46150. }());
  46151. BABYLON.AnimationEvent = AnimationEvent;
  46152. var PathCursor = /** @class */ (function () {
  46153. function PathCursor(path) {
  46154. this.path = path;
  46155. this._onchange = new Array();
  46156. this.value = 0;
  46157. this.animations = new Array();
  46158. }
  46159. PathCursor.prototype.getPoint = function () {
  46160. var point = this.path.getPointAtLengthPosition(this.value);
  46161. return new BABYLON.Vector3(point.x, 0, point.y);
  46162. };
  46163. PathCursor.prototype.moveAhead = function (step) {
  46164. if (step === void 0) { step = 0.002; }
  46165. this.move(step);
  46166. return this;
  46167. };
  46168. PathCursor.prototype.moveBack = function (step) {
  46169. if (step === void 0) { step = 0.002; }
  46170. this.move(-step);
  46171. return this;
  46172. };
  46173. PathCursor.prototype.move = function (step) {
  46174. if (Math.abs(step) > 1) {
  46175. throw "step size should be less than 1.";
  46176. }
  46177. this.value += step;
  46178. this.ensureLimits();
  46179. this.raiseOnChange();
  46180. return this;
  46181. };
  46182. PathCursor.prototype.ensureLimits = function () {
  46183. while (this.value > 1) {
  46184. this.value -= 1;
  46185. }
  46186. while (this.value < 0) {
  46187. this.value += 1;
  46188. }
  46189. return this;
  46190. };
  46191. // used by animation engine
  46192. PathCursor.prototype.raiseOnChange = function () {
  46193. var _this = this;
  46194. this._onchange.forEach(function (f) { return f(_this); });
  46195. return this;
  46196. };
  46197. PathCursor.prototype.onchange = function (f) {
  46198. this._onchange.push(f);
  46199. return this;
  46200. };
  46201. return PathCursor;
  46202. }());
  46203. BABYLON.PathCursor = PathCursor;
  46204. var AnimationKeyInterpolation;
  46205. (function (AnimationKeyInterpolation) {
  46206. /**
  46207. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46208. */
  46209. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46210. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46211. var Animation = /** @class */ (function () {
  46212. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46213. this.name = name;
  46214. this.targetProperty = targetProperty;
  46215. this.framePerSecond = framePerSecond;
  46216. this.dataType = dataType;
  46217. this.loopMode = loopMode;
  46218. this.enableBlending = enableBlending;
  46219. this._runtimeAnimations = new Array();
  46220. // The set of event that will be linked to this animation
  46221. this._events = new Array();
  46222. this.blendingSpeed = 0.01;
  46223. this._ranges = {};
  46224. this.targetPropertyPath = targetProperty.split(".");
  46225. this.dataType = dataType;
  46226. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46227. }
  46228. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46229. var dataType = undefined;
  46230. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46231. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46232. }
  46233. else if (from instanceof BABYLON.Quaternion) {
  46234. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46235. }
  46236. else if (from instanceof BABYLON.Vector3) {
  46237. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46238. }
  46239. else if (from instanceof BABYLON.Vector2) {
  46240. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46241. }
  46242. else if (from instanceof BABYLON.Color3) {
  46243. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46244. }
  46245. else if (from instanceof BABYLON.Size) {
  46246. dataType = Animation.ANIMATIONTYPE_SIZE;
  46247. }
  46248. if (dataType == undefined) {
  46249. return null;
  46250. }
  46251. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46252. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46253. animation.setKeys(keys);
  46254. if (easingFunction !== undefined) {
  46255. animation.setEasingFunction(easingFunction);
  46256. }
  46257. return animation;
  46258. };
  46259. /**
  46260. * Sets up an animation.
  46261. * @param property the property to animate
  46262. * @param animationType the animation type to apply
  46263. * @param easingFunction the easing function used in the animation
  46264. * @returns The created animation
  46265. */
  46266. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46267. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46268. animation.setEasingFunction(easingFunction);
  46269. return animation;
  46270. };
  46271. /**
  46272. * Create and start an animation on a node
  46273. * @param {string} name defines the name of the global animation that will be run on all nodes
  46274. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46275. * @param {string} targetProperty defines property to animate
  46276. * @param {number} framePerSecond defines the number of frame per second yo use
  46277. * @param {number} totalFrame defines the number of frames in total
  46278. * @param {any} from defines the initial value
  46279. * @param {any} to defines the final value
  46280. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46281. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46282. * @param onAnimationEnd defines the callback to call when animation end
  46283. * @returns the animatable created for this animation
  46284. */
  46285. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46286. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46287. if (!animation) {
  46288. return null;
  46289. }
  46290. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46291. };
  46292. /**
  46293. * Create and start an animation on a node and its descendants
  46294. * @param {string} name defines the name of the global animation that will be run on all nodes
  46295. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46296. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  46297. * @param {string} targetProperty defines property to animate
  46298. * @param {number} framePerSecond defines the number of frame per second yo use
  46299. * @param {number} totalFrame defines the number of frames in total
  46300. * @param {any} from defines the initial value
  46301. * @param {any} to defines the final value
  46302. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46303. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46304. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46305. * @returns the list of animatables created for all nodes
  46306. * @example https://www.babylonjs-playground.com/#MH0VLI
  46307. */
  46308. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46309. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46310. if (!animation) {
  46311. return null;
  46312. }
  46313. var scene = node.getScene();
  46314. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46315. };
  46316. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46317. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46318. if (!animation) {
  46319. return null;
  46320. }
  46321. node.animations.push(animation);
  46322. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46323. };
  46324. /**
  46325. * Transition property of the Camera to the target Value.
  46326. * @param property The property to transition
  46327. * @param targetValue The target Value of the property
  46328. * @param host The object where the property to animate belongs
  46329. * @param scene Scene used to run the animation
  46330. * @param frameRate Framerate (in frame/s) to use
  46331. * @param transition The transition type we want to use
  46332. * @param duration The duration of the animation, in milliseconds
  46333. * @param onAnimationEnd Call back trigger at the end of the animation.
  46334. */
  46335. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46336. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46337. if (duration <= 0) {
  46338. host[property] = targetValue;
  46339. if (onAnimationEnd) {
  46340. onAnimationEnd();
  46341. }
  46342. return null;
  46343. }
  46344. var endFrame = frameRate * (duration / 1000);
  46345. transition.setKeys([{
  46346. frame: 0,
  46347. value: host[property].clone ? host[property].clone() : host[property]
  46348. },
  46349. {
  46350. frame: endFrame,
  46351. value: targetValue
  46352. }]);
  46353. if (!host.animations) {
  46354. host.animations = [];
  46355. }
  46356. host.animations.push(transition);
  46357. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46358. animation.onAnimationEnd = onAnimationEnd;
  46359. return animation;
  46360. };
  46361. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46362. /**
  46363. * Return the array of runtime animations currently using this animation
  46364. */
  46365. get: function () {
  46366. return this._runtimeAnimations;
  46367. },
  46368. enumerable: true,
  46369. configurable: true
  46370. });
  46371. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46372. get: function () {
  46373. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46374. var runtimeAnimation = _a[_i];
  46375. if (!runtimeAnimation.isStopped) {
  46376. return true;
  46377. }
  46378. }
  46379. return false;
  46380. },
  46381. enumerable: true,
  46382. configurable: true
  46383. });
  46384. // Methods
  46385. /**
  46386. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46387. */
  46388. Animation.prototype.toString = function (fullDetails) {
  46389. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46390. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46391. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46392. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46393. if (fullDetails) {
  46394. ret += ", Ranges: {";
  46395. var first = true;
  46396. for (var name in this._ranges) {
  46397. if (first) {
  46398. ret += ", ";
  46399. first = false;
  46400. }
  46401. ret += name;
  46402. }
  46403. ret += "}";
  46404. }
  46405. return ret;
  46406. };
  46407. /**
  46408. * Add an event to this animation.
  46409. */
  46410. Animation.prototype.addEvent = function (event) {
  46411. this._events.push(event);
  46412. };
  46413. /**
  46414. * Remove all events found at the given frame
  46415. * @param frame
  46416. */
  46417. Animation.prototype.removeEvents = function (frame) {
  46418. for (var index = 0; index < this._events.length; index++) {
  46419. if (this._events[index].frame === frame) {
  46420. this._events.splice(index, 1);
  46421. index--;
  46422. }
  46423. }
  46424. };
  46425. Animation.prototype.getEvents = function () {
  46426. return this._events;
  46427. };
  46428. Animation.prototype.createRange = function (name, from, to) {
  46429. // check name not already in use; could happen for bones after serialized
  46430. if (!this._ranges[name]) {
  46431. this._ranges[name] = new AnimationRange(name, from, to);
  46432. }
  46433. };
  46434. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46435. if (deleteFrames === void 0) { deleteFrames = true; }
  46436. var range = this._ranges[name];
  46437. if (!range) {
  46438. return;
  46439. }
  46440. if (deleteFrames) {
  46441. var from = range.from;
  46442. var to = range.to;
  46443. // this loop MUST go high to low for multiple splices to work
  46444. for (var key = this._keys.length - 1; key >= 0; key--) {
  46445. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46446. this._keys.splice(key, 1);
  46447. }
  46448. }
  46449. }
  46450. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46451. };
  46452. Animation.prototype.getRange = function (name) {
  46453. return this._ranges[name];
  46454. };
  46455. Animation.prototype.getKeys = function () {
  46456. return this._keys;
  46457. };
  46458. Animation.prototype.getHighestFrame = function () {
  46459. var ret = 0;
  46460. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46461. if (ret < this._keys[key].frame) {
  46462. ret = this._keys[key].frame;
  46463. }
  46464. }
  46465. return ret;
  46466. };
  46467. Animation.prototype.getEasingFunction = function () {
  46468. return this._easingFunction;
  46469. };
  46470. Animation.prototype.setEasingFunction = function (easingFunction) {
  46471. this._easingFunction = easingFunction;
  46472. };
  46473. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46474. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46475. };
  46476. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46477. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46478. };
  46479. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46480. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46481. };
  46482. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46483. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46484. };
  46485. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46486. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46487. };
  46488. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46489. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46490. };
  46491. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46492. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46493. };
  46494. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46495. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46496. };
  46497. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46498. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46499. };
  46500. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46501. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46502. };
  46503. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46504. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46505. };
  46506. Animation.prototype.clone = function () {
  46507. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46508. clone.enableBlending = this.enableBlending;
  46509. clone.blendingSpeed = this.blendingSpeed;
  46510. if (this._keys) {
  46511. clone.setKeys(this._keys);
  46512. }
  46513. if (this._ranges) {
  46514. clone._ranges = {};
  46515. for (var name in this._ranges) {
  46516. var range = this._ranges[name];
  46517. if (!range) {
  46518. continue;
  46519. }
  46520. clone._ranges[name] = range.clone();
  46521. }
  46522. }
  46523. return clone;
  46524. };
  46525. Animation.prototype.setKeys = function (values) {
  46526. this._keys = values.slice(0);
  46527. };
  46528. Animation.prototype.serialize = function () {
  46529. var serializationObject = {};
  46530. serializationObject.name = this.name;
  46531. serializationObject.property = this.targetProperty;
  46532. serializationObject.framePerSecond = this.framePerSecond;
  46533. serializationObject.dataType = this.dataType;
  46534. serializationObject.loopBehavior = this.loopMode;
  46535. serializationObject.enableBlending = this.enableBlending;
  46536. serializationObject.blendingSpeed = this.blendingSpeed;
  46537. var dataType = this.dataType;
  46538. serializationObject.keys = [];
  46539. var keys = this.getKeys();
  46540. for (var index = 0; index < keys.length; index++) {
  46541. var animationKey = keys[index];
  46542. var key = {};
  46543. key.frame = animationKey.frame;
  46544. switch (dataType) {
  46545. case Animation.ANIMATIONTYPE_FLOAT:
  46546. key.values = [animationKey.value];
  46547. break;
  46548. case Animation.ANIMATIONTYPE_QUATERNION:
  46549. case Animation.ANIMATIONTYPE_MATRIX:
  46550. case Animation.ANIMATIONTYPE_VECTOR3:
  46551. case Animation.ANIMATIONTYPE_COLOR3:
  46552. key.values = animationKey.value.asArray();
  46553. break;
  46554. }
  46555. serializationObject.keys.push(key);
  46556. }
  46557. serializationObject.ranges = [];
  46558. for (var name in this._ranges) {
  46559. var source = this._ranges[name];
  46560. if (!source) {
  46561. continue;
  46562. }
  46563. var range = {};
  46564. range.name = name;
  46565. range.from = source.from;
  46566. range.to = source.to;
  46567. serializationObject.ranges.push(range);
  46568. }
  46569. return serializationObject;
  46570. };
  46571. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46572. get: function () {
  46573. return Animation._ANIMATIONTYPE_FLOAT;
  46574. },
  46575. enumerable: true,
  46576. configurable: true
  46577. });
  46578. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46579. get: function () {
  46580. return Animation._ANIMATIONTYPE_VECTOR3;
  46581. },
  46582. enumerable: true,
  46583. configurable: true
  46584. });
  46585. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46586. get: function () {
  46587. return Animation._ANIMATIONTYPE_VECTOR2;
  46588. },
  46589. enumerable: true,
  46590. configurable: true
  46591. });
  46592. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46593. get: function () {
  46594. return Animation._ANIMATIONTYPE_SIZE;
  46595. },
  46596. enumerable: true,
  46597. configurable: true
  46598. });
  46599. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46600. get: function () {
  46601. return Animation._ANIMATIONTYPE_QUATERNION;
  46602. },
  46603. enumerable: true,
  46604. configurable: true
  46605. });
  46606. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46607. get: function () {
  46608. return Animation._ANIMATIONTYPE_MATRIX;
  46609. },
  46610. enumerable: true,
  46611. configurable: true
  46612. });
  46613. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46614. get: function () {
  46615. return Animation._ANIMATIONTYPE_COLOR3;
  46616. },
  46617. enumerable: true,
  46618. configurable: true
  46619. });
  46620. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46621. get: function () {
  46622. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46623. },
  46624. enumerable: true,
  46625. configurable: true
  46626. });
  46627. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46628. get: function () {
  46629. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46630. },
  46631. enumerable: true,
  46632. configurable: true
  46633. });
  46634. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46635. get: function () {
  46636. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46637. },
  46638. enumerable: true,
  46639. configurable: true
  46640. });
  46641. Animation.Parse = function (parsedAnimation) {
  46642. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46643. var dataType = parsedAnimation.dataType;
  46644. var keys = [];
  46645. var data;
  46646. var index;
  46647. if (parsedAnimation.enableBlending) {
  46648. animation.enableBlending = parsedAnimation.enableBlending;
  46649. }
  46650. if (parsedAnimation.blendingSpeed) {
  46651. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46652. }
  46653. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46654. var key = parsedAnimation.keys[index];
  46655. var inTangent;
  46656. var outTangent;
  46657. switch (dataType) {
  46658. case Animation.ANIMATIONTYPE_FLOAT:
  46659. data = key.values[0];
  46660. if (key.values.length >= 1) {
  46661. inTangent = key.values[1];
  46662. }
  46663. if (key.values.length >= 2) {
  46664. outTangent = key.values[2];
  46665. }
  46666. break;
  46667. case Animation.ANIMATIONTYPE_QUATERNION:
  46668. data = BABYLON.Quaternion.FromArray(key.values);
  46669. if (key.values.length >= 8) {
  46670. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46671. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46672. inTangent = _inTangent;
  46673. }
  46674. }
  46675. if (key.values.length >= 12) {
  46676. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46677. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46678. outTangent = _outTangent;
  46679. }
  46680. }
  46681. break;
  46682. case Animation.ANIMATIONTYPE_MATRIX:
  46683. data = BABYLON.Matrix.FromArray(key.values);
  46684. break;
  46685. case Animation.ANIMATIONTYPE_COLOR3:
  46686. data = BABYLON.Color3.FromArray(key.values);
  46687. break;
  46688. case Animation.ANIMATIONTYPE_VECTOR3:
  46689. default:
  46690. data = BABYLON.Vector3.FromArray(key.values);
  46691. break;
  46692. }
  46693. var keyData = {};
  46694. keyData.frame = key.frame;
  46695. keyData.value = data;
  46696. if (inTangent != undefined) {
  46697. keyData.inTangent = inTangent;
  46698. }
  46699. if (outTangent != undefined) {
  46700. keyData.outTangent = outTangent;
  46701. }
  46702. keys.push(keyData);
  46703. }
  46704. animation.setKeys(keys);
  46705. if (parsedAnimation.ranges) {
  46706. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46707. data = parsedAnimation.ranges[index];
  46708. animation.createRange(data.name, data.from, data.to);
  46709. }
  46710. }
  46711. return animation;
  46712. };
  46713. Animation.AppendSerializedAnimations = function (source, destination) {
  46714. if (source.animations) {
  46715. destination.animations = [];
  46716. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46717. var animation = source.animations[animationIndex];
  46718. destination.animations.push(animation.serialize());
  46719. }
  46720. }
  46721. };
  46722. Animation.AllowMatricesInterpolation = false;
  46723. // Statics
  46724. Animation._ANIMATIONTYPE_FLOAT = 0;
  46725. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46726. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46727. Animation._ANIMATIONTYPE_MATRIX = 3;
  46728. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46729. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46730. Animation._ANIMATIONTYPE_SIZE = 6;
  46731. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46732. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46733. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46734. return Animation;
  46735. }());
  46736. BABYLON.Animation = Animation;
  46737. })(BABYLON || (BABYLON = {}));
  46738. //# sourceMappingURL=babylon.animation.js.map
  46739. var BABYLON;
  46740. (function (BABYLON) {
  46741. /**
  46742. * This class defines the direct association between an animation and a target
  46743. */
  46744. var TargetedAnimation = /** @class */ (function () {
  46745. function TargetedAnimation() {
  46746. }
  46747. return TargetedAnimation;
  46748. }());
  46749. BABYLON.TargetedAnimation = TargetedAnimation;
  46750. /**
  46751. * Use this class to create coordinated animations on multiple targets
  46752. */
  46753. var AnimationGroup = /** @class */ (function () {
  46754. function AnimationGroup(name, scene) {
  46755. if (scene === void 0) { scene = null; }
  46756. this.name = name;
  46757. this._targetedAnimations = new Array();
  46758. this._animatables = new Array();
  46759. this._from = Number.MAX_VALUE;
  46760. this._to = -Number.MAX_VALUE;
  46761. this._speedRatio = 1;
  46762. this.onAnimationEndObservable = new BABYLON.Observable();
  46763. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46764. this._scene.animationGroups.push(this);
  46765. }
  46766. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46767. /**
  46768. * Define if the animations are started
  46769. */
  46770. get: function () {
  46771. return this._isStarted;
  46772. },
  46773. enumerable: true,
  46774. configurable: true
  46775. });
  46776. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46777. /**
  46778. * Gets or sets the speed ratio to use for all animations
  46779. */
  46780. get: function () {
  46781. return this._speedRatio;
  46782. },
  46783. /**
  46784. * Gets or sets the speed ratio to use for all animations
  46785. */
  46786. set: function (value) {
  46787. if (this._speedRatio === value) {
  46788. return;
  46789. }
  46790. this._speedRatio = value;
  46791. for (var index = 0; index < this._animatables.length; index++) {
  46792. var animatable = this._animatables[index];
  46793. animatable.speedRatio = this._speedRatio;
  46794. }
  46795. },
  46796. enumerable: true,
  46797. configurable: true
  46798. });
  46799. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46800. /**
  46801. * Gets the targeted animations for this animation group
  46802. */
  46803. get: function () {
  46804. return this._targetedAnimations;
  46805. },
  46806. enumerable: true,
  46807. configurable: true
  46808. });
  46809. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  46810. /**
  46811. * returning the list of animatables controlled by this animation group.
  46812. */
  46813. get: function () {
  46814. return this._animatables;
  46815. },
  46816. enumerable: true,
  46817. configurable: true
  46818. });
  46819. /**
  46820. * Add an animation (with its target) in the group
  46821. * @param animation defines the animation we want to add
  46822. * @param target defines the target of the animation
  46823. * @returns the {BABYLON.TargetedAnimation} object
  46824. */
  46825. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46826. var targetedAnimation = {
  46827. animation: animation,
  46828. target: target
  46829. };
  46830. var keys = animation.getKeys();
  46831. if (this._from > keys[0].frame) {
  46832. this._from = keys[0].frame;
  46833. }
  46834. if (this._to < keys[keys.length - 1].frame) {
  46835. this._to = keys[keys.length - 1].frame;
  46836. }
  46837. this._targetedAnimations.push(targetedAnimation);
  46838. return targetedAnimation;
  46839. };
  46840. /**
  46841. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46842. * It can add constant keys at begin or end
  46843. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46844. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46845. */
  46846. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46847. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46848. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46849. beginFrame = Math.max(beginFrame, this._from);
  46850. endFrame = Math.min(endFrame, this._to);
  46851. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46852. var targetedAnimation = this._targetedAnimations[index];
  46853. var keys = targetedAnimation.animation.getKeys();
  46854. var startKey = keys[0];
  46855. var endKey = keys[keys.length - 1];
  46856. if (startKey.frame > beginFrame) {
  46857. var newKey = {
  46858. frame: beginFrame,
  46859. value: startKey.value,
  46860. inTangent: startKey.inTangent,
  46861. outTangent: startKey.outTangent,
  46862. interpolation: startKey.interpolation
  46863. };
  46864. keys.splice(0, 0, newKey);
  46865. }
  46866. if (endKey.frame < endFrame) {
  46867. var newKey = {
  46868. frame: endFrame,
  46869. value: endKey.value,
  46870. inTangent: endKey.outTangent,
  46871. outTangent: endKey.outTangent,
  46872. interpolation: endKey.interpolation
  46873. };
  46874. keys.push(newKey);
  46875. }
  46876. }
  46877. return this;
  46878. };
  46879. /**
  46880. * Start all animations on given targets
  46881. * @param loop defines if animations must loop
  46882. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46883. */
  46884. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46885. var _this = this;
  46886. if (loop === void 0) { loop = false; }
  46887. if (speedRatio === void 0) { speedRatio = 1; }
  46888. if (this._isStarted || this._targetedAnimations.length === 0) {
  46889. return this;
  46890. }
  46891. var _loop_1 = function () {
  46892. var targetedAnimation = this_1._targetedAnimations[index];
  46893. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46894. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46895. }));
  46896. };
  46897. var this_1 = this;
  46898. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46899. _loop_1();
  46900. }
  46901. this._speedRatio = speedRatio;
  46902. this._isStarted = true;
  46903. return this;
  46904. };
  46905. /**
  46906. * Pause all animations
  46907. */
  46908. AnimationGroup.prototype.pause = function () {
  46909. if (!this._isStarted) {
  46910. return this;
  46911. }
  46912. for (var index = 0; index < this._animatables.length; index++) {
  46913. var animatable = this._animatables[index];
  46914. animatable.pause();
  46915. }
  46916. return this;
  46917. };
  46918. /**
  46919. * Play all animations to initial state
  46920. * This function will start() the animations if they were not started or will restart() them if they were paused
  46921. * @param loop defines if animations must loop
  46922. */
  46923. AnimationGroup.prototype.play = function (loop) {
  46924. if (this.isStarted) {
  46925. if (loop !== undefined) {
  46926. for (var index = 0; index < this._animatables.length; index++) {
  46927. var animatable = this._animatables[index];
  46928. animatable.loopAnimation = loop;
  46929. }
  46930. }
  46931. this.restart();
  46932. }
  46933. else {
  46934. this.start(loop, this._speedRatio);
  46935. }
  46936. return this;
  46937. };
  46938. /**
  46939. * Reset all animations to initial state
  46940. */
  46941. AnimationGroup.prototype.reset = function () {
  46942. if (!this._isStarted) {
  46943. return this;
  46944. }
  46945. for (var index = 0; index < this._animatables.length; index++) {
  46946. var animatable = this._animatables[index];
  46947. animatable.reset();
  46948. }
  46949. return this;
  46950. };
  46951. /**
  46952. * Restart animations from key 0
  46953. */
  46954. AnimationGroup.prototype.restart = function () {
  46955. if (!this._isStarted) {
  46956. return this;
  46957. }
  46958. for (var index = 0; index < this._animatables.length; index++) {
  46959. var animatable = this._animatables[index];
  46960. animatable.restart();
  46961. }
  46962. return this;
  46963. };
  46964. /**
  46965. * Stop all animations
  46966. */
  46967. AnimationGroup.prototype.stop = function () {
  46968. if (!this._isStarted) {
  46969. return this;
  46970. }
  46971. for (var index = 0; index < this._animatables.length; index++) {
  46972. var animatable = this._animatables[index];
  46973. animatable.stop();
  46974. }
  46975. this._isStarted = false;
  46976. return this;
  46977. };
  46978. /**
  46979. * Goes to a specific frame in this animation group
  46980. *
  46981. * @param frame the frame number to go to
  46982. * @return the animationGroup
  46983. */
  46984. AnimationGroup.prototype.goToFrame = function (frame) {
  46985. if (!this._isStarted) {
  46986. return this;
  46987. }
  46988. for (var index = 0; index < this._animatables.length; index++) {
  46989. var animatable = this._animatables[index];
  46990. animatable.goToFrame(frame);
  46991. }
  46992. return this;
  46993. };
  46994. /**
  46995. * Dispose all associated resources
  46996. */
  46997. AnimationGroup.prototype.dispose = function () {
  46998. this._targetedAnimations = [];
  46999. this._animatables = [];
  47000. var index = this._scene.animationGroups.indexOf(this);
  47001. if (index > -1) {
  47002. this._scene.animationGroups.splice(index, 1);
  47003. }
  47004. };
  47005. return AnimationGroup;
  47006. }());
  47007. BABYLON.AnimationGroup = AnimationGroup;
  47008. })(BABYLON || (BABYLON = {}));
  47009. //# sourceMappingURL=babylon.animationGroup.js.map
  47010. var BABYLON;
  47011. (function (BABYLON) {
  47012. var RuntimeAnimation = /** @class */ (function () {
  47013. function RuntimeAnimation(target, animation) {
  47014. this._offsetsCache = {};
  47015. this._highLimitsCache = {};
  47016. this._stopped = false;
  47017. this._blendingFactor = 0;
  47018. this._ratioOffset = 0;
  47019. this._animation = animation;
  47020. this._target = target;
  47021. animation._runtimeAnimations.push(this);
  47022. }
  47023. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47024. get: function () {
  47025. return this._animation;
  47026. },
  47027. enumerable: true,
  47028. configurable: true
  47029. });
  47030. RuntimeAnimation.prototype.reset = function () {
  47031. this._offsetsCache = {};
  47032. this._highLimitsCache = {};
  47033. this.currentFrame = 0;
  47034. this._blendingFactor = 0;
  47035. this._originalBlendValue = null;
  47036. };
  47037. RuntimeAnimation.prototype.isStopped = function () {
  47038. return this._stopped;
  47039. };
  47040. RuntimeAnimation.prototype.dispose = function () {
  47041. var index = this._animation.runtimeAnimations.indexOf(this);
  47042. if (index > -1) {
  47043. this._animation.runtimeAnimations.splice(index, 1);
  47044. }
  47045. };
  47046. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47047. if (typeof value === "function") {
  47048. return value();
  47049. }
  47050. return value;
  47051. };
  47052. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47053. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47054. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47055. }
  47056. this.currentFrame = currentFrame;
  47057. var keys = this._animation.getKeys();
  47058. // Try to get a hash to find the right key
  47059. 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));
  47060. if (keys[startKeyIndex].frame >= currentFrame) {
  47061. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47062. startKeyIndex--;
  47063. }
  47064. }
  47065. for (var key = startKeyIndex; key < keys.length; key++) {
  47066. var endKey = keys[key + 1];
  47067. if (endKey.frame >= currentFrame) {
  47068. var startKey = keys[key];
  47069. var startValue = this._getKeyValue(startKey.value);
  47070. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47071. return startValue;
  47072. }
  47073. var endValue = this._getKeyValue(endKey.value);
  47074. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47075. var frameDelta = endKey.frame - startKey.frame;
  47076. // gradient : percent of currentFrame between the frame inf and the frame sup
  47077. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47078. // check for easingFunction and correction of gradient
  47079. var easingFunction = this._animation.getEasingFunction();
  47080. if (easingFunction != null) {
  47081. gradient = easingFunction.ease(gradient);
  47082. }
  47083. switch (this._animation.dataType) {
  47084. // Float
  47085. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47086. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47087. switch (loopMode) {
  47088. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47089. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47090. return floatValue;
  47091. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47092. return offsetValue * repeatCount + floatValue;
  47093. }
  47094. break;
  47095. // Quaternion
  47096. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47097. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47098. switch (loopMode) {
  47099. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47100. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47101. return quatValue;
  47102. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47103. return quatValue.add(offsetValue.scale(repeatCount));
  47104. }
  47105. return quatValue;
  47106. // Vector3
  47107. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47108. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47109. switch (loopMode) {
  47110. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47111. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47112. return vec3Value;
  47113. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47114. return vec3Value.add(offsetValue.scale(repeatCount));
  47115. }
  47116. // Vector2
  47117. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47118. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47119. switch (loopMode) {
  47120. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47121. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47122. return vec2Value;
  47123. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47124. return vec2Value.add(offsetValue.scale(repeatCount));
  47125. }
  47126. // Size
  47127. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47128. switch (loopMode) {
  47129. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47130. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47131. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47132. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47133. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47134. }
  47135. // Color3
  47136. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47137. switch (loopMode) {
  47138. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47139. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47140. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47141. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47142. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47143. }
  47144. // Matrix
  47145. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47146. switch (loopMode) {
  47147. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47148. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47149. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47150. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47151. }
  47152. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47153. return startValue;
  47154. }
  47155. default:
  47156. break;
  47157. }
  47158. break;
  47159. }
  47160. }
  47161. return this._getKeyValue(keys[keys.length - 1].value);
  47162. };
  47163. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47164. if (blend === void 0) { blend = false; }
  47165. // Set value
  47166. var path;
  47167. var destination;
  47168. var targetPropertyPath = this._animation.targetPropertyPath;
  47169. if (targetPropertyPath.length > 1) {
  47170. var property = this._target[targetPropertyPath[0]];
  47171. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47172. property = property[targetPropertyPath[index]];
  47173. }
  47174. path = targetPropertyPath[targetPropertyPath.length - 1];
  47175. destination = property;
  47176. }
  47177. else {
  47178. path = targetPropertyPath[0];
  47179. destination = this._target;
  47180. }
  47181. // Blending
  47182. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47183. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47184. if (enableBlending && this._blendingFactor <= 1.0) {
  47185. if (!this._originalBlendValue) {
  47186. if (destination[path].clone) {
  47187. this._originalBlendValue = destination[path].clone();
  47188. }
  47189. else {
  47190. this._originalBlendValue = destination[path];
  47191. }
  47192. }
  47193. if (this._originalBlendValue.prototype) {
  47194. if (this._originalBlendValue.prototype.Lerp) {
  47195. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47196. }
  47197. else {
  47198. destination[path] = currentValue;
  47199. }
  47200. }
  47201. else if (this._originalBlendValue.m) {
  47202. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47203. }
  47204. else {
  47205. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47206. }
  47207. this._blendingFactor += blendingSpeed;
  47208. }
  47209. else {
  47210. destination[path] = currentValue;
  47211. }
  47212. if (this._target.markAsDirty) {
  47213. this._target.markAsDirty(this._animation.targetProperty);
  47214. }
  47215. };
  47216. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47217. if (this._target && this._target.animationPropertiesOverride) {
  47218. return this._target.animationPropertiesOverride.loopMode;
  47219. }
  47220. return this._animation.loopMode;
  47221. };
  47222. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47223. var keys = this._animation.getKeys();
  47224. if (frame < keys[0].frame) {
  47225. frame = keys[0].frame;
  47226. }
  47227. else if (frame > keys[keys.length - 1].frame) {
  47228. frame = keys[keys.length - 1].frame;
  47229. }
  47230. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47231. this.setValue(currentValue);
  47232. };
  47233. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47234. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47235. this._ratioOffset = this._previousRatio - newRatio;
  47236. };
  47237. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47238. if (blend === void 0) { blend = false; }
  47239. var targetPropertyPath = this._animation.targetPropertyPath;
  47240. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47241. this._stopped = true;
  47242. return false;
  47243. }
  47244. var returnValue = true;
  47245. var keys = this._animation.getKeys();
  47246. // Adding a start key at frame 0 if missing
  47247. if (keys[0].frame !== 0) {
  47248. var newKey = { frame: 0, value: keys[0].value };
  47249. keys.splice(0, 0, newKey);
  47250. }
  47251. // Check limits
  47252. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47253. from = keys[0].frame;
  47254. }
  47255. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47256. to = keys[keys.length - 1].frame;
  47257. }
  47258. //to and from cannot be the same key
  47259. if (from === to) {
  47260. if (from > keys[0].frame) {
  47261. from--;
  47262. }
  47263. else if (to < keys[keys.length - 1].frame) {
  47264. to++;
  47265. }
  47266. }
  47267. // Compute ratio
  47268. var range = to - from;
  47269. var offsetValue;
  47270. // ratio represents the frame delta between from and to
  47271. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47272. var highLimitValue = 0;
  47273. this._previousDelay = delay;
  47274. this._previousRatio = ratio;
  47275. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47276. returnValue = false;
  47277. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47278. }
  47279. else {
  47280. // Get max value if required
  47281. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47282. var keyOffset = to.toString() + from.toString();
  47283. if (!this._offsetsCache[keyOffset]) {
  47284. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47285. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47286. switch (this._animation.dataType) {
  47287. // Float
  47288. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47289. this._offsetsCache[keyOffset] = toValue - fromValue;
  47290. break;
  47291. // Quaternion
  47292. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47293. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47294. break;
  47295. // Vector3
  47296. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47297. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47298. // Vector2
  47299. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47300. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47301. // Size
  47302. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47303. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47304. // Color3
  47305. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47306. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47307. default:
  47308. break;
  47309. }
  47310. this._highLimitsCache[keyOffset] = toValue;
  47311. }
  47312. highLimitValue = this._highLimitsCache[keyOffset];
  47313. offsetValue = this._offsetsCache[keyOffset];
  47314. }
  47315. }
  47316. if (offsetValue === undefined) {
  47317. switch (this._animation.dataType) {
  47318. // Float
  47319. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47320. offsetValue = 0;
  47321. break;
  47322. // Quaternion
  47323. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47324. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47325. break;
  47326. // Vector3
  47327. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47328. offsetValue = BABYLON.Vector3.Zero();
  47329. break;
  47330. // Vector2
  47331. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47332. offsetValue = BABYLON.Vector2.Zero();
  47333. break;
  47334. // Size
  47335. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47336. offsetValue = BABYLON.Size.Zero();
  47337. break;
  47338. // Color3
  47339. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47340. offsetValue = BABYLON.Color3.Black();
  47341. }
  47342. }
  47343. // Compute value
  47344. var repeatCount = (ratio / range) >> 0;
  47345. var currentFrame = returnValue ? from + ratio % range : to;
  47346. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47347. // Set value
  47348. this.setValue(currentValue);
  47349. // Check events
  47350. var events = this._animation.getEvents();
  47351. for (var index = 0; index < events.length; index++) {
  47352. // Make sure current frame has passed event frame and that event frame is within the current range
  47353. // Also, handle both forward and reverse animations
  47354. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47355. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47356. var event = events[index];
  47357. if (!event.isDone) {
  47358. // If event should be done only once, remove it.
  47359. if (event.onlyOnce) {
  47360. events.splice(index, 1);
  47361. index--;
  47362. }
  47363. event.isDone = true;
  47364. event.action();
  47365. } // Don't do anything if the event has already be done.
  47366. }
  47367. else if (events[index].isDone && !events[index].onlyOnce) {
  47368. // reset event, the animation is looping
  47369. events[index].isDone = false;
  47370. }
  47371. }
  47372. if (!returnValue) {
  47373. this._stopped = true;
  47374. }
  47375. return returnValue;
  47376. };
  47377. return RuntimeAnimation;
  47378. }());
  47379. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47380. })(BABYLON || (BABYLON = {}));
  47381. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47382. var BABYLON;
  47383. (function (BABYLON) {
  47384. var Animatable = /** @class */ (function () {
  47385. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47386. if (fromFrame === void 0) { fromFrame = 0; }
  47387. if (toFrame === void 0) { toFrame = 100; }
  47388. if (loopAnimation === void 0) { loopAnimation = false; }
  47389. if (speedRatio === void 0) { speedRatio = 1.0; }
  47390. this.target = target;
  47391. this.fromFrame = fromFrame;
  47392. this.toFrame = toFrame;
  47393. this.loopAnimation = loopAnimation;
  47394. this.onAnimationEnd = onAnimationEnd;
  47395. this._localDelayOffset = null;
  47396. this._pausedDelay = null;
  47397. this._runtimeAnimations = new Array();
  47398. this._paused = false;
  47399. this._speedRatio = 1;
  47400. this.animationStarted = false;
  47401. if (animations) {
  47402. this.appendAnimations(target, animations);
  47403. }
  47404. this._speedRatio = speedRatio;
  47405. this._scene = scene;
  47406. scene._activeAnimatables.push(this);
  47407. }
  47408. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47409. get: function () {
  47410. return this._speedRatio;
  47411. },
  47412. set: function (value) {
  47413. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47414. var animation = this._runtimeAnimations[index];
  47415. animation._prepareForSpeedRatioChange(value);
  47416. }
  47417. this._speedRatio = value;
  47418. },
  47419. enumerable: true,
  47420. configurable: true
  47421. });
  47422. // Methods
  47423. Animatable.prototype.getAnimations = function () {
  47424. return this._runtimeAnimations;
  47425. };
  47426. Animatable.prototype.appendAnimations = function (target, animations) {
  47427. for (var index = 0; index < animations.length; index++) {
  47428. var animation = animations[index];
  47429. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47430. }
  47431. };
  47432. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47433. var runtimeAnimations = this._runtimeAnimations;
  47434. for (var index = 0; index < runtimeAnimations.length; index++) {
  47435. if (runtimeAnimations[index].animation.targetProperty === property) {
  47436. return runtimeAnimations[index].animation;
  47437. }
  47438. }
  47439. return null;
  47440. };
  47441. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47442. var runtimeAnimations = this._runtimeAnimations;
  47443. for (var index = 0; index < runtimeAnimations.length; index++) {
  47444. if (runtimeAnimations[index].animation.targetProperty === property) {
  47445. return runtimeAnimations[index];
  47446. }
  47447. }
  47448. return null;
  47449. };
  47450. Animatable.prototype.reset = function () {
  47451. var runtimeAnimations = this._runtimeAnimations;
  47452. for (var index = 0; index < runtimeAnimations.length; index++) {
  47453. runtimeAnimations[index].reset();
  47454. }
  47455. // Reset to original value
  47456. for (index = 0; index < runtimeAnimations.length; index++) {
  47457. var animation = runtimeAnimations[index];
  47458. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47459. }
  47460. this._localDelayOffset = null;
  47461. this._pausedDelay = null;
  47462. };
  47463. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47464. var runtimeAnimations = this._runtimeAnimations;
  47465. for (var index = 0; index < runtimeAnimations.length; index++) {
  47466. runtimeAnimations[index].animation.enableBlending = true;
  47467. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47468. }
  47469. };
  47470. Animatable.prototype.disableBlending = function () {
  47471. var runtimeAnimations = this._runtimeAnimations;
  47472. for (var index = 0; index < runtimeAnimations.length; index++) {
  47473. runtimeAnimations[index].animation.enableBlending = false;
  47474. }
  47475. };
  47476. Animatable.prototype.goToFrame = function (frame) {
  47477. var runtimeAnimations = this._runtimeAnimations;
  47478. if (runtimeAnimations[0]) {
  47479. var fps = runtimeAnimations[0].animation.framePerSecond;
  47480. var currentFrame = runtimeAnimations[0].currentFrame;
  47481. var adjustTime = frame - currentFrame;
  47482. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47483. if (this._localDelayOffset === null) {
  47484. this._localDelayOffset = 0;
  47485. }
  47486. this._localDelayOffset -= delay;
  47487. }
  47488. for (var index = 0; index < runtimeAnimations.length; index++) {
  47489. runtimeAnimations[index].goToFrame(frame);
  47490. }
  47491. };
  47492. Animatable.prototype.pause = function () {
  47493. if (this._paused) {
  47494. return;
  47495. }
  47496. this._paused = true;
  47497. };
  47498. Animatable.prototype.restart = function () {
  47499. this._paused = false;
  47500. };
  47501. Animatable.prototype.stop = function (animationName) {
  47502. if (animationName) {
  47503. var idx = this._scene._activeAnimatables.indexOf(this);
  47504. if (idx > -1) {
  47505. var runtimeAnimations = this._runtimeAnimations;
  47506. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47507. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47508. continue;
  47509. }
  47510. runtimeAnimations[index].dispose();
  47511. runtimeAnimations.splice(index, 1);
  47512. }
  47513. if (runtimeAnimations.length == 0) {
  47514. this._scene._activeAnimatables.splice(idx, 1);
  47515. if (this.onAnimationEnd) {
  47516. this.onAnimationEnd();
  47517. }
  47518. }
  47519. }
  47520. }
  47521. else {
  47522. var index = this._scene._activeAnimatables.indexOf(this);
  47523. if (index > -1) {
  47524. this._scene._activeAnimatables.splice(index, 1);
  47525. var runtimeAnimations = this._runtimeAnimations;
  47526. for (var index = 0; index < runtimeAnimations.length; index++) {
  47527. runtimeAnimations[index].dispose();
  47528. }
  47529. if (this.onAnimationEnd) {
  47530. this.onAnimationEnd();
  47531. }
  47532. }
  47533. }
  47534. };
  47535. Animatable.prototype._animate = function (delay) {
  47536. if (this._paused) {
  47537. this.animationStarted = false;
  47538. if (this._pausedDelay === null) {
  47539. this._pausedDelay = delay;
  47540. }
  47541. return true;
  47542. }
  47543. if (this._localDelayOffset === null) {
  47544. this._localDelayOffset = delay;
  47545. this._pausedDelay = null;
  47546. }
  47547. else if (this._pausedDelay !== null) {
  47548. this._localDelayOffset += delay - this._pausedDelay;
  47549. this._pausedDelay = null;
  47550. }
  47551. // Animating
  47552. var running = false;
  47553. var runtimeAnimations = this._runtimeAnimations;
  47554. var index;
  47555. for (index = 0; index < runtimeAnimations.length; index++) {
  47556. var animation = runtimeAnimations[index];
  47557. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47558. running = running || isRunning;
  47559. }
  47560. this.animationStarted = running;
  47561. if (!running) {
  47562. // Remove from active animatables
  47563. index = this._scene._activeAnimatables.indexOf(this);
  47564. this._scene._activeAnimatables.splice(index, 1);
  47565. // Dispose all runtime animations
  47566. for (index = 0; index < runtimeAnimations.length; index++) {
  47567. runtimeAnimations[index].dispose();
  47568. }
  47569. }
  47570. if (!running && this.onAnimationEnd) {
  47571. this.onAnimationEnd();
  47572. this.onAnimationEnd = null;
  47573. }
  47574. return running;
  47575. };
  47576. return Animatable;
  47577. }());
  47578. BABYLON.Animatable = Animatable;
  47579. })(BABYLON || (BABYLON = {}));
  47580. //# sourceMappingURL=babylon.animatable.js.map
  47581. var BABYLON;
  47582. (function (BABYLON) {
  47583. var EasingFunction = /** @class */ (function () {
  47584. function EasingFunction() {
  47585. // Properties
  47586. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47587. }
  47588. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47589. get: function () {
  47590. return EasingFunction._EASINGMODE_EASEIN;
  47591. },
  47592. enumerable: true,
  47593. configurable: true
  47594. });
  47595. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47596. get: function () {
  47597. return EasingFunction._EASINGMODE_EASEOUT;
  47598. },
  47599. enumerable: true,
  47600. configurable: true
  47601. });
  47602. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47603. get: function () {
  47604. return EasingFunction._EASINGMODE_EASEINOUT;
  47605. },
  47606. enumerable: true,
  47607. configurable: true
  47608. });
  47609. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47610. var n = Math.min(Math.max(easingMode, 0), 2);
  47611. this._easingMode = n;
  47612. };
  47613. EasingFunction.prototype.getEasingMode = function () {
  47614. return this._easingMode;
  47615. };
  47616. EasingFunction.prototype.easeInCore = function (gradient) {
  47617. throw new Error('You must implement this method');
  47618. };
  47619. EasingFunction.prototype.ease = function (gradient) {
  47620. switch (this._easingMode) {
  47621. case EasingFunction.EASINGMODE_EASEIN:
  47622. return this.easeInCore(gradient);
  47623. case EasingFunction.EASINGMODE_EASEOUT:
  47624. return (1 - this.easeInCore(1 - gradient));
  47625. }
  47626. if (gradient >= 0.5) {
  47627. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47628. }
  47629. return (this.easeInCore(gradient * 2) * 0.5);
  47630. };
  47631. //Statics
  47632. EasingFunction._EASINGMODE_EASEIN = 0;
  47633. EasingFunction._EASINGMODE_EASEOUT = 1;
  47634. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47635. return EasingFunction;
  47636. }());
  47637. BABYLON.EasingFunction = EasingFunction;
  47638. var CircleEase = /** @class */ (function (_super) {
  47639. __extends(CircleEase, _super);
  47640. function CircleEase() {
  47641. return _super !== null && _super.apply(this, arguments) || this;
  47642. }
  47643. CircleEase.prototype.easeInCore = function (gradient) {
  47644. gradient = Math.max(0, Math.min(1, gradient));
  47645. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47646. };
  47647. return CircleEase;
  47648. }(EasingFunction));
  47649. BABYLON.CircleEase = CircleEase;
  47650. var BackEase = /** @class */ (function (_super) {
  47651. __extends(BackEase, _super);
  47652. function BackEase(amplitude) {
  47653. if (amplitude === void 0) { amplitude = 1; }
  47654. var _this = _super.call(this) || this;
  47655. _this.amplitude = amplitude;
  47656. return _this;
  47657. }
  47658. BackEase.prototype.easeInCore = function (gradient) {
  47659. var num = Math.max(0, this.amplitude);
  47660. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47661. };
  47662. return BackEase;
  47663. }(EasingFunction));
  47664. BABYLON.BackEase = BackEase;
  47665. var BounceEase = /** @class */ (function (_super) {
  47666. __extends(BounceEase, _super);
  47667. function BounceEase(bounces, bounciness) {
  47668. if (bounces === void 0) { bounces = 3; }
  47669. if (bounciness === void 0) { bounciness = 2; }
  47670. var _this = _super.call(this) || this;
  47671. _this.bounces = bounces;
  47672. _this.bounciness = bounciness;
  47673. return _this;
  47674. }
  47675. BounceEase.prototype.easeInCore = function (gradient) {
  47676. var y = Math.max(0.0, this.bounces);
  47677. var bounciness = this.bounciness;
  47678. if (bounciness <= 1.0) {
  47679. bounciness = 1.001;
  47680. }
  47681. var num9 = Math.pow(bounciness, y);
  47682. var num5 = 1.0 - bounciness;
  47683. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47684. var num15 = gradient * num4;
  47685. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47686. var num3 = Math.floor(num65);
  47687. var num13 = num3 + 1.0;
  47688. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47689. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47690. var num7 = (num8 + num12) * 0.5;
  47691. var num6 = gradient - num7;
  47692. var num2 = num7 - num8;
  47693. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47694. };
  47695. return BounceEase;
  47696. }(EasingFunction));
  47697. BABYLON.BounceEase = BounceEase;
  47698. var CubicEase = /** @class */ (function (_super) {
  47699. __extends(CubicEase, _super);
  47700. function CubicEase() {
  47701. return _super !== null && _super.apply(this, arguments) || this;
  47702. }
  47703. CubicEase.prototype.easeInCore = function (gradient) {
  47704. return (gradient * gradient * gradient);
  47705. };
  47706. return CubicEase;
  47707. }(EasingFunction));
  47708. BABYLON.CubicEase = CubicEase;
  47709. var ElasticEase = /** @class */ (function (_super) {
  47710. __extends(ElasticEase, _super);
  47711. function ElasticEase(oscillations, springiness) {
  47712. if (oscillations === void 0) { oscillations = 3; }
  47713. if (springiness === void 0) { springiness = 3; }
  47714. var _this = _super.call(this) || this;
  47715. _this.oscillations = oscillations;
  47716. _this.springiness = springiness;
  47717. return _this;
  47718. }
  47719. ElasticEase.prototype.easeInCore = function (gradient) {
  47720. var num2;
  47721. var num3 = Math.max(0.0, this.oscillations);
  47722. var num = Math.max(0.0, this.springiness);
  47723. if (num == 0) {
  47724. num2 = gradient;
  47725. }
  47726. else {
  47727. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47728. }
  47729. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47730. };
  47731. return ElasticEase;
  47732. }(EasingFunction));
  47733. BABYLON.ElasticEase = ElasticEase;
  47734. var ExponentialEase = /** @class */ (function (_super) {
  47735. __extends(ExponentialEase, _super);
  47736. function ExponentialEase(exponent) {
  47737. if (exponent === void 0) { exponent = 2; }
  47738. var _this = _super.call(this) || this;
  47739. _this.exponent = exponent;
  47740. return _this;
  47741. }
  47742. ExponentialEase.prototype.easeInCore = function (gradient) {
  47743. if (this.exponent <= 0) {
  47744. return gradient;
  47745. }
  47746. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47747. };
  47748. return ExponentialEase;
  47749. }(EasingFunction));
  47750. BABYLON.ExponentialEase = ExponentialEase;
  47751. var PowerEase = /** @class */ (function (_super) {
  47752. __extends(PowerEase, _super);
  47753. function PowerEase(power) {
  47754. if (power === void 0) { power = 2; }
  47755. var _this = _super.call(this) || this;
  47756. _this.power = power;
  47757. return _this;
  47758. }
  47759. PowerEase.prototype.easeInCore = function (gradient) {
  47760. var y = Math.max(0.0, this.power);
  47761. return Math.pow(gradient, y);
  47762. };
  47763. return PowerEase;
  47764. }(EasingFunction));
  47765. BABYLON.PowerEase = PowerEase;
  47766. var QuadraticEase = /** @class */ (function (_super) {
  47767. __extends(QuadraticEase, _super);
  47768. function QuadraticEase() {
  47769. return _super !== null && _super.apply(this, arguments) || this;
  47770. }
  47771. QuadraticEase.prototype.easeInCore = function (gradient) {
  47772. return (gradient * gradient);
  47773. };
  47774. return QuadraticEase;
  47775. }(EasingFunction));
  47776. BABYLON.QuadraticEase = QuadraticEase;
  47777. var QuarticEase = /** @class */ (function (_super) {
  47778. __extends(QuarticEase, _super);
  47779. function QuarticEase() {
  47780. return _super !== null && _super.apply(this, arguments) || this;
  47781. }
  47782. QuarticEase.prototype.easeInCore = function (gradient) {
  47783. return (gradient * gradient * gradient * gradient);
  47784. };
  47785. return QuarticEase;
  47786. }(EasingFunction));
  47787. BABYLON.QuarticEase = QuarticEase;
  47788. var QuinticEase = /** @class */ (function (_super) {
  47789. __extends(QuinticEase, _super);
  47790. function QuinticEase() {
  47791. return _super !== null && _super.apply(this, arguments) || this;
  47792. }
  47793. QuinticEase.prototype.easeInCore = function (gradient) {
  47794. return (gradient * gradient * gradient * gradient * gradient);
  47795. };
  47796. return QuinticEase;
  47797. }(EasingFunction));
  47798. BABYLON.QuinticEase = QuinticEase;
  47799. var SineEase = /** @class */ (function (_super) {
  47800. __extends(SineEase, _super);
  47801. function SineEase() {
  47802. return _super !== null && _super.apply(this, arguments) || this;
  47803. }
  47804. SineEase.prototype.easeInCore = function (gradient) {
  47805. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47806. };
  47807. return SineEase;
  47808. }(EasingFunction));
  47809. BABYLON.SineEase = SineEase;
  47810. var BezierCurveEase = /** @class */ (function (_super) {
  47811. __extends(BezierCurveEase, _super);
  47812. function BezierCurveEase(x1, y1, x2, y2) {
  47813. if (x1 === void 0) { x1 = 0; }
  47814. if (y1 === void 0) { y1 = 0; }
  47815. if (x2 === void 0) { x2 = 1; }
  47816. if (y2 === void 0) { y2 = 1; }
  47817. var _this = _super.call(this) || this;
  47818. _this.x1 = x1;
  47819. _this.y1 = y1;
  47820. _this.x2 = x2;
  47821. _this.y2 = y2;
  47822. return _this;
  47823. }
  47824. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47825. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47826. };
  47827. return BezierCurveEase;
  47828. }(EasingFunction));
  47829. BABYLON.BezierCurveEase = BezierCurveEase;
  47830. })(BABYLON || (BABYLON = {}));
  47831. //# sourceMappingURL=babylon.easing.js.map
  47832. var BABYLON;
  47833. (function (BABYLON) {
  47834. var Condition = /** @class */ (function () {
  47835. function Condition(actionManager) {
  47836. this._actionManager = actionManager;
  47837. }
  47838. Condition.prototype.isValid = function () {
  47839. return true;
  47840. };
  47841. Condition.prototype._getProperty = function (propertyPath) {
  47842. return this._actionManager._getProperty(propertyPath);
  47843. };
  47844. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47845. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47846. };
  47847. Condition.prototype.serialize = function () {
  47848. };
  47849. Condition.prototype._serialize = function (serializedCondition) {
  47850. return {
  47851. type: 2,
  47852. children: [],
  47853. name: serializedCondition.name,
  47854. properties: serializedCondition.properties
  47855. };
  47856. };
  47857. return Condition;
  47858. }());
  47859. BABYLON.Condition = Condition;
  47860. var ValueCondition = /** @class */ (function (_super) {
  47861. __extends(ValueCondition, _super);
  47862. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47863. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47864. var _this = _super.call(this, actionManager) || this;
  47865. _this.propertyPath = propertyPath;
  47866. _this.value = value;
  47867. _this.operator = operator;
  47868. _this._target = target;
  47869. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47870. _this._property = _this._getProperty(_this.propertyPath);
  47871. return _this;
  47872. }
  47873. Object.defineProperty(ValueCondition, "IsEqual", {
  47874. get: function () {
  47875. return ValueCondition._IsEqual;
  47876. },
  47877. enumerable: true,
  47878. configurable: true
  47879. });
  47880. Object.defineProperty(ValueCondition, "IsDifferent", {
  47881. get: function () {
  47882. return ValueCondition._IsDifferent;
  47883. },
  47884. enumerable: true,
  47885. configurable: true
  47886. });
  47887. Object.defineProperty(ValueCondition, "IsGreater", {
  47888. get: function () {
  47889. return ValueCondition._IsGreater;
  47890. },
  47891. enumerable: true,
  47892. configurable: true
  47893. });
  47894. Object.defineProperty(ValueCondition, "IsLesser", {
  47895. get: function () {
  47896. return ValueCondition._IsLesser;
  47897. },
  47898. enumerable: true,
  47899. configurable: true
  47900. });
  47901. // Methods
  47902. ValueCondition.prototype.isValid = function () {
  47903. switch (this.operator) {
  47904. case ValueCondition.IsGreater:
  47905. return this._effectiveTarget[this._property] > this.value;
  47906. case ValueCondition.IsLesser:
  47907. return this._effectiveTarget[this._property] < this.value;
  47908. case ValueCondition.IsEqual:
  47909. case ValueCondition.IsDifferent:
  47910. var check;
  47911. if (this.value.equals) {
  47912. check = this.value.equals(this._effectiveTarget[this._property]);
  47913. }
  47914. else {
  47915. check = this.value === this._effectiveTarget[this._property];
  47916. }
  47917. return this.operator === ValueCondition.IsEqual ? check : !check;
  47918. }
  47919. return false;
  47920. };
  47921. ValueCondition.prototype.serialize = function () {
  47922. return this._serialize({
  47923. name: "ValueCondition",
  47924. properties: [
  47925. BABYLON.Action._GetTargetProperty(this._target),
  47926. { name: "propertyPath", value: this.propertyPath },
  47927. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47928. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47929. ]
  47930. });
  47931. };
  47932. ValueCondition.GetOperatorName = function (operator) {
  47933. switch (operator) {
  47934. case ValueCondition._IsEqual: return "IsEqual";
  47935. case ValueCondition._IsDifferent: return "IsDifferent";
  47936. case ValueCondition._IsGreater: return "IsGreater";
  47937. case ValueCondition._IsLesser: return "IsLesser";
  47938. default: return "";
  47939. }
  47940. };
  47941. // Statics
  47942. ValueCondition._IsEqual = 0;
  47943. ValueCondition._IsDifferent = 1;
  47944. ValueCondition._IsGreater = 2;
  47945. ValueCondition._IsLesser = 3;
  47946. return ValueCondition;
  47947. }(Condition));
  47948. BABYLON.ValueCondition = ValueCondition;
  47949. var PredicateCondition = /** @class */ (function (_super) {
  47950. __extends(PredicateCondition, _super);
  47951. function PredicateCondition(actionManager, predicate) {
  47952. var _this = _super.call(this, actionManager) || this;
  47953. _this.predicate = predicate;
  47954. return _this;
  47955. }
  47956. PredicateCondition.prototype.isValid = function () {
  47957. return this.predicate();
  47958. };
  47959. return PredicateCondition;
  47960. }(Condition));
  47961. BABYLON.PredicateCondition = PredicateCondition;
  47962. var StateCondition = /** @class */ (function (_super) {
  47963. __extends(StateCondition, _super);
  47964. function StateCondition(actionManager, target, value) {
  47965. var _this = _super.call(this, actionManager) || this;
  47966. _this.value = value;
  47967. _this._target = target;
  47968. return _this;
  47969. }
  47970. // Methods
  47971. StateCondition.prototype.isValid = function () {
  47972. return this._target.state === this.value;
  47973. };
  47974. StateCondition.prototype.serialize = function () {
  47975. return this._serialize({
  47976. name: "StateCondition",
  47977. properties: [
  47978. BABYLON.Action._GetTargetProperty(this._target),
  47979. { name: "value", value: this.value }
  47980. ]
  47981. });
  47982. };
  47983. return StateCondition;
  47984. }(Condition));
  47985. BABYLON.StateCondition = StateCondition;
  47986. })(BABYLON || (BABYLON = {}));
  47987. //# sourceMappingURL=babylon.condition.js.map
  47988. var BABYLON;
  47989. (function (BABYLON) {
  47990. var Action = /** @class */ (function () {
  47991. function Action(triggerOptions, condition) {
  47992. this.triggerOptions = triggerOptions;
  47993. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47994. if (triggerOptions.parameter) {
  47995. this.trigger = triggerOptions.trigger;
  47996. this._triggerParameter = triggerOptions.parameter;
  47997. }
  47998. else {
  47999. this.trigger = triggerOptions;
  48000. }
  48001. this._nextActiveAction = this;
  48002. this._condition = condition;
  48003. }
  48004. // Methods
  48005. Action.prototype._prepare = function () {
  48006. };
  48007. Action.prototype.getTriggerParameter = function () {
  48008. return this._triggerParameter;
  48009. };
  48010. Action.prototype._executeCurrent = function (evt) {
  48011. if (this._nextActiveAction._condition) {
  48012. var condition = this._nextActiveAction._condition;
  48013. var currentRenderId = this._actionManager.getScene().getRenderId();
  48014. // We cache the current evaluation for the current frame
  48015. if (condition._evaluationId === currentRenderId) {
  48016. if (!condition._currentResult) {
  48017. return;
  48018. }
  48019. }
  48020. else {
  48021. condition._evaluationId = currentRenderId;
  48022. if (!condition.isValid()) {
  48023. condition._currentResult = false;
  48024. return;
  48025. }
  48026. condition._currentResult = true;
  48027. }
  48028. }
  48029. this.onBeforeExecuteObservable.notifyObservers(this);
  48030. this._nextActiveAction.execute(evt);
  48031. this.skipToNextActiveAction();
  48032. };
  48033. Action.prototype.execute = function (evt) {
  48034. };
  48035. Action.prototype.skipToNextActiveAction = function () {
  48036. if (this._nextActiveAction._child) {
  48037. if (!this._nextActiveAction._child._actionManager) {
  48038. this._nextActiveAction._child._actionManager = this._actionManager;
  48039. }
  48040. this._nextActiveAction = this._nextActiveAction._child;
  48041. }
  48042. else {
  48043. this._nextActiveAction = this;
  48044. }
  48045. };
  48046. Action.prototype.then = function (action) {
  48047. this._child = action;
  48048. action._actionManager = this._actionManager;
  48049. action._prepare();
  48050. return action;
  48051. };
  48052. Action.prototype._getProperty = function (propertyPath) {
  48053. return this._actionManager._getProperty(propertyPath);
  48054. };
  48055. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48056. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48057. };
  48058. Action.prototype.serialize = function (parent) {
  48059. };
  48060. // Called by BABYLON.Action objects in serialize(...). Internal use
  48061. Action.prototype._serialize = function (serializedAction, parent) {
  48062. var serializationObject = {
  48063. type: 1,
  48064. children: [],
  48065. name: serializedAction.name,
  48066. properties: serializedAction.properties || []
  48067. };
  48068. // Serialize child
  48069. if (this._child) {
  48070. this._child.serialize(serializationObject);
  48071. }
  48072. // Check if "this" has a condition
  48073. if (this._condition) {
  48074. var serializedCondition = this._condition.serialize();
  48075. serializedCondition.children.push(serializationObject);
  48076. if (parent) {
  48077. parent.children.push(serializedCondition);
  48078. }
  48079. return serializedCondition;
  48080. }
  48081. if (parent) {
  48082. parent.children.push(serializationObject);
  48083. }
  48084. return serializationObject;
  48085. };
  48086. Action._SerializeValueAsString = function (value) {
  48087. if (typeof value === "number") {
  48088. return value.toString();
  48089. }
  48090. if (typeof value === "boolean") {
  48091. return value ? "true" : "false";
  48092. }
  48093. if (value instanceof BABYLON.Vector2) {
  48094. return value.x + ", " + value.y;
  48095. }
  48096. if (value instanceof BABYLON.Vector3) {
  48097. return value.x + ", " + value.y + ", " + value.z;
  48098. }
  48099. if (value instanceof BABYLON.Color3) {
  48100. return value.r + ", " + value.g + ", " + value.b;
  48101. }
  48102. if (value instanceof BABYLON.Color4) {
  48103. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48104. }
  48105. return value; // string
  48106. };
  48107. Action._GetTargetProperty = function (target) {
  48108. return {
  48109. name: "target",
  48110. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48111. : target instanceof BABYLON.Light ? "LightProperties"
  48112. : target instanceof BABYLON.Camera ? "CameraProperties"
  48113. : "SceneProperties",
  48114. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48115. };
  48116. };
  48117. return Action;
  48118. }());
  48119. BABYLON.Action = Action;
  48120. })(BABYLON || (BABYLON = {}));
  48121. //# sourceMappingURL=babylon.action.js.map
  48122. var BABYLON;
  48123. (function (BABYLON) {
  48124. /**
  48125. * ActionEvent is the event beint sent when an action is triggered.
  48126. */
  48127. var ActionEvent = /** @class */ (function () {
  48128. /**
  48129. * @param source The mesh or sprite that triggered the action.
  48130. * @param pointerX The X mouse cursor position at the time of the event
  48131. * @param pointerY The Y mouse cursor position at the time of the event
  48132. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48133. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48134. */
  48135. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48136. this.source = source;
  48137. this.pointerX = pointerX;
  48138. this.pointerY = pointerY;
  48139. this.meshUnderPointer = meshUnderPointer;
  48140. this.sourceEvent = sourceEvent;
  48141. this.additionalData = additionalData;
  48142. }
  48143. /**
  48144. * Helper function to auto-create an ActionEvent from a source mesh.
  48145. * @param source The source mesh that triggered the event
  48146. * @param evt {Event} The original (browser) event
  48147. */
  48148. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48149. var scene = source.getScene();
  48150. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48151. };
  48152. /**
  48153. * Helper function to auto-create an ActionEvent from a source mesh.
  48154. * @param source The source sprite that triggered the event
  48155. * @param scene Scene associated with the sprite
  48156. * @param evt {Event} The original (browser) event
  48157. */
  48158. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48159. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48160. };
  48161. /**
  48162. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48163. * @param scene the scene where the event occurred
  48164. * @param evt {Event} The original (browser) event
  48165. */
  48166. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48167. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48168. };
  48169. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48170. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48171. };
  48172. return ActionEvent;
  48173. }());
  48174. BABYLON.ActionEvent = ActionEvent;
  48175. /**
  48176. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48177. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48178. */
  48179. var ActionManager = /** @class */ (function () {
  48180. function ActionManager(scene) {
  48181. // Members
  48182. this.actions = new Array();
  48183. this.hoverCursor = '';
  48184. this._scene = scene;
  48185. scene._actionManagers.push(this);
  48186. }
  48187. Object.defineProperty(ActionManager, "NothingTrigger", {
  48188. get: function () {
  48189. return ActionManager._NothingTrigger;
  48190. },
  48191. enumerable: true,
  48192. configurable: true
  48193. });
  48194. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48195. get: function () {
  48196. return ActionManager._OnPickTrigger;
  48197. },
  48198. enumerable: true,
  48199. configurable: true
  48200. });
  48201. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48202. get: function () {
  48203. return ActionManager._OnLeftPickTrigger;
  48204. },
  48205. enumerable: true,
  48206. configurable: true
  48207. });
  48208. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48209. get: function () {
  48210. return ActionManager._OnRightPickTrigger;
  48211. },
  48212. enumerable: true,
  48213. configurable: true
  48214. });
  48215. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48216. get: function () {
  48217. return ActionManager._OnCenterPickTrigger;
  48218. },
  48219. enumerable: true,
  48220. configurable: true
  48221. });
  48222. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48223. get: function () {
  48224. return ActionManager._OnPickDownTrigger;
  48225. },
  48226. enumerable: true,
  48227. configurable: true
  48228. });
  48229. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48230. get: function () {
  48231. return ActionManager._OnDoublePickTrigger;
  48232. },
  48233. enumerable: true,
  48234. configurable: true
  48235. });
  48236. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48237. get: function () {
  48238. return ActionManager._OnPickUpTrigger;
  48239. },
  48240. enumerable: true,
  48241. configurable: true
  48242. });
  48243. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48244. /// This trigger will only be raised if you also declared a OnPickDown
  48245. get: function () {
  48246. return ActionManager._OnPickOutTrigger;
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48252. get: function () {
  48253. return ActionManager._OnLongPressTrigger;
  48254. },
  48255. enumerable: true,
  48256. configurable: true
  48257. });
  48258. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48259. get: function () {
  48260. return ActionManager._OnPointerOverTrigger;
  48261. },
  48262. enumerable: true,
  48263. configurable: true
  48264. });
  48265. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48266. get: function () {
  48267. return ActionManager._OnPointerOutTrigger;
  48268. },
  48269. enumerable: true,
  48270. configurable: true
  48271. });
  48272. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48273. get: function () {
  48274. return ActionManager._OnEveryFrameTrigger;
  48275. },
  48276. enumerable: true,
  48277. configurable: true
  48278. });
  48279. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48280. get: function () {
  48281. return ActionManager._OnIntersectionEnterTrigger;
  48282. },
  48283. enumerable: true,
  48284. configurable: true
  48285. });
  48286. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48287. get: function () {
  48288. return ActionManager._OnIntersectionExitTrigger;
  48289. },
  48290. enumerable: true,
  48291. configurable: true
  48292. });
  48293. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48294. get: function () {
  48295. return ActionManager._OnKeyDownTrigger;
  48296. },
  48297. enumerable: true,
  48298. configurable: true
  48299. });
  48300. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48301. get: function () {
  48302. return ActionManager._OnKeyUpTrigger;
  48303. },
  48304. enumerable: true,
  48305. configurable: true
  48306. });
  48307. // Methods
  48308. ActionManager.prototype.dispose = function () {
  48309. var index = this._scene._actionManagers.indexOf(this);
  48310. for (var i = 0; i < this.actions.length; i++) {
  48311. var action = this.actions[i];
  48312. ActionManager.Triggers[action.trigger]--;
  48313. if (ActionManager.Triggers[action.trigger] === 0) {
  48314. delete ActionManager.Triggers[action.trigger];
  48315. }
  48316. }
  48317. if (index > -1) {
  48318. this._scene._actionManagers.splice(index, 1);
  48319. }
  48320. };
  48321. ActionManager.prototype.getScene = function () {
  48322. return this._scene;
  48323. };
  48324. /**
  48325. * Does this action manager handles actions of any of the given triggers
  48326. * @param {number[]} triggers - the triggers to be tested
  48327. * @return {boolean} whether one (or more) of the triggers is handeled
  48328. */
  48329. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48330. for (var index = 0; index < this.actions.length; index++) {
  48331. var action = this.actions[index];
  48332. if (triggers.indexOf(action.trigger) > -1) {
  48333. return true;
  48334. }
  48335. }
  48336. return false;
  48337. };
  48338. /**
  48339. * Does this action manager handles actions of a given trigger
  48340. * @param {number} trigger - the trigger to be tested
  48341. * @return {boolean} whether the trigger is handeled
  48342. */
  48343. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48344. for (var index = 0; index < this.actions.length; index++) {
  48345. var action = this.actions[index];
  48346. if (action.trigger === trigger) {
  48347. return true;
  48348. }
  48349. }
  48350. return false;
  48351. };
  48352. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48353. /**
  48354. * Does this action manager has pointer triggers
  48355. * @return {boolean} whether or not it has pointer triggers
  48356. */
  48357. get: function () {
  48358. for (var index = 0; index < this.actions.length; index++) {
  48359. var action = this.actions[index];
  48360. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48361. return true;
  48362. }
  48363. }
  48364. return false;
  48365. },
  48366. enumerable: true,
  48367. configurable: true
  48368. });
  48369. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48370. /**
  48371. * Does this action manager has pick triggers
  48372. * @return {boolean} whether or not it has pick triggers
  48373. */
  48374. get: function () {
  48375. for (var index = 0; index < this.actions.length; index++) {
  48376. var action = this.actions[index];
  48377. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48378. return true;
  48379. }
  48380. }
  48381. return false;
  48382. },
  48383. enumerable: true,
  48384. configurable: true
  48385. });
  48386. Object.defineProperty(ActionManager, "HasTriggers", {
  48387. /**
  48388. * Does exist one action manager with at least one trigger
  48389. * @return {boolean} whether or not it exists one action manager with one trigger
  48390. **/
  48391. get: function () {
  48392. for (var t in ActionManager.Triggers) {
  48393. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48394. return true;
  48395. }
  48396. }
  48397. return false;
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48403. /**
  48404. * Does exist one action manager with at least one pick trigger
  48405. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48406. **/
  48407. get: function () {
  48408. for (var t in ActionManager.Triggers) {
  48409. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48410. var t_int = parseInt(t);
  48411. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48412. return true;
  48413. }
  48414. }
  48415. }
  48416. return false;
  48417. },
  48418. enumerable: true,
  48419. configurable: true
  48420. });
  48421. /**
  48422. * Does exist one action manager that handles actions of a given trigger
  48423. * @param {number} trigger - the trigger to be tested
  48424. * @return {boolean} whether the trigger is handeled by at least one action manager
  48425. **/
  48426. ActionManager.HasSpecificTrigger = function (trigger) {
  48427. for (var t in ActionManager.Triggers) {
  48428. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48429. var t_int = parseInt(t);
  48430. if (t_int === trigger) {
  48431. return true;
  48432. }
  48433. }
  48434. }
  48435. return false;
  48436. };
  48437. /**
  48438. * Registers an action to this action manager
  48439. * @param {BABYLON.Action} action - the action to be registered
  48440. * @return {BABYLON.Action} the action amended (prepared) after registration
  48441. */
  48442. ActionManager.prototype.registerAction = function (action) {
  48443. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48444. if (this.getScene().actionManager !== this) {
  48445. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48446. return null;
  48447. }
  48448. }
  48449. this.actions.push(action);
  48450. if (ActionManager.Triggers[action.trigger]) {
  48451. ActionManager.Triggers[action.trigger]++;
  48452. }
  48453. else {
  48454. ActionManager.Triggers[action.trigger] = 1;
  48455. }
  48456. action._actionManager = this;
  48457. action._prepare();
  48458. return action;
  48459. };
  48460. /**
  48461. * Unregisters an action to this action manager
  48462. * @param action The action to be unregistered
  48463. * @return whether the action has been unregistered
  48464. */
  48465. ActionManager.prototype.unregisterAction = function (action) {
  48466. var index = this.actions.indexOf(action);
  48467. if (index !== -1) {
  48468. this.actions.splice(index, 1);
  48469. ActionManager.Triggers[action.trigger] -= 1;
  48470. if (ActionManager.Triggers[action.trigger] === 0) {
  48471. delete ActionManager.Triggers[action.trigger];
  48472. }
  48473. delete action._actionManager;
  48474. return true;
  48475. }
  48476. return false;
  48477. };
  48478. /**
  48479. * Process a specific trigger
  48480. * @param {number} trigger - the trigger to process
  48481. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48482. */
  48483. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48484. for (var index = 0; index < this.actions.length; index++) {
  48485. var action = this.actions[index];
  48486. if (action.trigger === trigger) {
  48487. if (evt) {
  48488. if (trigger === ActionManager.OnKeyUpTrigger
  48489. || trigger === ActionManager.OnKeyDownTrigger) {
  48490. var parameter = action.getTriggerParameter();
  48491. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48492. if (!parameter.toLowerCase) {
  48493. continue;
  48494. }
  48495. var lowerCase = parameter.toLowerCase();
  48496. if (lowerCase !== evt.sourceEvent.key) {
  48497. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48498. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48499. if (actualkey !== lowerCase) {
  48500. continue;
  48501. }
  48502. }
  48503. }
  48504. }
  48505. }
  48506. action._executeCurrent(evt);
  48507. }
  48508. }
  48509. };
  48510. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48511. var properties = propertyPath.split(".");
  48512. for (var index = 0; index < properties.length - 1; index++) {
  48513. target = target[properties[index]];
  48514. }
  48515. return target;
  48516. };
  48517. ActionManager.prototype._getProperty = function (propertyPath) {
  48518. var properties = propertyPath.split(".");
  48519. return properties[properties.length - 1];
  48520. };
  48521. ActionManager.prototype.serialize = function (name) {
  48522. var root = {
  48523. children: new Array(),
  48524. name: name,
  48525. type: 3,
  48526. properties: new Array() // Empty for root but required
  48527. };
  48528. for (var i = 0; i < this.actions.length; i++) {
  48529. var triggerObject = {
  48530. type: 0,
  48531. children: new Array(),
  48532. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48533. properties: new Array()
  48534. };
  48535. var triggerOptions = this.actions[i].triggerOptions;
  48536. if (triggerOptions && typeof triggerOptions !== "number") {
  48537. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48538. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48539. }
  48540. else {
  48541. var parameter = {};
  48542. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48543. if (triggerOptions.parameter.mesh) {
  48544. parameter._meshId = triggerOptions.parameter.mesh.id;
  48545. }
  48546. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48547. }
  48548. }
  48549. // Serialize child action, recursively
  48550. this.actions[i].serialize(triggerObject);
  48551. // Add serialized trigger
  48552. root.children.push(triggerObject);
  48553. }
  48554. return root;
  48555. };
  48556. ActionManager.Parse = function (parsedActions, object, scene) {
  48557. var actionManager = new ActionManager(scene);
  48558. if (object === null)
  48559. scene.actionManager = actionManager;
  48560. else
  48561. object.actionManager = actionManager;
  48562. // instanciate a new object
  48563. var instanciate = function (name, params) {
  48564. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48565. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48566. newInstance.constructor.apply(newInstance, params);
  48567. return newInstance;
  48568. };
  48569. var parseParameter = function (name, value, target, propertyPath) {
  48570. if (propertyPath === null) {
  48571. // String, boolean or float
  48572. var floatValue = parseFloat(value);
  48573. if (value === "true" || value === "false")
  48574. return value === "true";
  48575. else
  48576. return isNaN(floatValue) ? value : floatValue;
  48577. }
  48578. var effectiveTarget = propertyPath.split(".");
  48579. var values = value.split(",");
  48580. // Get effective Target
  48581. for (var i = 0; i < effectiveTarget.length; i++) {
  48582. target = target[effectiveTarget[i]];
  48583. }
  48584. // Return appropriate value with its type
  48585. if (typeof (target) === "boolean")
  48586. return values[0] === "true";
  48587. if (typeof (target) === "string")
  48588. return values[0];
  48589. // Parameters with multiple values such as Vector3 etc.
  48590. var split = new Array();
  48591. for (var i = 0; i < values.length; i++)
  48592. split.push(parseFloat(values[i]));
  48593. if (target instanceof BABYLON.Vector3)
  48594. return BABYLON.Vector3.FromArray(split);
  48595. if (target instanceof BABYLON.Vector4)
  48596. return BABYLON.Vector4.FromArray(split);
  48597. if (target instanceof BABYLON.Color3)
  48598. return BABYLON.Color3.FromArray(split);
  48599. if (target instanceof BABYLON.Color4)
  48600. return BABYLON.Color4.FromArray(split);
  48601. return parseFloat(values[0]);
  48602. };
  48603. // traverse graph per trigger
  48604. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48605. if (combineArray === void 0) { combineArray = null; }
  48606. if (parsedAction.detached)
  48607. return;
  48608. var parameters = new Array();
  48609. var target = null;
  48610. var propertyPath = null;
  48611. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48612. // Parameters
  48613. if (parsedAction.type === 2)
  48614. parameters.push(actionManager);
  48615. else
  48616. parameters.push(trigger);
  48617. if (combine) {
  48618. var actions = new Array();
  48619. for (var j = 0; j < parsedAction.combine.length; j++) {
  48620. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48621. }
  48622. parameters.push(actions);
  48623. }
  48624. else {
  48625. for (var i = 0; i < parsedAction.properties.length; i++) {
  48626. var value = parsedAction.properties[i].value;
  48627. var name = parsedAction.properties[i].name;
  48628. var targetType = parsedAction.properties[i].targetType;
  48629. if (name === "target")
  48630. if (targetType !== null && targetType === "SceneProperties")
  48631. value = target = scene;
  48632. else
  48633. value = target = scene.getNodeByName(value);
  48634. else if (name === "parent")
  48635. value = scene.getNodeByName(value);
  48636. else if (name === "sound")
  48637. value = scene.getSoundByName(value);
  48638. else if (name !== "propertyPath") {
  48639. if (parsedAction.type === 2 && name === "operator")
  48640. value = BABYLON.ValueCondition[value];
  48641. else
  48642. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48643. }
  48644. else {
  48645. propertyPath = value;
  48646. }
  48647. parameters.push(value);
  48648. }
  48649. }
  48650. if (combineArray === null) {
  48651. parameters.push(condition);
  48652. }
  48653. else {
  48654. parameters.push(null);
  48655. }
  48656. // If interpolate value action
  48657. if (parsedAction.name === "InterpolateValueAction") {
  48658. var param = parameters[parameters.length - 2];
  48659. parameters[parameters.length - 1] = param;
  48660. parameters[parameters.length - 2] = condition;
  48661. }
  48662. // Action or condition(s) and not CombineAction
  48663. var newAction = instanciate(parsedAction.name, parameters);
  48664. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48665. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48666. if (action)
  48667. action.then(nothing);
  48668. else
  48669. actionManager.registerAction(nothing);
  48670. action = nothing;
  48671. }
  48672. if (combineArray === null) {
  48673. if (newAction instanceof BABYLON.Condition) {
  48674. condition = newAction;
  48675. newAction = action;
  48676. }
  48677. else {
  48678. condition = null;
  48679. if (action)
  48680. action.then(newAction);
  48681. else
  48682. actionManager.registerAction(newAction);
  48683. }
  48684. }
  48685. else {
  48686. combineArray.push(newAction);
  48687. }
  48688. for (var i = 0; i < parsedAction.children.length; i++)
  48689. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48690. };
  48691. // triggers
  48692. for (var i = 0; i < parsedActions.children.length; i++) {
  48693. var triggerParams;
  48694. var trigger = parsedActions.children[i];
  48695. if (trigger.properties.length > 0) {
  48696. var param = trigger.properties[0].value;
  48697. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48698. if (value._meshId) {
  48699. value.mesh = scene.getMeshByID(value._meshId);
  48700. }
  48701. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48702. }
  48703. else
  48704. triggerParams = ActionManager[trigger.name];
  48705. for (var j = 0; j < trigger.children.length; j++) {
  48706. if (!trigger.detached)
  48707. traverse(trigger.children[j], triggerParams, null, null);
  48708. }
  48709. }
  48710. };
  48711. ActionManager.GetTriggerName = function (trigger) {
  48712. switch (trigger) {
  48713. case 0: return "NothingTrigger";
  48714. case 1: return "OnPickTrigger";
  48715. case 2: return "OnLeftPickTrigger";
  48716. case 3: return "OnRightPickTrigger";
  48717. case 4: return "OnCenterPickTrigger";
  48718. case 5: return "OnPickDownTrigger";
  48719. case 6: return "OnPickUpTrigger";
  48720. case 7: return "OnLongPressTrigger";
  48721. case 8: return "OnPointerOverTrigger";
  48722. case 9: return "OnPointerOutTrigger";
  48723. case 10: return "OnEveryFrameTrigger";
  48724. case 11: return "OnIntersectionEnterTrigger";
  48725. case 12: return "OnIntersectionExitTrigger";
  48726. case 13: return "OnKeyDownTrigger";
  48727. case 14: return "OnKeyUpTrigger";
  48728. case 15: return "OnPickOutTrigger";
  48729. default: return "";
  48730. }
  48731. };
  48732. // Statics
  48733. ActionManager._NothingTrigger = 0;
  48734. ActionManager._OnPickTrigger = 1;
  48735. ActionManager._OnLeftPickTrigger = 2;
  48736. ActionManager._OnRightPickTrigger = 3;
  48737. ActionManager._OnCenterPickTrigger = 4;
  48738. ActionManager._OnPickDownTrigger = 5;
  48739. ActionManager._OnDoublePickTrigger = 6;
  48740. ActionManager._OnPickUpTrigger = 7;
  48741. ActionManager._OnLongPressTrigger = 8;
  48742. ActionManager._OnPointerOverTrigger = 9;
  48743. ActionManager._OnPointerOutTrigger = 10;
  48744. ActionManager._OnEveryFrameTrigger = 11;
  48745. ActionManager._OnIntersectionEnterTrigger = 12;
  48746. ActionManager._OnIntersectionExitTrigger = 13;
  48747. ActionManager._OnKeyDownTrigger = 14;
  48748. ActionManager._OnKeyUpTrigger = 15;
  48749. ActionManager._OnPickOutTrigger = 16;
  48750. ActionManager.Triggers = {};
  48751. return ActionManager;
  48752. }());
  48753. BABYLON.ActionManager = ActionManager;
  48754. })(BABYLON || (BABYLON = {}));
  48755. //# sourceMappingURL=babylon.actionManager.js.map
  48756. var BABYLON;
  48757. (function (BABYLON) {
  48758. var InterpolateValueAction = /** @class */ (function (_super) {
  48759. __extends(InterpolateValueAction, _super);
  48760. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48761. if (duration === void 0) { duration = 1000; }
  48762. var _this = _super.call(this, triggerOptions, condition) || this;
  48763. _this.propertyPath = propertyPath;
  48764. _this.value = value;
  48765. _this.duration = duration;
  48766. _this.stopOtherAnimations = stopOtherAnimations;
  48767. _this.onInterpolationDone = onInterpolationDone;
  48768. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48769. _this._target = _this._effectiveTarget = target;
  48770. return _this;
  48771. }
  48772. InterpolateValueAction.prototype._prepare = function () {
  48773. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48774. this._property = this._getProperty(this.propertyPath);
  48775. };
  48776. InterpolateValueAction.prototype.execute = function () {
  48777. var _this = this;
  48778. var scene = this._actionManager.getScene();
  48779. var keys = [
  48780. {
  48781. frame: 0,
  48782. value: this._effectiveTarget[this._property]
  48783. }, {
  48784. frame: 100,
  48785. value: this.value
  48786. }
  48787. ];
  48788. var dataType;
  48789. if (typeof this.value === "number") {
  48790. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48791. }
  48792. else if (this.value instanceof BABYLON.Color3) {
  48793. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48794. }
  48795. else if (this.value instanceof BABYLON.Vector3) {
  48796. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48797. }
  48798. else if (this.value instanceof BABYLON.Matrix) {
  48799. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48800. }
  48801. else if (this.value instanceof BABYLON.Quaternion) {
  48802. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48803. }
  48804. else {
  48805. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48806. return;
  48807. }
  48808. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48809. animation.setKeys(keys);
  48810. if (this.stopOtherAnimations) {
  48811. scene.stopAnimation(this._effectiveTarget);
  48812. }
  48813. var wrapper = function () {
  48814. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48815. if (_this.onInterpolationDone) {
  48816. _this.onInterpolationDone();
  48817. }
  48818. };
  48819. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48820. };
  48821. InterpolateValueAction.prototype.serialize = function (parent) {
  48822. return _super.prototype._serialize.call(this, {
  48823. name: "InterpolateValueAction",
  48824. properties: [
  48825. BABYLON.Action._GetTargetProperty(this._target),
  48826. { name: "propertyPath", value: this.propertyPath },
  48827. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48828. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48829. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48830. ]
  48831. }, parent);
  48832. };
  48833. return InterpolateValueAction;
  48834. }(BABYLON.Action));
  48835. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48836. })(BABYLON || (BABYLON = {}));
  48837. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48838. var BABYLON;
  48839. (function (BABYLON) {
  48840. var SwitchBooleanAction = /** @class */ (function (_super) {
  48841. __extends(SwitchBooleanAction, _super);
  48842. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48843. var _this = _super.call(this, triggerOptions, condition) || this;
  48844. _this.propertyPath = propertyPath;
  48845. _this._target = _this._effectiveTarget = target;
  48846. return _this;
  48847. }
  48848. SwitchBooleanAction.prototype._prepare = function () {
  48849. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48850. this._property = this._getProperty(this.propertyPath);
  48851. };
  48852. SwitchBooleanAction.prototype.execute = function () {
  48853. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48854. };
  48855. SwitchBooleanAction.prototype.serialize = function (parent) {
  48856. return _super.prototype._serialize.call(this, {
  48857. name: "SwitchBooleanAction",
  48858. properties: [
  48859. BABYLON.Action._GetTargetProperty(this._target),
  48860. { name: "propertyPath", value: this.propertyPath }
  48861. ]
  48862. }, parent);
  48863. };
  48864. return SwitchBooleanAction;
  48865. }(BABYLON.Action));
  48866. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48867. var SetStateAction = /** @class */ (function (_super) {
  48868. __extends(SetStateAction, _super);
  48869. function SetStateAction(triggerOptions, target, value, condition) {
  48870. var _this = _super.call(this, triggerOptions, condition) || this;
  48871. _this.value = value;
  48872. _this._target = target;
  48873. return _this;
  48874. }
  48875. SetStateAction.prototype.execute = function () {
  48876. this._target.state = this.value;
  48877. };
  48878. SetStateAction.prototype.serialize = function (parent) {
  48879. return _super.prototype._serialize.call(this, {
  48880. name: "SetStateAction",
  48881. properties: [
  48882. BABYLON.Action._GetTargetProperty(this._target),
  48883. { name: "value", value: this.value }
  48884. ]
  48885. }, parent);
  48886. };
  48887. return SetStateAction;
  48888. }(BABYLON.Action));
  48889. BABYLON.SetStateAction = SetStateAction;
  48890. var SetValueAction = /** @class */ (function (_super) {
  48891. __extends(SetValueAction, _super);
  48892. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48893. var _this = _super.call(this, triggerOptions, condition) || this;
  48894. _this.propertyPath = propertyPath;
  48895. _this.value = value;
  48896. _this._target = _this._effectiveTarget = target;
  48897. return _this;
  48898. }
  48899. SetValueAction.prototype._prepare = function () {
  48900. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48901. this._property = this._getProperty(this.propertyPath);
  48902. };
  48903. SetValueAction.prototype.execute = function () {
  48904. this._effectiveTarget[this._property] = this.value;
  48905. if (this._target.markAsDirty) {
  48906. this._target.markAsDirty(this._property);
  48907. }
  48908. };
  48909. SetValueAction.prototype.serialize = function (parent) {
  48910. return _super.prototype._serialize.call(this, {
  48911. name: "SetValueAction",
  48912. properties: [
  48913. BABYLON.Action._GetTargetProperty(this._target),
  48914. { name: "propertyPath", value: this.propertyPath },
  48915. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48916. ]
  48917. }, parent);
  48918. };
  48919. return SetValueAction;
  48920. }(BABYLON.Action));
  48921. BABYLON.SetValueAction = SetValueAction;
  48922. var IncrementValueAction = /** @class */ (function (_super) {
  48923. __extends(IncrementValueAction, _super);
  48924. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48925. var _this = _super.call(this, triggerOptions, condition) || this;
  48926. _this.propertyPath = propertyPath;
  48927. _this.value = value;
  48928. _this._target = _this._effectiveTarget = target;
  48929. return _this;
  48930. }
  48931. IncrementValueAction.prototype._prepare = function () {
  48932. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48933. this._property = this._getProperty(this.propertyPath);
  48934. if (typeof this._effectiveTarget[this._property] !== "number") {
  48935. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48936. }
  48937. };
  48938. IncrementValueAction.prototype.execute = function () {
  48939. this._effectiveTarget[this._property] += this.value;
  48940. if (this._target.markAsDirty) {
  48941. this._target.markAsDirty(this._property);
  48942. }
  48943. };
  48944. IncrementValueAction.prototype.serialize = function (parent) {
  48945. return _super.prototype._serialize.call(this, {
  48946. name: "IncrementValueAction",
  48947. properties: [
  48948. BABYLON.Action._GetTargetProperty(this._target),
  48949. { name: "propertyPath", value: this.propertyPath },
  48950. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48951. ]
  48952. }, parent);
  48953. };
  48954. return IncrementValueAction;
  48955. }(BABYLON.Action));
  48956. BABYLON.IncrementValueAction = IncrementValueAction;
  48957. var PlayAnimationAction = /** @class */ (function (_super) {
  48958. __extends(PlayAnimationAction, _super);
  48959. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48960. var _this = _super.call(this, triggerOptions, condition) || this;
  48961. _this.from = from;
  48962. _this.to = to;
  48963. _this.loop = loop;
  48964. _this._target = target;
  48965. return _this;
  48966. }
  48967. PlayAnimationAction.prototype._prepare = function () {
  48968. };
  48969. PlayAnimationAction.prototype.execute = function () {
  48970. var scene = this._actionManager.getScene();
  48971. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48972. };
  48973. PlayAnimationAction.prototype.serialize = function (parent) {
  48974. return _super.prototype._serialize.call(this, {
  48975. name: "PlayAnimationAction",
  48976. properties: [
  48977. BABYLON.Action._GetTargetProperty(this._target),
  48978. { name: "from", value: String(this.from) },
  48979. { name: "to", value: String(this.to) },
  48980. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48981. ]
  48982. }, parent);
  48983. };
  48984. return PlayAnimationAction;
  48985. }(BABYLON.Action));
  48986. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48987. var StopAnimationAction = /** @class */ (function (_super) {
  48988. __extends(StopAnimationAction, _super);
  48989. function StopAnimationAction(triggerOptions, target, condition) {
  48990. var _this = _super.call(this, triggerOptions, condition) || this;
  48991. _this._target = target;
  48992. return _this;
  48993. }
  48994. StopAnimationAction.prototype._prepare = function () {
  48995. };
  48996. StopAnimationAction.prototype.execute = function () {
  48997. var scene = this._actionManager.getScene();
  48998. scene.stopAnimation(this._target);
  48999. };
  49000. StopAnimationAction.prototype.serialize = function (parent) {
  49001. return _super.prototype._serialize.call(this, {
  49002. name: "StopAnimationAction",
  49003. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49004. }, parent);
  49005. };
  49006. return StopAnimationAction;
  49007. }(BABYLON.Action));
  49008. BABYLON.StopAnimationAction = StopAnimationAction;
  49009. var DoNothingAction = /** @class */ (function (_super) {
  49010. __extends(DoNothingAction, _super);
  49011. function DoNothingAction(triggerOptions, condition) {
  49012. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49013. return _super.call(this, triggerOptions, condition) || this;
  49014. }
  49015. DoNothingAction.prototype.execute = function () {
  49016. };
  49017. DoNothingAction.prototype.serialize = function (parent) {
  49018. return _super.prototype._serialize.call(this, {
  49019. name: "DoNothingAction",
  49020. properties: []
  49021. }, parent);
  49022. };
  49023. return DoNothingAction;
  49024. }(BABYLON.Action));
  49025. BABYLON.DoNothingAction = DoNothingAction;
  49026. var CombineAction = /** @class */ (function (_super) {
  49027. __extends(CombineAction, _super);
  49028. function CombineAction(triggerOptions, children, condition) {
  49029. var _this = _super.call(this, triggerOptions, condition) || this;
  49030. _this.children = children;
  49031. return _this;
  49032. }
  49033. CombineAction.prototype._prepare = function () {
  49034. for (var index = 0; index < this.children.length; index++) {
  49035. this.children[index]._actionManager = this._actionManager;
  49036. this.children[index]._prepare();
  49037. }
  49038. };
  49039. CombineAction.prototype.execute = function (evt) {
  49040. for (var index = 0; index < this.children.length; index++) {
  49041. this.children[index].execute(evt);
  49042. }
  49043. };
  49044. CombineAction.prototype.serialize = function (parent) {
  49045. var serializationObject = _super.prototype._serialize.call(this, {
  49046. name: "CombineAction",
  49047. properties: [],
  49048. combine: []
  49049. }, parent);
  49050. for (var i = 0; i < this.children.length; i++) {
  49051. serializationObject.combine.push(this.children[i].serialize(null));
  49052. }
  49053. return serializationObject;
  49054. };
  49055. return CombineAction;
  49056. }(BABYLON.Action));
  49057. BABYLON.CombineAction = CombineAction;
  49058. var ExecuteCodeAction = /** @class */ (function (_super) {
  49059. __extends(ExecuteCodeAction, _super);
  49060. function ExecuteCodeAction(triggerOptions, func, condition) {
  49061. var _this = _super.call(this, triggerOptions, condition) || this;
  49062. _this.func = func;
  49063. return _this;
  49064. }
  49065. ExecuteCodeAction.prototype.execute = function (evt) {
  49066. this.func(evt);
  49067. };
  49068. return ExecuteCodeAction;
  49069. }(BABYLON.Action));
  49070. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49071. var SetParentAction = /** @class */ (function (_super) {
  49072. __extends(SetParentAction, _super);
  49073. function SetParentAction(triggerOptions, target, parent, condition) {
  49074. var _this = _super.call(this, triggerOptions, condition) || this;
  49075. _this._target = target;
  49076. _this._parent = parent;
  49077. return _this;
  49078. }
  49079. SetParentAction.prototype._prepare = function () {
  49080. };
  49081. SetParentAction.prototype.execute = function () {
  49082. if (this._target.parent === this._parent) {
  49083. return;
  49084. }
  49085. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49086. invertParentWorldMatrix.invert();
  49087. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49088. this._target.parent = this._parent;
  49089. };
  49090. SetParentAction.prototype.serialize = function (parent) {
  49091. return _super.prototype._serialize.call(this, {
  49092. name: "SetParentAction",
  49093. properties: [
  49094. BABYLON.Action._GetTargetProperty(this._target),
  49095. BABYLON.Action._GetTargetProperty(this._parent),
  49096. ]
  49097. }, parent);
  49098. };
  49099. return SetParentAction;
  49100. }(BABYLON.Action));
  49101. BABYLON.SetParentAction = SetParentAction;
  49102. var PlaySoundAction = /** @class */ (function (_super) {
  49103. __extends(PlaySoundAction, _super);
  49104. function PlaySoundAction(triggerOptions, sound, condition) {
  49105. var _this = _super.call(this, triggerOptions, condition) || this;
  49106. _this._sound = sound;
  49107. return _this;
  49108. }
  49109. PlaySoundAction.prototype._prepare = function () {
  49110. };
  49111. PlaySoundAction.prototype.execute = function () {
  49112. if (this._sound !== undefined)
  49113. this._sound.play();
  49114. };
  49115. PlaySoundAction.prototype.serialize = function (parent) {
  49116. return _super.prototype._serialize.call(this, {
  49117. name: "PlaySoundAction",
  49118. properties: [{ name: "sound", value: this._sound.name }]
  49119. }, parent);
  49120. };
  49121. return PlaySoundAction;
  49122. }(BABYLON.Action));
  49123. BABYLON.PlaySoundAction = PlaySoundAction;
  49124. var StopSoundAction = /** @class */ (function (_super) {
  49125. __extends(StopSoundAction, _super);
  49126. function StopSoundAction(triggerOptions, sound, condition) {
  49127. var _this = _super.call(this, triggerOptions, condition) || this;
  49128. _this._sound = sound;
  49129. return _this;
  49130. }
  49131. StopSoundAction.prototype._prepare = function () {
  49132. };
  49133. StopSoundAction.prototype.execute = function () {
  49134. if (this._sound !== undefined)
  49135. this._sound.stop();
  49136. };
  49137. StopSoundAction.prototype.serialize = function (parent) {
  49138. return _super.prototype._serialize.call(this, {
  49139. name: "StopSoundAction",
  49140. properties: [{ name: "sound", value: this._sound.name }]
  49141. }, parent);
  49142. };
  49143. return StopSoundAction;
  49144. }(BABYLON.Action));
  49145. BABYLON.StopSoundAction = StopSoundAction;
  49146. })(BABYLON || (BABYLON = {}));
  49147. //# sourceMappingURL=babylon.directActions.js.map
  49148. var BABYLON;
  49149. (function (BABYLON) {
  49150. var SpriteManager = /** @class */ (function () {
  49151. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49152. if (epsilon === void 0) { epsilon = 0.01; }
  49153. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49154. this.name = name;
  49155. this.sprites = new Array();
  49156. this.renderingGroupId = 0;
  49157. this.layerMask = 0x0FFFFFFF;
  49158. this.fogEnabled = true;
  49159. this.isPickable = false;
  49160. /**
  49161. * An event triggered when the manager is disposed.
  49162. * @type {BABYLON.Observable}
  49163. */
  49164. this.onDisposeObservable = new BABYLON.Observable();
  49165. this._vertexBuffers = {};
  49166. this._capacity = capacity;
  49167. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49168. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49169. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49170. if (cellSize.width && cellSize.height) {
  49171. this.cellWidth = cellSize.width;
  49172. this.cellHeight = cellSize.height;
  49173. }
  49174. else if (cellSize !== undefined) {
  49175. this.cellWidth = cellSize;
  49176. this.cellHeight = cellSize;
  49177. }
  49178. else {
  49179. return;
  49180. }
  49181. this._epsilon = epsilon;
  49182. this._scene = scene;
  49183. this._scene.spriteManagers.push(this);
  49184. var indices = [];
  49185. var index = 0;
  49186. for (var count = 0; count < capacity; count++) {
  49187. indices.push(index);
  49188. indices.push(index + 1);
  49189. indices.push(index + 2);
  49190. indices.push(index);
  49191. indices.push(index + 2);
  49192. indices.push(index + 3);
  49193. index += 4;
  49194. }
  49195. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49196. // VBO
  49197. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49198. this._vertexData = new Float32Array(capacity * 16 * 4);
  49199. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49200. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49201. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49202. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49203. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49204. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49205. this._vertexBuffers["options"] = options;
  49206. this._vertexBuffers["cellInfo"] = cellInfo;
  49207. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49208. // Effects
  49209. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49210. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49211. }
  49212. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49213. set: function (callback) {
  49214. if (this._onDisposeObserver) {
  49215. this.onDisposeObservable.remove(this._onDisposeObserver);
  49216. }
  49217. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(SpriteManager.prototype, "texture", {
  49223. get: function () {
  49224. return this._spriteTexture;
  49225. },
  49226. set: function (value) {
  49227. this._spriteTexture = value;
  49228. },
  49229. enumerable: true,
  49230. configurable: true
  49231. });
  49232. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49233. var arrayOffset = index * 16;
  49234. if (offsetX === 0)
  49235. offsetX = this._epsilon;
  49236. else if (offsetX === 1)
  49237. offsetX = 1 - this._epsilon;
  49238. if (offsetY === 0)
  49239. offsetY = this._epsilon;
  49240. else if (offsetY === 1)
  49241. offsetY = 1 - this._epsilon;
  49242. this._vertexData[arrayOffset] = sprite.position.x;
  49243. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49244. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49245. this._vertexData[arrayOffset + 3] = sprite.angle;
  49246. this._vertexData[arrayOffset + 4] = sprite.width;
  49247. this._vertexData[arrayOffset + 5] = sprite.height;
  49248. this._vertexData[arrayOffset + 6] = offsetX;
  49249. this._vertexData[arrayOffset + 7] = offsetY;
  49250. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49251. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49252. var offset = (sprite.cellIndex / rowSize) >> 0;
  49253. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49254. this._vertexData[arrayOffset + 11] = offset;
  49255. // Color
  49256. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49257. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49258. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49259. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49260. };
  49261. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49262. var count = Math.min(this._capacity, this.sprites.length);
  49263. var min = BABYLON.Vector3.Zero();
  49264. var max = BABYLON.Vector3.Zero();
  49265. var distance = Number.MAX_VALUE;
  49266. var currentSprite = null;
  49267. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49268. var cameraView = camera.getViewMatrix();
  49269. for (var index = 0; index < count; index++) {
  49270. var sprite = this.sprites[index];
  49271. if (!sprite) {
  49272. continue;
  49273. }
  49274. if (predicate) {
  49275. if (!predicate(sprite)) {
  49276. continue;
  49277. }
  49278. }
  49279. else if (!sprite.isPickable) {
  49280. continue;
  49281. }
  49282. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49283. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49284. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49285. if (ray.intersectsBoxMinMax(min, max)) {
  49286. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49287. if (distance > currentDistance) {
  49288. distance = currentDistance;
  49289. currentSprite = sprite;
  49290. if (fastCheck) {
  49291. break;
  49292. }
  49293. }
  49294. }
  49295. }
  49296. if (currentSprite) {
  49297. var result = new BABYLON.PickingInfo();
  49298. result.hit = true;
  49299. result.pickedSprite = currentSprite;
  49300. result.distance = distance;
  49301. return result;
  49302. }
  49303. return null;
  49304. };
  49305. SpriteManager.prototype.render = function () {
  49306. // Check
  49307. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49308. return;
  49309. var engine = this._scene.getEngine();
  49310. var baseSize = this._spriteTexture.getBaseSize();
  49311. // Sprites
  49312. var deltaTime = engine.getDeltaTime();
  49313. var max = Math.min(this._capacity, this.sprites.length);
  49314. var rowSize = baseSize.width / this.cellWidth;
  49315. var offset = 0;
  49316. for (var index = 0; index < max; index++) {
  49317. var sprite = this.sprites[index];
  49318. if (!sprite) {
  49319. continue;
  49320. }
  49321. sprite._animate(deltaTime);
  49322. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49323. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49324. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49325. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49326. }
  49327. this._buffer.update(this._vertexData);
  49328. // Render
  49329. var effect = this._effectBase;
  49330. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49331. effect = this._effectFog;
  49332. }
  49333. engine.enableEffect(effect);
  49334. var viewMatrix = this._scene.getViewMatrix();
  49335. effect.setTexture("diffuseSampler", this._spriteTexture);
  49336. effect.setMatrix("view", viewMatrix);
  49337. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49338. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49339. // Fog
  49340. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49341. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49342. effect.setColor3("vFogColor", this._scene.fogColor);
  49343. }
  49344. // VBOs
  49345. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49346. // Draw order
  49347. engine.setDepthFunctionToLessOrEqual();
  49348. effect.setBool("alphaTest", true);
  49349. engine.setColorWrite(false);
  49350. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49351. engine.setColorWrite(true);
  49352. effect.setBool("alphaTest", false);
  49353. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49354. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49355. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49356. };
  49357. SpriteManager.prototype.dispose = function () {
  49358. if (this._buffer) {
  49359. this._buffer.dispose();
  49360. this._buffer = null;
  49361. }
  49362. if (this._indexBuffer) {
  49363. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49364. this._indexBuffer = null;
  49365. }
  49366. if (this._spriteTexture) {
  49367. this._spriteTexture.dispose();
  49368. this._spriteTexture = null;
  49369. }
  49370. // Remove from scene
  49371. var index = this._scene.spriteManagers.indexOf(this);
  49372. this._scene.spriteManagers.splice(index, 1);
  49373. // Callback
  49374. this.onDisposeObservable.notifyObservers(this);
  49375. this.onDisposeObservable.clear();
  49376. };
  49377. return SpriteManager;
  49378. }());
  49379. BABYLON.SpriteManager = SpriteManager;
  49380. })(BABYLON || (BABYLON = {}));
  49381. //# sourceMappingURL=babylon.spriteManager.js.map
  49382. var BABYLON;
  49383. (function (BABYLON) {
  49384. var Sprite = /** @class */ (function () {
  49385. function Sprite(name, manager) {
  49386. this.name = name;
  49387. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49388. this.width = 1.0;
  49389. this.height = 1.0;
  49390. this.angle = 0;
  49391. this.cellIndex = 0;
  49392. this.invertU = 0;
  49393. this.invertV = 0;
  49394. this.animations = new Array();
  49395. this.isPickable = false;
  49396. this._animationStarted = false;
  49397. this._loopAnimation = false;
  49398. this._fromIndex = 0;
  49399. this._toIndex = 0;
  49400. this._delay = 0;
  49401. this._direction = 1;
  49402. this._time = 0;
  49403. this._manager = manager;
  49404. this._manager.sprites.push(this);
  49405. this.position = BABYLON.Vector3.Zero();
  49406. }
  49407. Object.defineProperty(Sprite.prototype, "size", {
  49408. get: function () {
  49409. return this.width;
  49410. },
  49411. set: function (value) {
  49412. this.width = value;
  49413. this.height = value;
  49414. },
  49415. enumerable: true,
  49416. configurable: true
  49417. });
  49418. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49419. this._fromIndex = from;
  49420. this._toIndex = to;
  49421. this._loopAnimation = loop;
  49422. this._delay = delay;
  49423. this._animationStarted = true;
  49424. this._direction = from < to ? 1 : -1;
  49425. this.cellIndex = from;
  49426. this._time = 0;
  49427. this._onAnimationEnd = onAnimationEnd;
  49428. };
  49429. Sprite.prototype.stopAnimation = function () {
  49430. this._animationStarted = false;
  49431. };
  49432. Sprite.prototype._animate = function (deltaTime) {
  49433. if (!this._animationStarted)
  49434. return;
  49435. this._time += deltaTime;
  49436. if (this._time > this._delay) {
  49437. this._time = this._time % this._delay;
  49438. this.cellIndex += this._direction;
  49439. if (this.cellIndex > this._toIndex) {
  49440. if (this._loopAnimation) {
  49441. this.cellIndex = this._fromIndex;
  49442. }
  49443. else {
  49444. this.cellIndex = this._toIndex;
  49445. this._animationStarted = false;
  49446. if (this._onAnimationEnd) {
  49447. this._onAnimationEnd();
  49448. }
  49449. if (this.disposeWhenFinishedAnimating) {
  49450. this.dispose();
  49451. }
  49452. }
  49453. }
  49454. }
  49455. };
  49456. Sprite.prototype.dispose = function () {
  49457. for (var i = 0; i < this._manager.sprites.length; i++) {
  49458. if (this._manager.sprites[i] == this) {
  49459. this._manager.sprites.splice(i, 1);
  49460. }
  49461. }
  49462. };
  49463. return Sprite;
  49464. }());
  49465. BABYLON.Sprite = Sprite;
  49466. })(BABYLON || (BABYLON = {}));
  49467. //# sourceMappingURL=babylon.sprite.js.map
  49468. var BABYLON;
  49469. (function (BABYLON) {
  49470. var IntersectionInfo = /** @class */ (function () {
  49471. function IntersectionInfo(bu, bv, distance) {
  49472. this.bu = bu;
  49473. this.bv = bv;
  49474. this.distance = distance;
  49475. this.faceId = 0;
  49476. this.subMeshId = 0;
  49477. }
  49478. return IntersectionInfo;
  49479. }());
  49480. BABYLON.IntersectionInfo = IntersectionInfo;
  49481. var PickingInfo = /** @class */ (function () {
  49482. function PickingInfo() {
  49483. this.hit = false;
  49484. this.distance = 0;
  49485. this.pickedPoint = null;
  49486. this.pickedMesh = null;
  49487. this.bu = 0;
  49488. this.bv = 0;
  49489. this.faceId = -1;
  49490. this.subMeshId = 0;
  49491. this.pickedSprite = null;
  49492. }
  49493. // Methods
  49494. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49495. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49496. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49497. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49498. return null;
  49499. }
  49500. var indices = this.pickedMesh.getIndices();
  49501. if (!indices) {
  49502. return null;
  49503. }
  49504. var result;
  49505. if (useVerticesNormals) {
  49506. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49507. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49508. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49509. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49510. normal0 = normal0.scale(this.bu);
  49511. normal1 = normal1.scale(this.bv);
  49512. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49513. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49514. }
  49515. else {
  49516. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49517. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49518. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49519. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49520. var p1p2 = vertex1.subtract(vertex2);
  49521. var p3p2 = vertex3.subtract(vertex2);
  49522. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49523. }
  49524. if (useWorldCoordinates) {
  49525. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49526. }
  49527. return BABYLON.Vector3.Normalize(result);
  49528. };
  49529. PickingInfo.prototype.getTextureCoordinates = function () {
  49530. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49531. return null;
  49532. }
  49533. var indices = this.pickedMesh.getIndices();
  49534. if (!indices) {
  49535. return null;
  49536. }
  49537. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49538. if (!uvs) {
  49539. return null;
  49540. }
  49541. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49542. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49543. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49544. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49545. uv1 = uv1.scale(this.bu);
  49546. uv2 = uv2.scale(this.bv);
  49547. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49548. };
  49549. return PickingInfo;
  49550. }());
  49551. BABYLON.PickingInfo = PickingInfo;
  49552. })(BABYLON || (BABYLON = {}));
  49553. //# sourceMappingURL=babylon.pickingInfo.js.map
  49554. var BABYLON;
  49555. (function (BABYLON) {
  49556. var Ray = /** @class */ (function () {
  49557. function Ray(origin, direction, length) {
  49558. if (length === void 0) { length = Number.MAX_VALUE; }
  49559. this.origin = origin;
  49560. this.direction = direction;
  49561. this.length = length;
  49562. }
  49563. // Methods
  49564. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49565. var d = 0.0;
  49566. var maxValue = Number.MAX_VALUE;
  49567. var inv;
  49568. var min;
  49569. var max;
  49570. var temp;
  49571. if (Math.abs(this.direction.x) < 0.0000001) {
  49572. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49573. return false;
  49574. }
  49575. }
  49576. else {
  49577. inv = 1.0 / this.direction.x;
  49578. min = (minimum.x - this.origin.x) * inv;
  49579. max = (maximum.x - this.origin.x) * inv;
  49580. if (max === -Infinity) {
  49581. max = Infinity;
  49582. }
  49583. if (min > max) {
  49584. temp = min;
  49585. min = max;
  49586. max = temp;
  49587. }
  49588. d = Math.max(min, d);
  49589. maxValue = Math.min(max, maxValue);
  49590. if (d > maxValue) {
  49591. return false;
  49592. }
  49593. }
  49594. if (Math.abs(this.direction.y) < 0.0000001) {
  49595. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49596. return false;
  49597. }
  49598. }
  49599. else {
  49600. inv = 1.0 / this.direction.y;
  49601. min = (minimum.y - this.origin.y) * inv;
  49602. max = (maximum.y - this.origin.y) * inv;
  49603. if (max === -Infinity) {
  49604. max = Infinity;
  49605. }
  49606. if (min > max) {
  49607. temp = min;
  49608. min = max;
  49609. max = temp;
  49610. }
  49611. d = Math.max(min, d);
  49612. maxValue = Math.min(max, maxValue);
  49613. if (d > maxValue) {
  49614. return false;
  49615. }
  49616. }
  49617. if (Math.abs(this.direction.z) < 0.0000001) {
  49618. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49619. return false;
  49620. }
  49621. }
  49622. else {
  49623. inv = 1.0 / this.direction.z;
  49624. min = (minimum.z - this.origin.z) * inv;
  49625. max = (maximum.z - this.origin.z) * inv;
  49626. if (max === -Infinity) {
  49627. max = Infinity;
  49628. }
  49629. if (min > max) {
  49630. temp = min;
  49631. min = max;
  49632. max = temp;
  49633. }
  49634. d = Math.max(min, d);
  49635. maxValue = Math.min(max, maxValue);
  49636. if (d > maxValue) {
  49637. return false;
  49638. }
  49639. }
  49640. return true;
  49641. };
  49642. Ray.prototype.intersectsBox = function (box) {
  49643. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49644. };
  49645. Ray.prototype.intersectsSphere = function (sphere) {
  49646. var x = sphere.center.x - this.origin.x;
  49647. var y = sphere.center.y - this.origin.y;
  49648. var z = sphere.center.z - this.origin.z;
  49649. var pyth = (x * x) + (y * y) + (z * z);
  49650. var rr = sphere.radius * sphere.radius;
  49651. if (pyth <= rr) {
  49652. return true;
  49653. }
  49654. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49655. if (dot < 0.0) {
  49656. return false;
  49657. }
  49658. var temp = pyth - (dot * dot);
  49659. return temp <= rr;
  49660. };
  49661. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49662. if (!this._edge1) {
  49663. this._edge1 = BABYLON.Vector3.Zero();
  49664. this._edge2 = BABYLON.Vector3.Zero();
  49665. this._pvec = BABYLON.Vector3.Zero();
  49666. this._tvec = BABYLON.Vector3.Zero();
  49667. this._qvec = BABYLON.Vector3.Zero();
  49668. }
  49669. vertex1.subtractToRef(vertex0, this._edge1);
  49670. vertex2.subtractToRef(vertex0, this._edge2);
  49671. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49672. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49673. if (det === 0) {
  49674. return null;
  49675. }
  49676. var invdet = 1 / det;
  49677. this.origin.subtractToRef(vertex0, this._tvec);
  49678. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49679. if (bu < 0 || bu > 1.0) {
  49680. return null;
  49681. }
  49682. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49683. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49684. if (bv < 0 || bu + bv > 1.0) {
  49685. return null;
  49686. }
  49687. //check if the distance is longer than the predefined length.
  49688. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49689. if (distance > this.length) {
  49690. return null;
  49691. }
  49692. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49693. };
  49694. Ray.prototype.intersectsPlane = function (plane) {
  49695. var distance;
  49696. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49697. if (Math.abs(result1) < 9.99999997475243E-07) {
  49698. return null;
  49699. }
  49700. else {
  49701. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49702. distance = (-plane.d - result2) / result1;
  49703. if (distance < 0.0) {
  49704. if (distance < -9.99999997475243E-07) {
  49705. return null;
  49706. }
  49707. else {
  49708. return 0;
  49709. }
  49710. }
  49711. return distance;
  49712. }
  49713. };
  49714. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49715. var tm = BABYLON.Tmp.Matrix[0];
  49716. mesh.getWorldMatrix().invertToRef(tm);
  49717. if (this._tmpRay) {
  49718. Ray.TransformToRef(this, tm, this._tmpRay);
  49719. }
  49720. else {
  49721. this._tmpRay = Ray.Transform(this, tm);
  49722. }
  49723. return mesh.intersects(this._tmpRay, fastCheck);
  49724. };
  49725. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49726. if (results) {
  49727. results.length = 0;
  49728. }
  49729. else {
  49730. results = [];
  49731. }
  49732. for (var i = 0; i < meshes.length; i++) {
  49733. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49734. if (pickInfo.hit) {
  49735. results.push(pickInfo);
  49736. }
  49737. }
  49738. results.sort(this._comparePickingInfo);
  49739. return results;
  49740. };
  49741. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49742. if (pickingInfoA.distance < pickingInfoB.distance) {
  49743. return -1;
  49744. }
  49745. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49746. return 1;
  49747. }
  49748. else {
  49749. return 0;
  49750. }
  49751. };
  49752. /**
  49753. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49754. * @param sega the first point of the segment to test the intersection against
  49755. * @param segb the second point of the segment to test the intersection against
  49756. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49757. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49758. */
  49759. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49760. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49761. var u = segb.subtract(sega);
  49762. var v = rsegb.subtract(this.origin);
  49763. var w = sega.subtract(this.origin);
  49764. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49765. var b = BABYLON.Vector3.Dot(u, v);
  49766. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49767. var d = BABYLON.Vector3.Dot(u, w);
  49768. var e = BABYLON.Vector3.Dot(v, w);
  49769. var D = a * c - b * b; // always >= 0
  49770. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49771. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49772. // compute the line parameters of the two closest points
  49773. if (D < Ray.smallnum) {
  49774. sN = 0.0; // force using point P0 on segment S1
  49775. sD = 1.0; // to prevent possible division by 0.0 later
  49776. tN = e;
  49777. tD = c;
  49778. }
  49779. else {
  49780. sN = (b * e - c * d);
  49781. tN = (a * e - b * d);
  49782. if (sN < 0.0) {
  49783. sN = 0.0;
  49784. tN = e;
  49785. tD = c;
  49786. }
  49787. else if (sN > sD) {
  49788. sN = sD;
  49789. tN = e + b;
  49790. tD = c;
  49791. }
  49792. }
  49793. if (tN < 0.0) {
  49794. tN = 0.0;
  49795. // recompute sc for this edge
  49796. if (-d < 0.0) {
  49797. sN = 0.0;
  49798. }
  49799. else if (-d > a)
  49800. sN = sD;
  49801. else {
  49802. sN = -d;
  49803. sD = a;
  49804. }
  49805. }
  49806. else if (tN > tD) {
  49807. tN = tD;
  49808. // recompute sc for this edge
  49809. if ((-d + b) < 0.0) {
  49810. sN = 0;
  49811. }
  49812. else if ((-d + b) > a) {
  49813. sN = sD;
  49814. }
  49815. else {
  49816. sN = (-d + b);
  49817. sD = a;
  49818. }
  49819. }
  49820. // finally do the division to get sc and tc
  49821. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49822. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49823. // get the difference of the two closest points
  49824. var qtc = v.multiplyByFloats(tc, tc, tc);
  49825. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49826. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49827. if (isIntersected) {
  49828. return qtc.length();
  49829. }
  49830. return -1;
  49831. };
  49832. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49833. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49834. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49835. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49836. this.direction.normalize();
  49837. return this;
  49838. };
  49839. // Statics
  49840. Ray.Zero = function () {
  49841. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49842. };
  49843. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49844. var result = Ray.Zero();
  49845. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49846. };
  49847. /**
  49848. * 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
  49849. * transformed to the given world matrix.
  49850. * @param origin The origin point
  49851. * @param end The end point
  49852. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49853. */
  49854. Ray.CreateNewFromTo = function (origin, end, world) {
  49855. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49856. var direction = end.subtract(origin);
  49857. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49858. direction.normalize();
  49859. return Ray.Transform(new Ray(origin, direction, length), world);
  49860. };
  49861. Ray.Transform = function (ray, matrix) {
  49862. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49863. Ray.TransformToRef(ray, matrix, result);
  49864. return result;
  49865. };
  49866. Ray.TransformToRef = function (ray, matrix, result) {
  49867. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49868. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49869. result.length = ray.length;
  49870. var dir = result.direction;
  49871. var len = dir.length();
  49872. if (!(len === 0 || len === 1)) {
  49873. var num = 1.0 / len;
  49874. dir.x *= num;
  49875. dir.y *= num;
  49876. dir.z *= num;
  49877. result.length *= len;
  49878. }
  49879. };
  49880. Ray.smallnum = 0.00000001;
  49881. Ray.rayl = 10e8;
  49882. return Ray;
  49883. }());
  49884. BABYLON.Ray = Ray;
  49885. })(BABYLON || (BABYLON = {}));
  49886. //# sourceMappingURL=babylon.ray.js.map
  49887. var BABYLON;
  49888. (function (BABYLON) {
  49889. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49890. if (boxMin.x > sphereCenter.x + sphereRadius)
  49891. return false;
  49892. if (sphereCenter.x - sphereRadius > boxMax.x)
  49893. return false;
  49894. if (boxMin.y > sphereCenter.y + sphereRadius)
  49895. return false;
  49896. if (sphereCenter.y - sphereRadius > boxMax.y)
  49897. return false;
  49898. if (boxMin.z > sphereCenter.z + sphereRadius)
  49899. return false;
  49900. if (sphereCenter.z - sphereRadius > boxMax.z)
  49901. return false;
  49902. return true;
  49903. };
  49904. var getLowestRoot = (function () {
  49905. var result = { root: 0, found: false };
  49906. return function (a, b, c, maxR) {
  49907. result.root = 0;
  49908. result.found = false;
  49909. var determinant = b * b - 4.0 * a * c;
  49910. if (determinant < 0)
  49911. return result;
  49912. var sqrtD = Math.sqrt(determinant);
  49913. var r1 = (-b - sqrtD) / (2.0 * a);
  49914. var r2 = (-b + sqrtD) / (2.0 * a);
  49915. if (r1 > r2) {
  49916. var temp = r2;
  49917. r2 = r1;
  49918. r1 = temp;
  49919. }
  49920. if (r1 > 0 && r1 < maxR) {
  49921. result.root = r1;
  49922. result.found = true;
  49923. return result;
  49924. }
  49925. if (r2 > 0 && r2 < maxR) {
  49926. result.root = r2;
  49927. result.found = true;
  49928. return result;
  49929. }
  49930. return result;
  49931. };
  49932. })();
  49933. var Collider = /** @class */ (function () {
  49934. function Collider() {
  49935. this._collisionPoint = BABYLON.Vector3.Zero();
  49936. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49937. this._tempVector = BABYLON.Vector3.Zero();
  49938. this._tempVector2 = BABYLON.Vector3.Zero();
  49939. this._tempVector3 = BABYLON.Vector3.Zero();
  49940. this._tempVector4 = BABYLON.Vector3.Zero();
  49941. this._edge = BABYLON.Vector3.Zero();
  49942. this._baseToVertex = BABYLON.Vector3.Zero();
  49943. this._destinationPoint = BABYLON.Vector3.Zero();
  49944. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49945. this._displacementVector = BABYLON.Vector3.Zero();
  49946. this._radius = BABYLON.Vector3.One();
  49947. this._retry = 0;
  49948. this._basePointWorld = BABYLON.Vector3.Zero();
  49949. this._velocityWorld = BABYLON.Vector3.Zero();
  49950. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49951. this._collisionMask = -1;
  49952. }
  49953. Object.defineProperty(Collider.prototype, "collisionMask", {
  49954. get: function () {
  49955. return this._collisionMask;
  49956. },
  49957. set: function (mask) {
  49958. this._collisionMask = !isNaN(mask) ? mask : -1;
  49959. },
  49960. enumerable: true,
  49961. configurable: true
  49962. });
  49963. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49964. /**
  49965. * Gets the plane normal used to compute the sliding response (in local space)
  49966. */
  49967. get: function () {
  49968. return this._slidePlaneNormal;
  49969. },
  49970. enumerable: true,
  49971. configurable: true
  49972. });
  49973. // Methods
  49974. Collider.prototype._initialize = function (source, dir, e) {
  49975. this._velocity = dir;
  49976. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49977. this._basePoint = source;
  49978. source.multiplyToRef(this._radius, this._basePointWorld);
  49979. dir.multiplyToRef(this._radius, this._velocityWorld);
  49980. this._velocityWorldLength = this._velocityWorld.length();
  49981. this._epsilon = e;
  49982. this.collisionFound = false;
  49983. };
  49984. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49985. pa.subtractToRef(point, this._tempVector);
  49986. pb.subtractToRef(point, this._tempVector2);
  49987. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49988. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49989. if (d < 0)
  49990. return false;
  49991. pc.subtractToRef(point, this._tempVector3);
  49992. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49993. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49994. if (d < 0)
  49995. return false;
  49996. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49997. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49998. return d >= 0;
  49999. };
  50000. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50001. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50002. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50003. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50004. return false;
  50005. }
  50006. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50007. return false;
  50008. return true;
  50009. };
  50010. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50011. var t0;
  50012. var embeddedInPlane = false;
  50013. //defensive programming, actually not needed.
  50014. if (!trianglePlaneArray) {
  50015. trianglePlaneArray = [];
  50016. }
  50017. if (!trianglePlaneArray[faceIndex]) {
  50018. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50019. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50020. }
  50021. var trianglePlane = trianglePlaneArray[faceIndex];
  50022. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50023. return;
  50024. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50025. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50026. if (normalDotVelocity == 0) {
  50027. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50028. return;
  50029. embeddedInPlane = true;
  50030. t0 = 0;
  50031. }
  50032. else {
  50033. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50034. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50035. if (t0 > t1) {
  50036. var temp = t1;
  50037. t1 = t0;
  50038. t0 = temp;
  50039. }
  50040. if (t0 > 1.0 || t1 < 0.0)
  50041. return;
  50042. if (t0 < 0)
  50043. t0 = 0;
  50044. if (t0 > 1.0)
  50045. t0 = 1.0;
  50046. }
  50047. this._collisionPoint.copyFromFloats(0, 0, 0);
  50048. var found = false;
  50049. var t = 1.0;
  50050. if (!embeddedInPlane) {
  50051. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50052. this._velocity.scaleToRef(t0, this._tempVector);
  50053. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50054. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50055. found = true;
  50056. t = t0;
  50057. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50058. }
  50059. }
  50060. if (!found) {
  50061. var velocitySquaredLength = this._velocity.lengthSquared();
  50062. var a = velocitySquaredLength;
  50063. this._basePoint.subtractToRef(p1, this._tempVector);
  50064. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50065. var c = this._tempVector.lengthSquared() - 1.0;
  50066. var lowestRoot = getLowestRoot(a, b, c, t);
  50067. if (lowestRoot.found) {
  50068. t = lowestRoot.root;
  50069. found = true;
  50070. this._collisionPoint.copyFrom(p1);
  50071. }
  50072. this._basePoint.subtractToRef(p2, this._tempVector);
  50073. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50074. c = this._tempVector.lengthSquared() - 1.0;
  50075. lowestRoot = getLowestRoot(a, b, c, t);
  50076. if (lowestRoot.found) {
  50077. t = lowestRoot.root;
  50078. found = true;
  50079. this._collisionPoint.copyFrom(p2);
  50080. }
  50081. this._basePoint.subtractToRef(p3, this._tempVector);
  50082. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50083. c = this._tempVector.lengthSquared() - 1.0;
  50084. lowestRoot = getLowestRoot(a, b, c, t);
  50085. if (lowestRoot.found) {
  50086. t = lowestRoot.root;
  50087. found = true;
  50088. this._collisionPoint.copyFrom(p3);
  50089. }
  50090. p2.subtractToRef(p1, this._edge);
  50091. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50092. var edgeSquaredLength = this._edge.lengthSquared();
  50093. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50094. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50095. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50096. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50097. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50098. lowestRoot = getLowestRoot(a, b, c, t);
  50099. if (lowestRoot.found) {
  50100. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50101. if (f >= 0.0 && f <= 1.0) {
  50102. t = lowestRoot.root;
  50103. found = true;
  50104. this._edge.scaleInPlace(f);
  50105. p1.addToRef(this._edge, this._collisionPoint);
  50106. }
  50107. }
  50108. p3.subtractToRef(p2, this._edge);
  50109. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50110. edgeSquaredLength = this._edge.lengthSquared();
  50111. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50112. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50113. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50114. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50115. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50116. lowestRoot = getLowestRoot(a, b, c, t);
  50117. if (lowestRoot.found) {
  50118. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50119. if (f >= 0.0 && f <= 1.0) {
  50120. t = lowestRoot.root;
  50121. found = true;
  50122. this._edge.scaleInPlace(f);
  50123. p2.addToRef(this._edge, this._collisionPoint);
  50124. }
  50125. }
  50126. p1.subtractToRef(p3, this._edge);
  50127. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50128. edgeSquaredLength = this._edge.lengthSquared();
  50129. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50130. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50131. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50132. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50133. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50134. lowestRoot = getLowestRoot(a, b, c, t);
  50135. if (lowestRoot.found) {
  50136. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50137. if (f >= 0.0 && f <= 1.0) {
  50138. t = lowestRoot.root;
  50139. found = true;
  50140. this._edge.scaleInPlace(f);
  50141. p3.addToRef(this._edge, this._collisionPoint);
  50142. }
  50143. }
  50144. }
  50145. if (found) {
  50146. var distToCollision = t * this._velocity.length();
  50147. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50148. if (!this.intersectionPoint) {
  50149. this.intersectionPoint = this._collisionPoint.clone();
  50150. }
  50151. else {
  50152. this.intersectionPoint.copyFrom(this._collisionPoint);
  50153. }
  50154. this._nearestDistance = distToCollision;
  50155. this.collisionFound = true;
  50156. }
  50157. }
  50158. };
  50159. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50160. for (var i = indexStart; i < indexEnd; i += 3) {
  50161. var p1 = pts[indices[i] - decal];
  50162. var p2 = pts[indices[i + 1] - decal];
  50163. var p3 = pts[indices[i + 2] - decal];
  50164. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50165. }
  50166. };
  50167. Collider.prototype._getResponse = function (pos, vel) {
  50168. pos.addToRef(vel, this._destinationPoint);
  50169. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50170. this._basePoint.addToRef(vel, pos);
  50171. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50172. this._slidePlaneNormal.normalize();
  50173. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50174. pos.addInPlace(this._displacementVector);
  50175. this.intersectionPoint.addInPlace(this._displacementVector);
  50176. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50177. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50178. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50179. };
  50180. return Collider;
  50181. }());
  50182. BABYLON.Collider = Collider;
  50183. })(BABYLON || (BABYLON = {}));
  50184. //# sourceMappingURL=babylon.collider.js.map
  50185. var BABYLON;
  50186. (function (BABYLON) {
  50187. //WebWorker code will be inserted to this variable.
  50188. BABYLON.CollisionWorker = "";
  50189. var WorkerTaskType;
  50190. (function (WorkerTaskType) {
  50191. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50192. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50193. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50194. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50195. var WorkerReplyType;
  50196. (function (WorkerReplyType) {
  50197. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50198. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50199. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50200. var CollisionCoordinatorWorker = /** @class */ (function () {
  50201. function CollisionCoordinatorWorker() {
  50202. var _this = this;
  50203. this._scaledPosition = BABYLON.Vector3.Zero();
  50204. this._scaledVelocity = BABYLON.Vector3.Zero();
  50205. this.onMeshUpdated = function (transformNode) {
  50206. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50207. };
  50208. this.onGeometryUpdated = function (geometry) {
  50209. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50210. };
  50211. this._afterRender = function () {
  50212. if (!_this._init)
  50213. return;
  50214. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50215. return;
  50216. }
  50217. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50218. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50219. if (_this._runningUpdated > 4) {
  50220. return;
  50221. }
  50222. ++_this._runningUpdated;
  50223. var payload = {
  50224. updatedMeshes: _this._addUpdateMeshesList,
  50225. updatedGeometries: _this._addUpdateGeometriesList,
  50226. removedGeometries: _this._toRemoveGeometryArray,
  50227. removedMeshes: _this._toRemoveMeshesArray
  50228. };
  50229. var message = {
  50230. payload: payload,
  50231. taskType: WorkerTaskType.UPDATE
  50232. };
  50233. var serializable = [];
  50234. for (var id in payload.updatedGeometries) {
  50235. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50236. //prepare transferables
  50237. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50238. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50239. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50240. }
  50241. }
  50242. _this._worker.postMessage(message, serializable);
  50243. _this._addUpdateMeshesList = {};
  50244. _this._addUpdateGeometriesList = {};
  50245. _this._toRemoveGeometryArray = [];
  50246. _this._toRemoveMeshesArray = [];
  50247. };
  50248. this._onMessageFromWorker = function (e) {
  50249. var returnData = e.data;
  50250. if (returnData.error != WorkerReplyType.SUCCESS) {
  50251. //TODO what errors can be returned from the worker?
  50252. BABYLON.Tools.Warn("error returned from worker!");
  50253. return;
  50254. }
  50255. switch (returnData.taskType) {
  50256. case WorkerTaskType.INIT:
  50257. _this._init = true;
  50258. //Update the worked with ALL of the scene's current state
  50259. _this._scene.meshes.forEach(function (mesh) {
  50260. _this.onMeshAdded(mesh);
  50261. });
  50262. _this._scene.getGeometries().forEach(function (geometry) {
  50263. _this.onGeometryAdded(geometry);
  50264. });
  50265. break;
  50266. case WorkerTaskType.UPDATE:
  50267. _this._runningUpdated--;
  50268. break;
  50269. case WorkerTaskType.COLLIDE:
  50270. var returnPayload = returnData.payload;
  50271. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50272. return;
  50273. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50274. if (callback) {
  50275. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50276. if (mesh) {
  50277. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50278. }
  50279. }
  50280. //cleanup
  50281. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50282. break;
  50283. }
  50284. };
  50285. this._collisionsCallbackArray = [];
  50286. this._init = false;
  50287. this._runningUpdated = 0;
  50288. this._addUpdateMeshesList = {};
  50289. this._addUpdateGeometriesList = {};
  50290. this._toRemoveGeometryArray = [];
  50291. this._toRemoveMeshesArray = [];
  50292. }
  50293. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50294. if (!this._init)
  50295. return;
  50296. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50297. return;
  50298. position.divideToRef(collider._radius, this._scaledPosition);
  50299. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50300. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50301. var payload = {
  50302. collider: {
  50303. position: this._scaledPosition.asArray(),
  50304. velocity: this._scaledVelocity.asArray(),
  50305. radius: collider._radius.asArray()
  50306. },
  50307. collisionId: collisionIndex,
  50308. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50309. maximumRetry: maximumRetry
  50310. };
  50311. var message = {
  50312. payload: payload,
  50313. taskType: WorkerTaskType.COLLIDE
  50314. };
  50315. this._worker.postMessage(message);
  50316. };
  50317. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50318. this._scene = scene;
  50319. this._scene.registerAfterRender(this._afterRender);
  50320. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50321. this._worker = new Worker(workerUrl);
  50322. this._worker.onmessage = this._onMessageFromWorker;
  50323. var message = {
  50324. payload: {},
  50325. taskType: WorkerTaskType.INIT
  50326. };
  50327. this._worker.postMessage(message);
  50328. };
  50329. CollisionCoordinatorWorker.prototype.destroy = function () {
  50330. this._scene.unregisterAfterRender(this._afterRender);
  50331. this._worker.terminate();
  50332. };
  50333. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50334. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50335. this.onMeshUpdated(mesh);
  50336. };
  50337. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50338. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50339. };
  50340. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50341. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50342. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50343. this.onGeometryUpdated(geometry);
  50344. };
  50345. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50346. this._toRemoveGeometryArray.push(geometry.id);
  50347. };
  50348. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50349. var submeshes = [];
  50350. if (mesh.subMeshes) {
  50351. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50352. var boundingInfo = sm.getBoundingInfo();
  50353. return {
  50354. position: idx,
  50355. verticesStart: sm.verticesStart,
  50356. verticesCount: sm.verticesCount,
  50357. indexStart: sm.indexStart,
  50358. indexCount: sm.indexCount,
  50359. hasMaterial: !!sm.getMaterial(),
  50360. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50361. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50362. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50363. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50364. };
  50365. });
  50366. }
  50367. var geometryId = null;
  50368. if (mesh instanceof BABYLON.Mesh) {
  50369. var geometry = mesh.geometry;
  50370. geometryId = geometry ? geometry.id : null;
  50371. }
  50372. else if (mesh instanceof BABYLON.InstancedMesh) {
  50373. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50374. geometryId = geometry ? geometry.id : null;
  50375. }
  50376. var boundingInfo = mesh.getBoundingInfo();
  50377. return {
  50378. uniqueId: mesh.uniqueId,
  50379. id: mesh.id,
  50380. name: mesh.name,
  50381. geometryId: geometryId,
  50382. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50383. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50384. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50385. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50386. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50387. subMeshes: submeshes,
  50388. checkCollisions: mesh.checkCollisions
  50389. };
  50390. };
  50391. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50392. return {
  50393. id: geometry.id,
  50394. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50395. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50396. indices: new Uint32Array(geometry.getIndices() || []),
  50397. };
  50398. };
  50399. return CollisionCoordinatorWorker;
  50400. }());
  50401. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50402. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50403. function CollisionCoordinatorLegacy() {
  50404. this._scaledPosition = BABYLON.Vector3.Zero();
  50405. this._scaledVelocity = BABYLON.Vector3.Zero();
  50406. this._finalPosition = BABYLON.Vector3.Zero();
  50407. }
  50408. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50409. position.divideToRef(collider._radius, this._scaledPosition);
  50410. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50411. collider.collidedMesh = null;
  50412. collider._retry = 0;
  50413. collider._initialVelocity = this._scaledVelocity;
  50414. collider._initialPosition = this._scaledPosition;
  50415. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50416. this._finalPosition.multiplyInPlace(collider._radius);
  50417. //run the callback
  50418. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50419. };
  50420. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50421. this._scene = scene;
  50422. };
  50423. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50424. //Legacy need no destruction method.
  50425. };
  50426. //No update in legacy mode
  50427. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50428. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50429. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50430. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50431. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50432. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50433. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50434. if (excludedMesh === void 0) { excludedMesh = null; }
  50435. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50436. if (collider._retry >= maximumRetry) {
  50437. finalPosition.copyFrom(position);
  50438. return;
  50439. }
  50440. // Check if this is a mesh else camera or -1
  50441. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50442. collider._initialize(position, velocity, closeDistance);
  50443. // Check all meshes
  50444. for (var index = 0; index < this._scene.meshes.length; index++) {
  50445. var mesh = this._scene.meshes[index];
  50446. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50447. mesh._checkCollision(collider);
  50448. }
  50449. }
  50450. if (!collider.collisionFound) {
  50451. position.addToRef(velocity, finalPosition);
  50452. return;
  50453. }
  50454. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50455. collider._getResponse(position, velocity);
  50456. }
  50457. if (velocity.length() <= closeDistance) {
  50458. finalPosition.copyFrom(position);
  50459. return;
  50460. }
  50461. collider._retry++;
  50462. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50463. };
  50464. return CollisionCoordinatorLegacy;
  50465. }());
  50466. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50467. })(BABYLON || (BABYLON = {}));
  50468. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50469. var BABYLON;
  50470. (function (BABYLON) {
  50471. /**
  50472. * A particle represents one of the element emitted by a particle system.
  50473. * This is mainly define by its coordinates, direction, velocity and age.
  50474. */
  50475. var Particle = /** @class */ (function () {
  50476. /**
  50477. * Creates a new instance of @see Particle
  50478. * @param particleSystem the particle system the particle belongs to
  50479. */
  50480. function Particle(particleSystem) {
  50481. this.particleSystem = particleSystem;
  50482. /**
  50483. * The world position of the particle in the scene.
  50484. */
  50485. this.position = BABYLON.Vector3.Zero();
  50486. /**
  50487. * The world direction of the particle in the scene.
  50488. */
  50489. this.direction = BABYLON.Vector3.Zero();
  50490. /**
  50491. * The color of the particle.
  50492. */
  50493. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50494. /**
  50495. * The color change of the particle per step.
  50496. */
  50497. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50498. /**
  50499. * Defines how long will the life of the particle be.
  50500. */
  50501. this.lifeTime = 1.0;
  50502. /**
  50503. * The current age of the particle.
  50504. */
  50505. this.age = 0;
  50506. /**
  50507. * The current size of the particle.
  50508. */
  50509. this.size = 0;
  50510. /**
  50511. * The current angle of the particle.
  50512. */
  50513. this.angle = 0;
  50514. /**
  50515. * Defines how fast is the angle changing.
  50516. */
  50517. this.angularSpeed = 0;
  50518. /**
  50519. * Defines the cell index used by the particle to be rendered from a sprite.
  50520. */
  50521. this.cellIndex = 0;
  50522. this._currentFrameCounter = 0;
  50523. if (!this.particleSystem.isAnimationSheetEnabled) {
  50524. return;
  50525. }
  50526. this.cellIndex = this.particleSystem.startSpriteCellID;
  50527. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50528. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50529. }
  50530. else {
  50531. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50532. }
  50533. }
  50534. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50535. // (ageOffset / scaledUpdateSpeed) / available cells
  50536. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50537. this._currentFrameCounter += scaledUpdateSpeed;
  50538. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50539. this._currentFrameCounter = 0;
  50540. this.cellIndex++;
  50541. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50542. this.cellIndex = this.particleSystem.endSpriteCellID;
  50543. }
  50544. }
  50545. };
  50546. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50547. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50548. this.cellIndex++;
  50549. this._currentFrameCounter = 0;
  50550. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50551. if (this.particleSystem.spriteCellLoop) {
  50552. this.cellIndex = this.particleSystem.startSpriteCellID;
  50553. }
  50554. else {
  50555. this.cellIndex = this.particleSystem.endSpriteCellID;
  50556. }
  50557. }
  50558. }
  50559. else {
  50560. this._currentFrameCounter++;
  50561. }
  50562. };
  50563. /**
  50564. * Copy the properties of particle to another one.
  50565. * @param other the particle to copy the information to.
  50566. */
  50567. Particle.prototype.copyTo = function (other) {
  50568. other.position.copyFrom(this.position);
  50569. other.direction.copyFrom(this.direction);
  50570. other.color.copyFrom(this.color);
  50571. other.colorStep.copyFrom(this.colorStep);
  50572. other.lifeTime = this.lifeTime;
  50573. other.age = this.age;
  50574. other.size = this.size;
  50575. other.angle = this.angle;
  50576. other.angularSpeed = this.angularSpeed;
  50577. other.particleSystem = this.particleSystem;
  50578. other.cellIndex = this.cellIndex;
  50579. };
  50580. return Particle;
  50581. }());
  50582. BABYLON.Particle = Particle;
  50583. })(BABYLON || (BABYLON = {}));
  50584. //# sourceMappingURL=babylon.particle.js.map
  50585. var BABYLON;
  50586. (function (BABYLON) {
  50587. /**
  50588. * This represents a particle system in Babylon.
  50589. * 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.
  50590. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50591. * @example https://doc.babylonjs.com/babylon101/particles
  50592. */
  50593. var ParticleSystem = /** @class */ (function () {
  50594. /**
  50595. * Instantiates a particle system.
  50596. * 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.
  50597. * @param name The name of the particle system
  50598. * @param capacity The max number of particles alive at the same time
  50599. * @param scene The scene the particle system belongs to
  50600. * @param customEffect a custom effect used to change the way particles are rendered by default
  50601. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50602. * @param epsilon Offset used to render the particles
  50603. */
  50604. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50605. if (customEffect === void 0) { customEffect = null; }
  50606. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50607. if (epsilon === void 0) { epsilon = 0.01; }
  50608. var _this = this;
  50609. /**
  50610. * List of animations used by the particle system.
  50611. */
  50612. this.animations = [];
  50613. /**
  50614. * The rendering group used by the Particle system to chose when to render.
  50615. */
  50616. this.renderingGroupId = 0;
  50617. /**
  50618. * The emitter represents the Mesh or position we are attaching the particle system to.
  50619. */
  50620. this.emitter = null;
  50621. /**
  50622. * The maximum number of particles to emit per frame
  50623. */
  50624. this.emitRate = 10;
  50625. /**
  50626. * If you want to launch only a few particles at once, that can be done, as well.
  50627. */
  50628. this.manualEmitCount = -1;
  50629. /**
  50630. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50631. */
  50632. this.updateSpeed = 0.01;
  50633. /**
  50634. * The amount of time the particle system is running (depends of the overall update speed).
  50635. */
  50636. this.targetStopDuration = 0;
  50637. /**
  50638. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50639. */
  50640. this.disposeOnStop = false;
  50641. /**
  50642. * Minimum power of emitting particles.
  50643. */
  50644. this.minEmitPower = 1;
  50645. /**
  50646. * Maximum power of emitting particles.
  50647. */
  50648. this.maxEmitPower = 1;
  50649. /**
  50650. * Minimum life time of emitting particles.
  50651. */
  50652. this.minLifeTime = 1;
  50653. /**
  50654. * Maximum life time of emitting particles.
  50655. */
  50656. this.maxLifeTime = 1;
  50657. /**
  50658. * Minimum Size of emitting particles.
  50659. */
  50660. this.minSize = 1;
  50661. /**
  50662. * Maximum Size of emitting particles.
  50663. */
  50664. this.maxSize = 1;
  50665. /**
  50666. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50667. */
  50668. this.minAngularSpeed = 0;
  50669. /**
  50670. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50671. */
  50672. this.maxAngularSpeed = 0;
  50673. /**
  50674. * The layer mask we are rendering the particles through.
  50675. */
  50676. this.layerMask = 0x0FFFFFFF;
  50677. /**
  50678. * This can help using your own shader to render the particle system.
  50679. * The according effect will be created
  50680. */
  50681. this.customShader = null;
  50682. /**
  50683. * By default particle system starts as soon as they are created. This prevents the
  50684. * automatic start to happen and let you decide when to start emitting particles.
  50685. */
  50686. this.preventAutoStart = false;
  50687. /**
  50688. * Callback triggered when the particle animation is ending.
  50689. */
  50690. this.onAnimationEnd = null;
  50691. /**
  50692. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50693. */
  50694. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50695. /**
  50696. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50697. * to override the particles.
  50698. */
  50699. this.forceDepthWrite = false;
  50700. /**
  50701. * You can use gravity if you want to give an orientation to your particles.
  50702. */
  50703. this.gravity = BABYLON.Vector3.Zero();
  50704. /**
  50705. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50706. */
  50707. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50708. /**
  50709. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50710. */
  50711. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50712. /**
  50713. * Color the particle will have at the end of its lifetime.
  50714. */
  50715. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50716. /**
  50717. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50718. */
  50719. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50720. /**
  50721. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50722. */
  50723. this.spriteCellLoop = true;
  50724. /**
  50725. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50726. */
  50727. this.spriteCellChangeSpeed = 0;
  50728. /**
  50729. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50730. */
  50731. this.startSpriteCellID = 0;
  50732. /**
  50733. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50734. */
  50735. this.endSpriteCellID = 0;
  50736. /**
  50737. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50738. */
  50739. this.spriteCellWidth = 0;
  50740. /**
  50741. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50742. */
  50743. this.spriteCellHeight = 0;
  50744. /**
  50745. * An event triggered when the system is disposed.
  50746. */
  50747. this.onDisposeObservable = new BABYLON.Observable();
  50748. this._particles = new Array();
  50749. this._stockParticles = new Array();
  50750. this._newPartsExcess = 0;
  50751. this._vertexBuffers = {};
  50752. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50753. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50754. this._scaledDirection = BABYLON.Vector3.Zero();
  50755. this._scaledGravity = BABYLON.Vector3.Zero();
  50756. this._currentRenderId = -1;
  50757. this._started = false;
  50758. this._stopped = false;
  50759. this._actualFrame = 0;
  50760. this._vertexBufferSize = 11;
  50761. this._appendParticleVertexes = null;
  50762. this.id = name;
  50763. this.name = name;
  50764. this._capacity = capacity;
  50765. this._epsilon = epsilon;
  50766. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50767. if (isAnimationSheetEnabled) {
  50768. this._vertexBufferSize = 12;
  50769. }
  50770. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50771. this._customEffect = customEffect;
  50772. scene.particleSystems.push(this);
  50773. this._createIndexBuffer();
  50774. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50775. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50776. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50777. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50778. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50779. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50780. if (this._isAnimationSheetEnabled) {
  50781. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50782. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50783. }
  50784. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50785. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50786. this._vertexBuffers["options"] = options;
  50787. // Default emitter type
  50788. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50789. this.updateFunction = function (particles) {
  50790. for (var index = 0; index < particles.length; index++) {
  50791. var particle = particles[index];
  50792. particle.age += _this._scaledUpdateSpeed;
  50793. if (particle.age >= particle.lifeTime) {
  50794. _this.recycleParticle(particle);
  50795. index--;
  50796. continue;
  50797. }
  50798. else {
  50799. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50800. particle.color.addInPlace(_this._scaledColorStep);
  50801. if (particle.color.a < 0)
  50802. particle.color.a = 0;
  50803. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50804. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50805. particle.position.addInPlace(_this._scaledDirection);
  50806. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50807. particle.direction.addInPlace(_this._scaledGravity);
  50808. if (_this._isAnimationSheetEnabled) {
  50809. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50810. }
  50811. }
  50812. }
  50813. };
  50814. }
  50815. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50816. /**
  50817. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50818. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50819. */
  50820. get: function () {
  50821. if (this.particleEmitterType.direction1) {
  50822. return this.particleEmitterType.direction1;
  50823. }
  50824. return BABYLON.Vector3.Zero();
  50825. },
  50826. set: function (value) {
  50827. if (this.particleEmitterType.direction1) {
  50828. this.particleEmitterType.direction1 = value;
  50829. }
  50830. },
  50831. enumerable: true,
  50832. configurable: true
  50833. });
  50834. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50835. /**
  50836. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50837. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50838. */
  50839. get: function () {
  50840. if (this.particleEmitterType.direction2) {
  50841. return this.particleEmitterType.direction2;
  50842. }
  50843. return BABYLON.Vector3.Zero();
  50844. },
  50845. set: function (value) {
  50846. if (this.particleEmitterType.direction2) {
  50847. this.particleEmitterType.direction2 = value;
  50848. }
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50854. /**
  50855. * 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.
  50856. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50857. */
  50858. get: function () {
  50859. if (this.particleEmitterType.minEmitBox) {
  50860. return this.particleEmitterType.minEmitBox;
  50861. }
  50862. return BABYLON.Vector3.Zero();
  50863. },
  50864. set: function (value) {
  50865. if (this.particleEmitterType.minEmitBox) {
  50866. this.particleEmitterType.minEmitBox = value;
  50867. }
  50868. },
  50869. enumerable: true,
  50870. configurable: true
  50871. });
  50872. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50873. /**
  50874. * 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.
  50875. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50876. */
  50877. get: function () {
  50878. if (this.particleEmitterType.maxEmitBox) {
  50879. return this.particleEmitterType.maxEmitBox;
  50880. }
  50881. return BABYLON.Vector3.Zero();
  50882. },
  50883. set: function (value) {
  50884. if (this.particleEmitterType.maxEmitBox) {
  50885. this.particleEmitterType.maxEmitBox = value;
  50886. }
  50887. },
  50888. enumerable: true,
  50889. configurable: true
  50890. });
  50891. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50892. /**
  50893. * Sets a callback that will be triggered when the system is disposed.
  50894. */
  50895. set: function (callback) {
  50896. if (this._onDisposeObserver) {
  50897. this.onDisposeObservable.remove(this._onDisposeObserver);
  50898. }
  50899. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50900. },
  50901. enumerable: true,
  50902. configurable: true
  50903. });
  50904. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50905. /**
  50906. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50907. */
  50908. get: function () {
  50909. return this._isAnimationSheetEnabled;
  50910. },
  50911. enumerable: true,
  50912. configurable: true
  50913. });
  50914. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50915. /**
  50916. * Gets the current list of active particles
  50917. */
  50918. get: function () {
  50919. return this._particles;
  50920. },
  50921. enumerable: true,
  50922. configurable: true
  50923. });
  50924. /**
  50925. * Returns the string "ParticleSystem"
  50926. * @returns a string containing the class name
  50927. */
  50928. ParticleSystem.prototype.getClassName = function () {
  50929. return "ParticleSystem";
  50930. };
  50931. ParticleSystem.prototype._createIndexBuffer = function () {
  50932. var indices = [];
  50933. var index = 0;
  50934. for (var count = 0; count < this._capacity; count++) {
  50935. indices.push(index);
  50936. indices.push(index + 1);
  50937. indices.push(index + 2);
  50938. indices.push(index);
  50939. indices.push(index + 2);
  50940. indices.push(index + 3);
  50941. index += 4;
  50942. }
  50943. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50944. };
  50945. /**
  50946. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50947. * Its lifetime will start back at 0.
  50948. * @param particle The particle to recycle
  50949. */
  50950. ParticleSystem.prototype.recycleParticle = function (particle) {
  50951. var lastParticle = this._particles.pop();
  50952. if (lastParticle !== particle) {
  50953. lastParticle.copyTo(particle);
  50954. this._stockParticles.push(lastParticle);
  50955. }
  50956. };
  50957. /**
  50958. * Gets the maximum number of particles active at the same time.
  50959. * @returns The max number of active particles.
  50960. */
  50961. ParticleSystem.prototype.getCapacity = function () {
  50962. return this._capacity;
  50963. };
  50964. /**
  50965. * Gets Wether there are still active particles in the system.
  50966. * @returns True if it is alive, otherwise false.
  50967. */
  50968. ParticleSystem.prototype.isAlive = function () {
  50969. return this._alive;
  50970. };
  50971. /**
  50972. * Gets Wether the system has been started.
  50973. * @returns True if it has been started, otherwise false.
  50974. */
  50975. ParticleSystem.prototype.isStarted = function () {
  50976. return this._started;
  50977. };
  50978. /**
  50979. * Starts the particle system and begins to emit.
  50980. */
  50981. ParticleSystem.prototype.start = function () {
  50982. this._started = true;
  50983. this._stopped = false;
  50984. this._actualFrame = 0;
  50985. };
  50986. /**
  50987. * Stops the particle system.
  50988. */
  50989. ParticleSystem.prototype.stop = function () {
  50990. this._stopped = true;
  50991. };
  50992. /**
  50993. * Remove all active particles
  50994. */
  50995. ParticleSystem.prototype.reset = function () {
  50996. this._stockParticles = [];
  50997. this._particles = [];
  50998. };
  50999. /**
  51000. * @ignore (for internal use only)
  51001. */
  51002. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51003. var offset = index * this._vertexBufferSize;
  51004. this._vertexData[offset] = particle.position.x;
  51005. this._vertexData[offset + 1] = particle.position.y;
  51006. this._vertexData[offset + 2] = particle.position.z;
  51007. this._vertexData[offset + 3] = particle.color.r;
  51008. this._vertexData[offset + 4] = particle.color.g;
  51009. this._vertexData[offset + 5] = particle.color.b;
  51010. this._vertexData[offset + 6] = particle.color.a;
  51011. this._vertexData[offset + 7] = particle.angle;
  51012. this._vertexData[offset + 8] = particle.size;
  51013. this._vertexData[offset + 9] = offsetX;
  51014. this._vertexData[offset + 10] = offsetY;
  51015. };
  51016. /**
  51017. * @ignore (for internal use only)
  51018. */
  51019. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51020. if (offsetX === 0)
  51021. offsetX = this._epsilon;
  51022. else if (offsetX === 1)
  51023. offsetX = 1 - this._epsilon;
  51024. if (offsetY === 0)
  51025. offsetY = this._epsilon;
  51026. else if (offsetY === 1)
  51027. offsetY = 1 - this._epsilon;
  51028. var offset = index * this._vertexBufferSize;
  51029. this._vertexData[offset] = particle.position.x;
  51030. this._vertexData[offset + 1] = particle.position.y;
  51031. this._vertexData[offset + 2] = particle.position.z;
  51032. this._vertexData[offset + 3] = particle.color.r;
  51033. this._vertexData[offset + 4] = particle.color.g;
  51034. this._vertexData[offset + 5] = particle.color.b;
  51035. this._vertexData[offset + 6] = particle.color.a;
  51036. this._vertexData[offset + 7] = particle.angle;
  51037. this._vertexData[offset + 8] = particle.size;
  51038. this._vertexData[offset + 9] = offsetX;
  51039. this._vertexData[offset + 10] = offsetY;
  51040. this._vertexData[offset + 11] = particle.cellIndex;
  51041. };
  51042. ParticleSystem.prototype._update = function (newParticles) {
  51043. // Update current
  51044. this._alive = this._particles.length > 0;
  51045. this.updateFunction(this._particles);
  51046. // Add new ones
  51047. var worldMatrix;
  51048. if (this.emitter.position) {
  51049. var emitterMesh = this.emitter;
  51050. worldMatrix = emitterMesh.getWorldMatrix();
  51051. }
  51052. else {
  51053. var emitterPosition = this.emitter;
  51054. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51055. }
  51056. var particle;
  51057. for (var index = 0; index < newParticles; index++) {
  51058. if (this._particles.length === this._capacity) {
  51059. break;
  51060. }
  51061. if (this._stockParticles.length !== 0) {
  51062. particle = this._stockParticles.pop();
  51063. particle.age = 0;
  51064. particle.cellIndex = this.startSpriteCellID;
  51065. }
  51066. else {
  51067. particle = new BABYLON.Particle(this);
  51068. }
  51069. this._particles.push(particle);
  51070. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51071. if (this.startPositionFunction) {
  51072. this.startPositionFunction(worldMatrix, particle.position, particle);
  51073. }
  51074. else {
  51075. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51076. }
  51077. if (this.startDirectionFunction) {
  51078. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51079. }
  51080. else {
  51081. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51082. }
  51083. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51084. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51085. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51086. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51087. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51088. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51089. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51090. }
  51091. };
  51092. ParticleSystem.prototype._getEffect = function () {
  51093. if (this._customEffect) {
  51094. return this._customEffect;
  51095. }
  51096. ;
  51097. var defines = [];
  51098. if (this._scene.clipPlane) {
  51099. defines.push("#define CLIPPLANE");
  51100. }
  51101. if (this._isAnimationSheetEnabled) {
  51102. defines.push("#define ANIMATESHEET");
  51103. }
  51104. // Effect
  51105. var join = defines.join("\n");
  51106. if (this._cachedDefines !== join) {
  51107. this._cachedDefines = join;
  51108. var attributesNamesOrOptions;
  51109. var effectCreationOption;
  51110. if (this._isAnimationSheetEnabled) {
  51111. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51112. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51113. }
  51114. else {
  51115. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51116. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51117. }
  51118. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51119. }
  51120. return this._effect;
  51121. };
  51122. /**
  51123. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51124. */
  51125. ParticleSystem.prototype.animate = function () {
  51126. if (!this._started)
  51127. return;
  51128. var effect = this._getEffect();
  51129. // Check
  51130. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51131. return;
  51132. if (this._currentRenderId === this._scene.getRenderId()) {
  51133. return;
  51134. }
  51135. this._currentRenderId = this._scene.getRenderId();
  51136. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51137. // determine the number of particles we need to create
  51138. var newParticles;
  51139. if (this.manualEmitCount > -1) {
  51140. newParticles = this.manualEmitCount;
  51141. this._newPartsExcess = 0;
  51142. this.manualEmitCount = 0;
  51143. }
  51144. else {
  51145. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51146. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51147. }
  51148. if (this._newPartsExcess > 1.0) {
  51149. newParticles += this._newPartsExcess >> 0;
  51150. this._newPartsExcess -= this._newPartsExcess >> 0;
  51151. }
  51152. this._alive = false;
  51153. if (!this._stopped) {
  51154. this._actualFrame += this._scaledUpdateSpeed;
  51155. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51156. this.stop();
  51157. }
  51158. else {
  51159. newParticles = 0;
  51160. }
  51161. this._update(newParticles);
  51162. // Stopped?
  51163. if (this._stopped) {
  51164. if (!this._alive) {
  51165. this._started = false;
  51166. if (this.onAnimationEnd) {
  51167. this.onAnimationEnd();
  51168. }
  51169. if (this.disposeOnStop) {
  51170. this._scene._toBeDisposed.push(this);
  51171. }
  51172. }
  51173. }
  51174. // Animation sheet
  51175. if (this._isAnimationSheetEnabled) {
  51176. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51177. }
  51178. else {
  51179. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51180. }
  51181. // Update VBO
  51182. var offset = 0;
  51183. for (var index = 0; index < this._particles.length; index++) {
  51184. var particle = this._particles[index];
  51185. this._appendParticleVertexes(offset, particle);
  51186. offset += 4;
  51187. }
  51188. if (this._vertexBuffer) {
  51189. this._vertexBuffer.update(this._vertexData);
  51190. }
  51191. };
  51192. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51193. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51194. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51195. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51196. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51197. };
  51198. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51199. this._appendParticleVertex(offset++, particle, 0, 0);
  51200. this._appendParticleVertex(offset++, particle, 1, 0);
  51201. this._appendParticleVertex(offset++, particle, 1, 1);
  51202. this._appendParticleVertex(offset++, particle, 0, 1);
  51203. };
  51204. /**
  51205. * Rebuilds the particle system.
  51206. */
  51207. ParticleSystem.prototype.rebuild = function () {
  51208. this._createIndexBuffer();
  51209. if (this._vertexBuffer) {
  51210. this._vertexBuffer._rebuild();
  51211. }
  51212. };
  51213. /**
  51214. * Renders the particle system in its current state.
  51215. * @returns the current number of particles
  51216. */
  51217. ParticleSystem.prototype.render = function () {
  51218. var effect = this._getEffect();
  51219. // Check
  51220. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51221. return 0;
  51222. }
  51223. var engine = this._scene.getEngine();
  51224. // Render
  51225. engine.enableEffect(effect);
  51226. engine.setState(false);
  51227. var viewMatrix = this._scene.getViewMatrix();
  51228. effect.setTexture("diffuseSampler", this.particleTexture);
  51229. effect.setMatrix("view", viewMatrix);
  51230. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51231. if (this._isAnimationSheetEnabled) {
  51232. var baseSize = this.particleTexture.getBaseSize();
  51233. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51234. }
  51235. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51236. if (this._scene.clipPlane) {
  51237. var clipPlane = this._scene.clipPlane;
  51238. var invView = viewMatrix.clone();
  51239. invView.invert();
  51240. effect.setMatrix("invView", invView);
  51241. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51242. }
  51243. // VBOs
  51244. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51245. // Draw order
  51246. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51247. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51248. }
  51249. else {
  51250. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51251. }
  51252. if (this.forceDepthWrite) {
  51253. engine.setDepthWrite(true);
  51254. }
  51255. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51256. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51257. return this._particles.length;
  51258. };
  51259. /**
  51260. * Disposes the particle system and free the associated resources
  51261. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51262. */
  51263. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51264. if (disposeTexture === void 0) { disposeTexture = true; }
  51265. if (this._vertexBuffer) {
  51266. this._vertexBuffer.dispose();
  51267. this._vertexBuffer = null;
  51268. }
  51269. if (this._indexBuffer) {
  51270. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51271. this._indexBuffer = null;
  51272. }
  51273. if (disposeTexture && this.particleTexture) {
  51274. this.particleTexture.dispose();
  51275. this.particleTexture = null;
  51276. }
  51277. // Remove from scene
  51278. var index = this._scene.particleSystems.indexOf(this);
  51279. if (index > -1) {
  51280. this._scene.particleSystems.splice(index, 1);
  51281. }
  51282. // Callback
  51283. this.onDisposeObservable.notifyObservers(this);
  51284. this.onDisposeObservable.clear();
  51285. };
  51286. /**
  51287. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51288. * @param radius The radius of the sphere to emit from
  51289. * @returns the emitter
  51290. */
  51291. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51292. if (radius === void 0) { radius = 1; }
  51293. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51294. this.particleEmitterType = particleEmitter;
  51295. return particleEmitter;
  51296. };
  51297. /**
  51298. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51299. * @param radius The radius of the sphere to emit from
  51300. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51301. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51302. * @returns the emitter
  51303. */
  51304. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51305. if (radius === void 0) { radius = 1; }
  51306. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51307. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51308. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51309. this.particleEmitterType = particleEmitter;
  51310. return particleEmitter;
  51311. };
  51312. /**
  51313. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51314. * @param radius The radius of the cone to emit from
  51315. * @param angle The base angle of the cone
  51316. * @returns the emitter
  51317. */
  51318. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51319. if (radius === void 0) { radius = 1; }
  51320. if (angle === void 0) { angle = Math.PI / 4; }
  51321. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51322. this.particleEmitterType = particleEmitter;
  51323. return particleEmitter;
  51324. };
  51325. // 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.
  51326. /**
  51327. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51328. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51329. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51330. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51331. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51332. * @returns the emitter
  51333. */
  51334. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51335. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51336. this.direction1 = direction1;
  51337. this.direction2 = direction2;
  51338. this.minEmitBox = minEmitBox;
  51339. this.maxEmitBox = maxEmitBox;
  51340. this.particleEmitterType = particleEmitter;
  51341. return particleEmitter;
  51342. };
  51343. /**
  51344. * Clones the particle system.
  51345. * @param name The name of the cloned object
  51346. * @param newEmitter The new emitter to use
  51347. * @returns the cloned particle system
  51348. */
  51349. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51350. var custom = null;
  51351. var program = null;
  51352. if (this.customShader != null) {
  51353. program = this.customShader;
  51354. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51355. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51356. }
  51357. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51358. result.customShader = program;
  51359. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51360. if (newEmitter === undefined) {
  51361. newEmitter = this.emitter;
  51362. }
  51363. result.emitter = newEmitter;
  51364. if (this.particleTexture) {
  51365. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51366. }
  51367. if (!this.preventAutoStart) {
  51368. result.start();
  51369. }
  51370. return result;
  51371. };
  51372. /**
  51373. * Serializes the particle system to a JSON object.
  51374. * @returns the JSON object
  51375. */
  51376. ParticleSystem.prototype.serialize = function () {
  51377. var serializationObject = {};
  51378. serializationObject.name = this.name;
  51379. serializationObject.id = this.id;
  51380. // Emitter
  51381. if (this.emitter.position) {
  51382. var emitterMesh = this.emitter;
  51383. serializationObject.emitterId = emitterMesh.id;
  51384. }
  51385. else {
  51386. var emitterPosition = this.emitter;
  51387. serializationObject.emitter = emitterPosition.asArray();
  51388. }
  51389. serializationObject.capacity = this.getCapacity();
  51390. if (this.particleTexture) {
  51391. serializationObject.textureName = this.particleTexture.name;
  51392. }
  51393. // Animations
  51394. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51395. // Particle system
  51396. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51397. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51398. serializationObject.minSize = this.minSize;
  51399. serializationObject.maxSize = this.maxSize;
  51400. serializationObject.minEmitPower = this.minEmitPower;
  51401. serializationObject.maxEmitPower = this.maxEmitPower;
  51402. serializationObject.minLifeTime = this.minLifeTime;
  51403. serializationObject.maxLifeTime = this.maxLifeTime;
  51404. serializationObject.emitRate = this.emitRate;
  51405. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51406. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51407. serializationObject.gravity = this.gravity.asArray();
  51408. serializationObject.direction1 = this.direction1.asArray();
  51409. serializationObject.direction2 = this.direction2.asArray();
  51410. serializationObject.color1 = this.color1.asArray();
  51411. serializationObject.color2 = this.color2.asArray();
  51412. serializationObject.colorDead = this.colorDead.asArray();
  51413. serializationObject.updateSpeed = this.updateSpeed;
  51414. serializationObject.targetStopDuration = this.targetStopDuration;
  51415. serializationObject.textureMask = this.textureMask.asArray();
  51416. serializationObject.blendMode = this.blendMode;
  51417. serializationObject.customShader = this.customShader;
  51418. serializationObject.preventAutoStart = this.preventAutoStart;
  51419. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51420. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51421. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51422. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51423. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51424. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51425. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51426. // Emitter
  51427. if (this.particleEmitterType) {
  51428. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51429. }
  51430. return serializationObject;
  51431. };
  51432. /**
  51433. * Parses a JSON object to create a particle system.
  51434. * @param parsedParticleSystem The JSON object to parse
  51435. * @param scene The scene to create the particle system in
  51436. * @param rootUrl The root url to use to load external dependencies like texture
  51437. * @returns the Parsed particle system
  51438. */
  51439. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51440. var name = parsedParticleSystem.name;
  51441. var custom = null;
  51442. var program = null;
  51443. if (parsedParticleSystem.customShader) {
  51444. program = parsedParticleSystem.customShader;
  51445. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51446. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51447. }
  51448. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51449. particleSystem.customShader = program;
  51450. if (parsedParticleSystem.id) {
  51451. particleSystem.id = parsedParticleSystem.id;
  51452. }
  51453. // Auto start
  51454. if (parsedParticleSystem.preventAutoStart) {
  51455. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51456. }
  51457. // Texture
  51458. if (parsedParticleSystem.textureName) {
  51459. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51460. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51461. }
  51462. // Emitter
  51463. if (parsedParticleSystem.emitterId) {
  51464. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51465. }
  51466. else {
  51467. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51468. }
  51469. // Animations
  51470. if (parsedParticleSystem.animations) {
  51471. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51472. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51473. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51474. }
  51475. }
  51476. if (parsedParticleSystem.autoAnimate) {
  51477. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51478. }
  51479. // Particle system
  51480. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51481. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51482. particleSystem.minSize = parsedParticleSystem.minSize;
  51483. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51484. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51485. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51486. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51487. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51488. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51489. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51490. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51491. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51492. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51493. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51494. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51495. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51496. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51497. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51498. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51499. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51500. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51501. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51502. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51503. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51504. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51505. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51506. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51507. if (!particleSystem.preventAutoStart) {
  51508. particleSystem.start();
  51509. }
  51510. return particleSystem;
  51511. };
  51512. /**
  51513. * Source color is added to the destination color without alpha affecting the result.
  51514. */
  51515. ParticleSystem.BLENDMODE_ONEONE = 0;
  51516. /**
  51517. * Blend current color and particle color using particle’s alpha.
  51518. */
  51519. ParticleSystem.BLENDMODE_STANDARD = 1;
  51520. return ParticleSystem;
  51521. }());
  51522. BABYLON.ParticleSystem = ParticleSystem;
  51523. })(BABYLON || (BABYLON = {}));
  51524. //# sourceMappingURL=babylon.particleSystem.js.map
  51525. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51526. var BABYLON;
  51527. (function (BABYLON) {
  51528. /**
  51529. * Particle emitter emitting particles from the inside of a box.
  51530. * It emits the particles randomly between 2 given directions.
  51531. */
  51532. var BoxParticleEmitter = /** @class */ (function () {
  51533. /**
  51534. * Creates a new instance of @see BoxParticleEmitter
  51535. */
  51536. function BoxParticleEmitter() {
  51537. /**
  51538. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51539. */
  51540. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51541. /**
  51542. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51543. */
  51544. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51545. /**
  51546. * 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.
  51547. */
  51548. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51549. /**
  51550. * 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.
  51551. */
  51552. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51553. }
  51554. /**
  51555. * Called by the particle System when the direction is computed for the created particle.
  51556. * @param emitPower is the power of the particle (speed)
  51557. * @param worldMatrix is the world matrix of the particle system
  51558. * @param directionToUpdate is the direction vector to update with the result
  51559. * @param particle is the particle we are computed the direction for
  51560. */
  51561. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51562. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51563. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51564. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51565. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51566. };
  51567. /**
  51568. * Called by the particle System when the position is computed for the created particle.
  51569. * @param worldMatrix is the world matrix of the particle system
  51570. * @param positionToUpdate is the position vector to update with the result
  51571. * @param particle is the particle we are computed the position for
  51572. */
  51573. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51574. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51575. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51576. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51577. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51578. };
  51579. /**
  51580. * Clones the current emitter and returns a copy of it
  51581. * @returns the new emitter
  51582. */
  51583. BoxParticleEmitter.prototype.clone = function () {
  51584. var newOne = new BoxParticleEmitter();
  51585. BABYLON.Tools.DeepCopy(this, newOne);
  51586. return newOne;
  51587. };
  51588. /**
  51589. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51590. * @param effect defines the update shader
  51591. */
  51592. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51593. effect.setVector3("direction1", this.direction1);
  51594. effect.setVector3("direction2", this.direction2);
  51595. effect.setVector3("minEmitBox", this.minEmitBox);
  51596. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51597. };
  51598. /**
  51599. * Returns a string to use to update the GPU particles update shader
  51600. * @returns a string containng the defines string
  51601. */
  51602. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51603. return "#define BOXEMITTER";
  51604. };
  51605. /**
  51606. * Returns the string "BoxEmitter"
  51607. * @returns a string containing the class name
  51608. */
  51609. BoxParticleEmitter.prototype.getClassName = function () {
  51610. return "BoxEmitter";
  51611. };
  51612. /**
  51613. * Serializes the particle system to a JSON object.
  51614. * @returns the JSON object
  51615. */
  51616. BoxParticleEmitter.prototype.serialize = function () {
  51617. var serializationObject = {};
  51618. serializationObject.type = this.getClassName();
  51619. serializationObject.direction1 = this.direction1.asArray();
  51620. ;
  51621. serializationObject.direction2 = this.direction2.asArray();
  51622. ;
  51623. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51624. ;
  51625. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51626. ;
  51627. return serializationObject;
  51628. };
  51629. /**
  51630. * Parse properties from a JSON object
  51631. * @param serializationObject defines the JSON object
  51632. */
  51633. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51634. this.direction1.copyFrom(serializationObject.direction1);
  51635. this.direction2.copyFrom(serializationObject.direction2);
  51636. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51637. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51638. };
  51639. return BoxParticleEmitter;
  51640. }());
  51641. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51642. })(BABYLON || (BABYLON = {}));
  51643. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51644. var BABYLON;
  51645. (function (BABYLON) {
  51646. /**
  51647. * Particle emitter emitting particles from the inside of a cone.
  51648. * It emits the particles alongside the cone volume from the base to the particle.
  51649. * The emission direction might be randomized.
  51650. */
  51651. var ConeParticleEmitter = /** @class */ (function () {
  51652. /**
  51653. * Creates a new instance of @see ConeParticleEmitter
  51654. * @param radius the radius of the emission cone (1 by default)
  51655. * @param angles the cone base angle (PI by default)
  51656. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51657. */
  51658. function ConeParticleEmitter(radius,
  51659. /**
  51660. * The radius of the emission cone.
  51661. */
  51662. angle,
  51663. /**
  51664. * The cone base angle.
  51665. */
  51666. directionRandomizer) {
  51667. if (radius === void 0) { radius = 1; }
  51668. if (angle === void 0) { angle = Math.PI; }
  51669. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51670. this.angle = angle;
  51671. this.directionRandomizer = directionRandomizer;
  51672. this.radius = radius;
  51673. }
  51674. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51675. /**
  51676. * Gets the radius of the emission cone.
  51677. */
  51678. get: function () {
  51679. return this._radius;
  51680. },
  51681. /**
  51682. * Sets the radius of the emission cone.
  51683. */
  51684. set: function (value) {
  51685. this._radius = value;
  51686. if (this.angle !== 0) {
  51687. this._height = value / Math.tan(this.angle / 2);
  51688. }
  51689. else {
  51690. this._height = 1;
  51691. }
  51692. },
  51693. enumerable: true,
  51694. configurable: true
  51695. });
  51696. /**
  51697. * Called by the particle System when the direction is computed for the created particle.
  51698. * @param emitPower is the power of the particle (speed)
  51699. * @param worldMatrix is the world matrix of the particle system
  51700. * @param directionToUpdate is the direction vector to update with the result
  51701. * @param particle is the particle we are computed the direction for
  51702. */
  51703. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51704. if (this.angle === 0) {
  51705. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51706. }
  51707. else {
  51708. // measure the direction Vector from the emitter to the particle.
  51709. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51710. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51711. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51712. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51713. direction.x += randX;
  51714. direction.y += randY;
  51715. direction.z += randZ;
  51716. direction.normalize();
  51717. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51718. }
  51719. };
  51720. /**
  51721. * Called by the particle System when the position is computed for the created particle.
  51722. * @param worldMatrix is the world matrix of the particle system
  51723. * @param positionToUpdate is the position vector to update with the result
  51724. * @param particle is the particle we are computed the position for
  51725. */
  51726. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51727. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51728. var h = BABYLON.Scalar.RandomRange(0, 1);
  51729. // Better distribution in a cone at normal angles.
  51730. h = 1 - h * h;
  51731. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51732. radius = radius * h / this._height;
  51733. var randX = radius * Math.sin(s);
  51734. var randZ = radius * Math.cos(s);
  51735. var randY = h * this._height;
  51736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51737. };
  51738. /**
  51739. * Clones the current emitter and returns a copy of it
  51740. * @returns the new emitter
  51741. */
  51742. ConeParticleEmitter.prototype.clone = function () {
  51743. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51744. BABYLON.Tools.DeepCopy(this, newOne);
  51745. return newOne;
  51746. };
  51747. /**
  51748. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51749. * @param effect defines the update shader
  51750. */
  51751. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51752. effect.setFloat("radius", this.radius);
  51753. effect.setFloat("angle", this.angle);
  51754. effect.setFloat("height", this._height);
  51755. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51756. };
  51757. /**
  51758. * Returns a string to use to update the GPU particles update shader
  51759. * @returns a string containng the defines string
  51760. */
  51761. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51762. return "#define CONEEMITTER";
  51763. };
  51764. /**
  51765. * Returns the string "BoxEmitter"
  51766. * @returns a string containing the class name
  51767. */
  51768. ConeParticleEmitter.prototype.getClassName = function () {
  51769. return "ConeEmitter";
  51770. };
  51771. /**
  51772. * Serializes the particle system to a JSON object.
  51773. * @returns the JSON object
  51774. */
  51775. ConeParticleEmitter.prototype.serialize = function () {
  51776. var serializationObject = {};
  51777. serializationObject.type = this.getClassName();
  51778. serializationObject.radius = this.radius;
  51779. serializationObject.angle = this.angle;
  51780. serializationObject.directionRandomizer = this.directionRandomizer;
  51781. return serializationObject;
  51782. };
  51783. /**
  51784. * Parse properties from a JSON object
  51785. * @param serializationObject defines the JSON object
  51786. */
  51787. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51788. this.radius = serializationObject.radius;
  51789. this.angle = serializationObject.angle;
  51790. this.directionRandomizer = serializationObject.directionRandomizer;
  51791. };
  51792. return ConeParticleEmitter;
  51793. }());
  51794. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51795. })(BABYLON || (BABYLON = {}));
  51796. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51797. var BABYLON;
  51798. (function (BABYLON) {
  51799. /**
  51800. * Particle emitter emitting particles from the inside of a sphere.
  51801. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51802. */
  51803. var SphereParticleEmitter = /** @class */ (function () {
  51804. /**
  51805. * Creates a new instance of @see SphereParticleEmitter
  51806. * @param radius the radius of the emission sphere (1 by default)
  51807. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51808. */
  51809. function SphereParticleEmitter(
  51810. /**
  51811. * The radius of the emission sphere.
  51812. */
  51813. radius,
  51814. /**
  51815. * How much to randomize the particle direction [0-1].
  51816. */
  51817. directionRandomizer) {
  51818. if (radius === void 0) { radius = 1; }
  51819. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51820. this.radius = radius;
  51821. this.directionRandomizer = directionRandomizer;
  51822. }
  51823. /**
  51824. * Called by the particle System when the direction is computed for the created particle.
  51825. * @param emitPower is the power of the particle (speed)
  51826. * @param worldMatrix is the world matrix of the particle system
  51827. * @param directionToUpdate is the direction vector to update with the result
  51828. * @param particle is the particle we are computed the direction for
  51829. */
  51830. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51831. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51832. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51833. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51834. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51835. direction.x += randX;
  51836. direction.y += randY;
  51837. direction.z += randZ;
  51838. direction.normalize();
  51839. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51840. };
  51841. /**
  51842. * Called by the particle System when the position is computed for the created particle.
  51843. * @param worldMatrix is the world matrix of the particle system
  51844. * @param positionToUpdate is the position vector to update with the result
  51845. * @param particle is the particle we are computed the position for
  51846. */
  51847. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51848. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51849. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51850. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51851. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51852. var randY = randRadius * Math.cos(theta);
  51853. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51854. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51855. };
  51856. /**
  51857. * Clones the current emitter and returns a copy of it
  51858. * @returns the new emitter
  51859. */
  51860. SphereParticleEmitter.prototype.clone = function () {
  51861. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51862. BABYLON.Tools.DeepCopy(this, newOne);
  51863. return newOne;
  51864. };
  51865. /**
  51866. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51867. * @param effect defines the update shader
  51868. */
  51869. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51870. effect.setFloat("radius", this.radius);
  51871. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51872. };
  51873. /**
  51874. * Returns a string to use to update the GPU particles update shader
  51875. * @returns a string containng the defines string
  51876. */
  51877. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51878. return "#define SPHEREEMITTER";
  51879. };
  51880. /**
  51881. * Returns the string "SphereParticleEmitter"
  51882. * @returns a string containing the class name
  51883. */
  51884. SphereParticleEmitter.prototype.getClassName = function () {
  51885. return "SphereParticleEmitter";
  51886. };
  51887. /**
  51888. * Serializes the particle system to a JSON object.
  51889. * @returns the JSON object
  51890. */
  51891. SphereParticleEmitter.prototype.serialize = function () {
  51892. var serializationObject = {};
  51893. serializationObject.type = this.getClassName();
  51894. serializationObject.radius = this.radius;
  51895. serializationObject.directionRandomizer = this.directionRandomizer;
  51896. return serializationObject;
  51897. };
  51898. /**
  51899. * Parse properties from a JSON object
  51900. * @param serializationObject defines the JSON object
  51901. */
  51902. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51903. this.radius = serializationObject.radius;
  51904. this.directionRandomizer = serializationObject.directionRandomizer;
  51905. };
  51906. return SphereParticleEmitter;
  51907. }());
  51908. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51909. /**
  51910. * Particle emitter emitting particles from the inside of a sphere.
  51911. * It emits the particles randomly between two vectors.
  51912. */
  51913. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51914. __extends(SphereDirectedParticleEmitter, _super);
  51915. /**
  51916. * Creates a new instance of @see SphereDirectedParticleEmitter
  51917. * @param radius the radius of the emission sphere (1 by default)
  51918. * @param direction1 the min limit of the emission direction (up vector by default)
  51919. * @param direction2 the max limit of the emission direction (up vector by default)
  51920. */
  51921. function SphereDirectedParticleEmitter(radius,
  51922. /**
  51923. * The min limit of the emission direction.
  51924. */
  51925. direction1,
  51926. /**
  51927. * The max limit of the emission direction.
  51928. */
  51929. direction2) {
  51930. if (radius === void 0) { radius = 1; }
  51931. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51932. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51933. var _this = _super.call(this, radius) || this;
  51934. _this.direction1 = direction1;
  51935. _this.direction2 = direction2;
  51936. return _this;
  51937. }
  51938. /**
  51939. * Called by the particle System when the direction is computed for the created particle.
  51940. * @param emitPower is the power of the particle (speed)
  51941. * @param worldMatrix is the world matrix of the particle system
  51942. * @param directionToUpdate is the direction vector to update with the result
  51943. * @param particle is the particle we are computed the direction for
  51944. */
  51945. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51946. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51947. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51948. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51949. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51950. };
  51951. /**
  51952. * Clones the current emitter and returns a copy of it
  51953. * @returns the new emitter
  51954. */
  51955. SphereDirectedParticleEmitter.prototype.clone = function () {
  51956. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51957. BABYLON.Tools.DeepCopy(this, newOne);
  51958. return newOne;
  51959. };
  51960. /**
  51961. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51962. * @param effect defines the update shader
  51963. */
  51964. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51965. effect.setFloat("radius", this.radius);
  51966. effect.setVector3("direction1", this.direction1);
  51967. effect.setVector3("direction2", this.direction2);
  51968. };
  51969. /**
  51970. * Returns a string to use to update the GPU particles update shader
  51971. * @returns a string containng the defines string
  51972. */
  51973. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51974. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51975. };
  51976. /**
  51977. * Returns the string "SphereDirectedParticleEmitter"
  51978. * @returns a string containing the class name
  51979. */
  51980. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51981. return "SphereDirectedParticleEmitter";
  51982. };
  51983. /**
  51984. * Serializes the particle system to a JSON object.
  51985. * @returns the JSON object
  51986. */
  51987. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51988. var serializationObject = _super.prototype.serialize.call(this);
  51989. ;
  51990. serializationObject.direction1 = this.direction1.asArray();
  51991. ;
  51992. serializationObject.direction2 = this.direction2.asArray();
  51993. ;
  51994. return serializationObject;
  51995. };
  51996. /**
  51997. * Parse properties from a JSON object
  51998. * @param serializationObject defines the JSON object
  51999. */
  52000. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52001. _super.prototype.parse.call(this, serializationObject);
  52002. this.direction1.copyFrom(serializationObject.direction1);
  52003. this.direction2.copyFrom(serializationObject.direction2);
  52004. };
  52005. return SphereDirectedParticleEmitter;
  52006. }(SphereParticleEmitter));
  52007. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52008. })(BABYLON || (BABYLON = {}));
  52009. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52010. var BABYLON;
  52011. (function (BABYLON) {
  52012. /**
  52013. * Represents one particle of a solid particle system.
  52014. * @see SolidParticleSystem
  52015. */
  52016. var SolidParticle = /** @class */ (function () {
  52017. /**
  52018. * Creates a Solid Particle object.
  52019. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52020. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52021. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52022. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52023. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52024. * @param shapeId (integer) is the model shape identifier in the SPS.
  52025. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52026. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52027. */
  52028. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52029. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52030. /**
  52031. * particle global index
  52032. */
  52033. this.idx = 0;
  52034. /**
  52035. * The color of the particle
  52036. */
  52037. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52038. /**
  52039. * The world space position of the particle.
  52040. */
  52041. this.position = BABYLON.Vector3.Zero();
  52042. /**
  52043. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52044. */
  52045. this.rotation = BABYLON.Vector3.Zero();
  52046. /**
  52047. * The scaling of the particle.
  52048. */
  52049. this.scaling = BABYLON.Vector3.One();
  52050. /**
  52051. * The uvs of the particle.
  52052. */
  52053. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52054. /**
  52055. * The current speed of the particle.
  52056. */
  52057. this.velocity = BABYLON.Vector3.Zero();
  52058. /**
  52059. * The pivot point in the particle local space.
  52060. */
  52061. this.pivot = BABYLON.Vector3.Zero();
  52062. /**
  52063. * Must the particle be translated from its pivot point in its local space ?
  52064. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52065. * Default : false
  52066. */
  52067. this.translateFromPivot = false;
  52068. /**
  52069. * Is the particle active or not ?
  52070. */
  52071. this.alive = true;
  52072. /**
  52073. * Is the particle visible or not ?
  52074. */
  52075. this.isVisible = true;
  52076. /**
  52077. * Index of this particle in the global "positions" array (Internal use)
  52078. */
  52079. this._pos = 0;
  52080. /**
  52081. * Index of this particle in the global "indices" array (Internal use)
  52082. */
  52083. this._ind = 0;
  52084. /**
  52085. * ModelShape id of this particle
  52086. */
  52087. this.shapeId = 0;
  52088. /**
  52089. * Index of the particle in its shape id (Internal use)
  52090. */
  52091. this.idxInShape = 0;
  52092. /**
  52093. * Still set as invisible in order to skip useless computations (Internal use)
  52094. */
  52095. this._stillInvisible = false;
  52096. /**
  52097. * Last computed particle rotation matrix
  52098. */
  52099. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52100. /**
  52101. * Parent particle Id, if any.
  52102. * Default null.
  52103. */
  52104. this.parentId = null;
  52105. /**
  52106. * Internal global position in the SPS.
  52107. */
  52108. this._globalPosition = BABYLON.Vector3.Zero();
  52109. this.idx = particleIndex;
  52110. this._pos = positionIndex;
  52111. this._ind = indiceIndex;
  52112. this._model = model;
  52113. this.shapeId = shapeId;
  52114. this.idxInShape = idxInShape;
  52115. this._sps = sps;
  52116. if (modelBoundingInfo) {
  52117. this._modelBoundingInfo = modelBoundingInfo;
  52118. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52119. }
  52120. }
  52121. Object.defineProperty(SolidParticle.prototype, "scale", {
  52122. /**
  52123. * Legacy support, changed scale to scaling
  52124. */
  52125. get: function () {
  52126. return this.scaling;
  52127. },
  52128. /**
  52129. * Legacy support, changed scale to scaling
  52130. */
  52131. set: function (scale) {
  52132. this.scaling = scale;
  52133. },
  52134. enumerable: true,
  52135. configurable: true
  52136. });
  52137. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52138. /**
  52139. * Legacy support, changed quaternion to rotationQuaternion
  52140. */
  52141. get: function () {
  52142. return this.rotationQuaternion;
  52143. },
  52144. /**
  52145. * Legacy support, changed quaternion to rotationQuaternion
  52146. */
  52147. set: function (q) {
  52148. this.rotationQuaternion = q;
  52149. },
  52150. enumerable: true,
  52151. configurable: true
  52152. });
  52153. /**
  52154. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52155. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52156. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52157. * @returns true if it intersects
  52158. */
  52159. SolidParticle.prototype.intersectsMesh = function (target) {
  52160. if (!this._boundingInfo || !target._boundingInfo) {
  52161. return false;
  52162. }
  52163. if (this._sps._bSphereOnly) {
  52164. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52165. }
  52166. return this._boundingInfo.intersects(target._boundingInfo, false);
  52167. };
  52168. return SolidParticle;
  52169. }());
  52170. BABYLON.SolidParticle = SolidParticle;
  52171. /**
  52172. * Represents the shape of the model used by one particle of a solid particle system.
  52173. * SPS internal tool, don't use it manually.
  52174. * @see SolidParticleSystem
  52175. */
  52176. var ModelShape = /** @class */ (function () {
  52177. /**
  52178. * 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.
  52179. * SPS internal tool, don't use it manually.
  52180. * @ignore
  52181. */
  52182. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52183. /**
  52184. * length of the shape in the model indices array (internal use)
  52185. */
  52186. this._indicesLength = 0;
  52187. this.shapeID = id;
  52188. this._shape = shape;
  52189. this._indicesLength = indicesLength;
  52190. this._shapeUV = shapeUV;
  52191. this._positionFunction = posFunction;
  52192. this._vertexFunction = vtxFunction;
  52193. }
  52194. return ModelShape;
  52195. }());
  52196. BABYLON.ModelShape = ModelShape;
  52197. /**
  52198. * Represents a Depth Sorted Particle in the solid particle system.
  52199. * @see SolidParticleSystem
  52200. */
  52201. var DepthSortedParticle = /** @class */ (function () {
  52202. function DepthSortedParticle() {
  52203. /**
  52204. * Index of the particle in the "indices" array
  52205. */
  52206. this.ind = 0;
  52207. /**
  52208. * Length of the particle shape in the "indices" array
  52209. */
  52210. this.indicesLength = 0;
  52211. /**
  52212. * Squared distance from the particle to the camera
  52213. */
  52214. this.sqDistance = 0.0;
  52215. }
  52216. return DepthSortedParticle;
  52217. }());
  52218. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52219. })(BABYLON || (BABYLON = {}));
  52220. //# sourceMappingURL=babylon.solidParticle.js.map
  52221. var BABYLON;
  52222. (function (BABYLON) {
  52223. /**
  52224. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52225. *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.
  52226. * The SPS is also a particle system. It provides some methods to manage the particles.
  52227. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52228. *
  52229. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52230. */
  52231. var SolidParticleSystem = /** @class */ (function () {
  52232. /**
  52233. * Creates a SPS (Solid Particle System) object.
  52234. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52235. * @param scene (Scene) is the scene in which the SPS is added.
  52236. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52237. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52238. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52239. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52240. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52241. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52242. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52243. */
  52244. function SolidParticleSystem(name, scene, options) {
  52245. /**
  52246. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52247. * Example : var p = SPS.particles[i];
  52248. */
  52249. this.particles = new Array();
  52250. /**
  52251. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52252. */
  52253. this.nbParticles = 0;
  52254. /**
  52255. * If the particles must ever face the camera (default false). Useful for planar particles.
  52256. */
  52257. this.billboard = false;
  52258. /**
  52259. * Recompute normals when adding a shape
  52260. */
  52261. this.recomputeNormals = true;
  52262. /**
  52263. * This a counter ofr your own usage. It's not set by any SPS functions.
  52264. */
  52265. this.counter = 0;
  52266. /**
  52267. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52268. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52269. */
  52270. this.vars = {};
  52271. /**
  52272. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52273. */
  52274. this._bSphereOnly = false;
  52275. /**
  52276. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52277. */
  52278. this._bSphereRadiusFactor = 1.0;
  52279. this._positions = new Array();
  52280. this._indices = new Array();
  52281. this._normals = new Array();
  52282. this._colors = new Array();
  52283. this._uvs = new Array();
  52284. this._index = 0; // indices index
  52285. this._updatable = true;
  52286. this._pickable = false;
  52287. this._isVisibilityBoxLocked = false;
  52288. this._alwaysVisible = false;
  52289. this._depthSort = false;
  52290. this._shapeCounter = 0;
  52291. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52292. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52293. this._computeParticleColor = true;
  52294. this._computeParticleTexture = true;
  52295. this._computeParticleRotation = true;
  52296. this._computeParticleVertex = false;
  52297. this._computeBoundingBox = false;
  52298. this._depthSortParticles = true;
  52299. this._cam_axisZ = BABYLON.Vector3.Zero();
  52300. this._cam_axisY = BABYLON.Vector3.Zero();
  52301. this._cam_axisX = BABYLON.Vector3.Zero();
  52302. this._axisZ = BABYLON.Axis.Z;
  52303. this._camDir = BABYLON.Vector3.Zero();
  52304. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52305. this._rotMatrix = new BABYLON.Matrix();
  52306. this._invertMatrix = new BABYLON.Matrix();
  52307. this._rotated = BABYLON.Vector3.Zero();
  52308. this._quaternion = new BABYLON.Quaternion();
  52309. this._vertex = BABYLON.Vector3.Zero();
  52310. this._normal = BABYLON.Vector3.Zero();
  52311. this._yaw = 0.0;
  52312. this._pitch = 0.0;
  52313. this._roll = 0.0;
  52314. this._halfroll = 0.0;
  52315. this._halfpitch = 0.0;
  52316. this._halfyaw = 0.0;
  52317. this._sinRoll = 0.0;
  52318. this._cosRoll = 0.0;
  52319. this._sinPitch = 0.0;
  52320. this._cosPitch = 0.0;
  52321. this._sinYaw = 0.0;
  52322. this._cosYaw = 0.0;
  52323. this._mustUnrotateFixedNormals = false;
  52324. this._minimum = BABYLON.Vector3.Zero();
  52325. this._maximum = BABYLON.Vector3.Zero();
  52326. this._minBbox = BABYLON.Vector3.Zero();
  52327. this._maxBbox = BABYLON.Vector3.Zero();
  52328. this._particlesIntersect = false;
  52329. this._depthSortFunction = function (p1, p2) {
  52330. return (p2.sqDistance - p1.sqDistance);
  52331. };
  52332. this._needs32Bits = false;
  52333. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52334. this._scaledPivot = BABYLON.Vector3.Zero();
  52335. this._particleHasParent = false;
  52336. this.name = name;
  52337. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52338. this._camera = scene.activeCamera;
  52339. this._pickable = options ? options.isPickable : false;
  52340. this._depthSort = options ? options.enableDepthSort : false;
  52341. this._particlesIntersect = options ? options.particleIntersection : false;
  52342. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52343. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52344. if (options && options.updatable) {
  52345. this._updatable = options.updatable;
  52346. }
  52347. else {
  52348. this._updatable = true;
  52349. }
  52350. if (this._pickable) {
  52351. this.pickedParticles = [];
  52352. }
  52353. if (this._depthSort) {
  52354. this.depthSortedParticles = [];
  52355. }
  52356. }
  52357. /**
  52358. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52359. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52360. * @returns the created mesh
  52361. */
  52362. SolidParticleSystem.prototype.buildMesh = function () {
  52363. if (this.nbParticles === 0) {
  52364. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52365. this.addShape(triangle, 1);
  52366. triangle.dispose();
  52367. }
  52368. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52369. this._positions32 = new Float32Array(this._positions);
  52370. this._uvs32 = new Float32Array(this._uvs);
  52371. this._colors32 = new Float32Array(this._colors);
  52372. if (this.recomputeNormals) {
  52373. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52374. }
  52375. this._normals32 = new Float32Array(this._normals);
  52376. this._fixedNormal32 = new Float32Array(this._normals);
  52377. if (this._mustUnrotateFixedNormals) {
  52378. this._unrotateFixedNormals();
  52379. }
  52380. var vertexData = new BABYLON.VertexData();
  52381. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52382. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52383. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52384. if (this._uvs32) {
  52385. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52386. ;
  52387. }
  52388. if (this._colors32) {
  52389. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52390. }
  52391. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52392. vertexData.applyToMesh(mesh, this._updatable);
  52393. this.mesh = mesh;
  52394. this.mesh.isPickable = this._pickable;
  52395. // free memory
  52396. if (!this._depthSort) {
  52397. this._indices = null;
  52398. }
  52399. this._positions = null;
  52400. this._normals = null;
  52401. this._uvs = null;
  52402. this._colors = null;
  52403. if (!this._updatable) {
  52404. this.particles.length = 0;
  52405. }
  52406. return mesh;
  52407. };
  52408. /**
  52409. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52410. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52411. * Thus the particles generated from `digest()` have their property `position` set yet.
  52412. * @param mesh ( Mesh ) is the mesh to be digested
  52413. * @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
  52414. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52415. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52416. * @returns the current SPS
  52417. */
  52418. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52419. var size = (options && options.facetNb) || 1;
  52420. var number = (options && options.number) || 0;
  52421. var delta = (options && options.delta) || 0;
  52422. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52423. var meshInd = mesh.getIndices();
  52424. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52425. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52426. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52427. var f = 0; // facet counter
  52428. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52429. // compute size from number
  52430. if (number) {
  52431. number = (number > totalFacets) ? totalFacets : number;
  52432. size = Math.round(totalFacets / number);
  52433. delta = 0;
  52434. }
  52435. else {
  52436. size = (size > totalFacets) ? totalFacets : size;
  52437. }
  52438. var facetPos = []; // submesh positions
  52439. var facetInd = []; // submesh indices
  52440. var facetUV = []; // submesh UV
  52441. var facetCol = []; // submesh colors
  52442. var barycenter = BABYLON.Vector3.Zero();
  52443. var sizeO = size;
  52444. while (f < totalFacets) {
  52445. size = sizeO + Math.floor((1 + delta) * Math.random());
  52446. if (f > totalFacets - size) {
  52447. size = totalFacets - f;
  52448. }
  52449. // reset temp arrays
  52450. facetPos.length = 0;
  52451. facetInd.length = 0;
  52452. facetUV.length = 0;
  52453. facetCol.length = 0;
  52454. // iterate over "size" facets
  52455. var fi = 0;
  52456. for (var j = f * 3; j < (f + size) * 3; j++) {
  52457. facetInd.push(fi);
  52458. var i = meshInd[j];
  52459. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52460. if (meshUV) {
  52461. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52462. }
  52463. if (meshCol) {
  52464. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52465. }
  52466. fi++;
  52467. }
  52468. // create a model shape for each single particle
  52469. var idx = this.nbParticles;
  52470. var shape = this._posToShape(facetPos);
  52471. var shapeUV = this._uvsToShapeUV(facetUV);
  52472. // compute the barycenter of the shape
  52473. var v;
  52474. for (v = 0; v < shape.length; v++) {
  52475. barycenter.addInPlace(shape[v]);
  52476. }
  52477. barycenter.scaleInPlace(1 / shape.length);
  52478. // shift the shape from its barycenter to the origin
  52479. for (v = 0; v < shape.length; v++) {
  52480. shape[v].subtractInPlace(barycenter);
  52481. }
  52482. var bInfo;
  52483. if (this._particlesIntersect) {
  52484. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52485. }
  52486. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52487. // add the particle in the SPS
  52488. var currentPos = this._positions.length;
  52489. var currentInd = this._indices.length;
  52490. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52491. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52492. // initialize the particle position
  52493. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52494. this._index += shape.length;
  52495. idx++;
  52496. this.nbParticles++;
  52497. this._shapeCounter++;
  52498. f += size;
  52499. }
  52500. return this;
  52501. };
  52502. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52503. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52504. var index = 0;
  52505. var idx = 0;
  52506. for (var p = 0; p < this.particles.length; p++) {
  52507. this._particle = this.particles[p];
  52508. this._shape = this._particle._model._shape;
  52509. if (this._particle.rotationQuaternion) {
  52510. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52511. }
  52512. else {
  52513. this._yaw = this._particle.rotation.y;
  52514. this._pitch = this._particle.rotation.x;
  52515. this._roll = this._particle.rotation.z;
  52516. this._quaternionRotationYPR();
  52517. }
  52518. this._quaternionToRotationMatrix();
  52519. this._rotMatrix.invertToRef(this._invertMatrix);
  52520. for (var pt = 0; pt < this._shape.length; pt++) {
  52521. idx = index + pt * 3;
  52522. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52523. this._fixedNormal32[idx] = this._normal.x;
  52524. this._fixedNormal32[idx + 1] = this._normal.y;
  52525. this._fixedNormal32[idx + 2] = this._normal.z;
  52526. }
  52527. index = idx + 3;
  52528. }
  52529. };
  52530. //reset copy
  52531. SolidParticleSystem.prototype._resetCopy = function () {
  52532. this._copy.position.x = 0;
  52533. this._copy.position.y = 0;
  52534. this._copy.position.z = 0;
  52535. this._copy.rotation.x = 0;
  52536. this._copy.rotation.y = 0;
  52537. this._copy.rotation.z = 0;
  52538. this._copy.rotationQuaternion = null;
  52539. this._copy.scaling.x = 1.0;
  52540. this._copy.scaling.y = 1.0;
  52541. this._copy.scaling.z = 1.0;
  52542. this._copy.uvs.x = 0;
  52543. this._copy.uvs.y = 0;
  52544. this._copy.uvs.z = 1.0;
  52545. this._copy.uvs.w = 1.0;
  52546. this._copy.color = null;
  52547. this._copy.translateFromPivot = false;
  52548. };
  52549. // _meshBuilder : inserts the shape model in the global SPS mesh
  52550. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52551. var i;
  52552. var u = 0;
  52553. var c = 0;
  52554. var n = 0;
  52555. this._resetCopy();
  52556. if (options && options.positionFunction) {
  52557. options.positionFunction(this._copy, idx, idxInShape);
  52558. this._mustUnrotateFixedNormals = true;
  52559. }
  52560. if (this._copy.rotationQuaternion) {
  52561. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52562. }
  52563. else {
  52564. this._yaw = this._copy.rotation.y;
  52565. this._pitch = this._copy.rotation.x;
  52566. this._roll = this._copy.rotation.z;
  52567. this._quaternionRotationYPR();
  52568. }
  52569. this._quaternionToRotationMatrix();
  52570. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52571. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52572. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52573. if (this._copy.translateFromPivot) {
  52574. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52575. }
  52576. else {
  52577. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52578. }
  52579. for (i = 0; i < shape.length; i++) {
  52580. this._vertex.x = shape[i].x;
  52581. this._vertex.y = shape[i].y;
  52582. this._vertex.z = shape[i].z;
  52583. if (options && options.vertexFunction) {
  52584. options.vertexFunction(this._copy, this._vertex, i);
  52585. }
  52586. this._vertex.x *= this._copy.scaling.x;
  52587. this._vertex.y *= this._copy.scaling.y;
  52588. this._vertex.z *= this._copy.scaling.z;
  52589. this._vertex.x -= this._scaledPivot.x;
  52590. this._vertex.y -= this._scaledPivot.y;
  52591. this._vertex.z -= this._scaledPivot.z;
  52592. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52593. this._rotated.addInPlace(this._pivotBackTranslation);
  52594. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52595. if (meshUV) {
  52596. 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);
  52597. u += 2;
  52598. }
  52599. if (this._copy.color) {
  52600. this._color = this._copy.color;
  52601. }
  52602. else if (meshCol && meshCol[c] !== undefined) {
  52603. this._color.r = meshCol[c];
  52604. this._color.g = meshCol[c + 1];
  52605. this._color.b = meshCol[c + 2];
  52606. this._color.a = meshCol[c + 3];
  52607. }
  52608. else {
  52609. this._color.r = 1.0;
  52610. this._color.g = 1.0;
  52611. this._color.b = 1.0;
  52612. this._color.a = 1.0;
  52613. }
  52614. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52615. c += 4;
  52616. if (!this.recomputeNormals && meshNor) {
  52617. this._normal.x = meshNor[n];
  52618. this._normal.y = meshNor[n + 1];
  52619. this._normal.z = meshNor[n + 2];
  52620. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52621. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52622. n += 3;
  52623. }
  52624. }
  52625. for (i = 0; i < meshInd.length; i++) {
  52626. var current_ind = p + meshInd[i];
  52627. indices.push(current_ind);
  52628. if (current_ind > 65535) {
  52629. this._needs32Bits = true;
  52630. }
  52631. }
  52632. if (this._pickable) {
  52633. var nbfaces = meshInd.length / 3;
  52634. for (i = 0; i < nbfaces; i++) {
  52635. this.pickedParticles.push({ idx: idx, faceId: i });
  52636. }
  52637. }
  52638. if (this._depthSort) {
  52639. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52640. }
  52641. return this._copy;
  52642. };
  52643. // returns a shape array from positions array
  52644. SolidParticleSystem.prototype._posToShape = function (positions) {
  52645. var shape = [];
  52646. for (var i = 0; i < positions.length; i += 3) {
  52647. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52648. }
  52649. return shape;
  52650. };
  52651. // returns a shapeUV array from a Vector4 uvs
  52652. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52653. var shapeUV = [];
  52654. if (uvs) {
  52655. for (var i = 0; i < uvs.length; i++)
  52656. shapeUV.push(uvs[i]);
  52657. }
  52658. return shapeUV;
  52659. };
  52660. // adds a new particle object in the particles array
  52661. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52662. if (bInfo === void 0) { bInfo = null; }
  52663. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52664. this.particles.push(sp);
  52665. return sp;
  52666. };
  52667. /**
  52668. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52669. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52670. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52671. * @param nb (positive integer) the number of particles to be created from this model
  52672. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52673. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52674. * @returns the number of shapes in the system
  52675. */
  52676. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52677. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52678. var meshInd = mesh.getIndices();
  52679. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52680. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52681. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52682. var bbInfo;
  52683. if (this._particlesIntersect) {
  52684. bbInfo = mesh.getBoundingInfo();
  52685. }
  52686. var shape = this._posToShape(meshPos);
  52687. var shapeUV = this._uvsToShapeUV(meshUV);
  52688. var posfunc = options ? options.positionFunction : null;
  52689. var vtxfunc = options ? options.vertexFunction : null;
  52690. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52691. // particles
  52692. var sp;
  52693. var currentCopy;
  52694. var idx = this.nbParticles;
  52695. for (var i = 0; i < nb; i++) {
  52696. var currentPos = this._positions.length;
  52697. var currentInd = this._indices.length;
  52698. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52699. if (this._updatable) {
  52700. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52701. sp.position.copyFrom(currentCopy.position);
  52702. sp.rotation.copyFrom(currentCopy.rotation);
  52703. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52704. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52705. }
  52706. if (currentCopy.color && sp.color) {
  52707. sp.color.copyFrom(currentCopy.color);
  52708. }
  52709. sp.scaling.copyFrom(currentCopy.scaling);
  52710. sp.uvs.copyFrom(currentCopy.uvs);
  52711. }
  52712. this._index += shape.length;
  52713. idx++;
  52714. }
  52715. this.nbParticles += nb;
  52716. this._shapeCounter++;
  52717. return this._shapeCounter - 1;
  52718. };
  52719. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52720. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52721. this._resetCopy();
  52722. if (particle._model._positionFunction) {
  52723. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52724. }
  52725. if (this._copy.rotationQuaternion) {
  52726. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52727. }
  52728. else {
  52729. this._yaw = this._copy.rotation.y;
  52730. this._pitch = this._copy.rotation.x;
  52731. this._roll = this._copy.rotation.z;
  52732. this._quaternionRotationYPR();
  52733. }
  52734. this._quaternionToRotationMatrix();
  52735. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52736. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52737. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52738. if (this._copy.translateFromPivot) {
  52739. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52740. }
  52741. else {
  52742. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52743. }
  52744. this._shape = particle._model._shape;
  52745. for (var pt = 0; pt < this._shape.length; pt++) {
  52746. this._vertex.x = this._shape[pt].x;
  52747. this._vertex.y = this._shape[pt].y;
  52748. this._vertex.z = this._shape[pt].z;
  52749. if (particle._model._vertexFunction) {
  52750. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52751. }
  52752. this._vertex.x *= this._copy.scaling.x;
  52753. this._vertex.y *= this._copy.scaling.y;
  52754. this._vertex.z *= this._copy.scaling.z;
  52755. this._vertex.x -= this._scaledPivot.x;
  52756. this._vertex.y -= this._scaledPivot.y;
  52757. this._vertex.z -= this._scaledPivot.z;
  52758. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52759. this._rotated.addInPlace(this._pivotBackTranslation);
  52760. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52761. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52762. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52763. }
  52764. particle.position.x = 0.0;
  52765. particle.position.y = 0.0;
  52766. particle.position.z = 0.0;
  52767. particle.rotation.x = 0.0;
  52768. particle.rotation.y = 0.0;
  52769. particle.rotation.z = 0.0;
  52770. particle.rotationQuaternion = null;
  52771. particle.scaling.x = 1.0;
  52772. particle.scaling.y = 1.0;
  52773. particle.scaling.z = 1.0;
  52774. particle.uvs.x = 0.0;
  52775. particle.uvs.y = 0.0;
  52776. particle.uvs.z = 1.0;
  52777. particle.uvs.w = 1.0;
  52778. particle.pivot.x = 0.0;
  52779. particle.pivot.y = 0.0;
  52780. particle.pivot.z = 0.0;
  52781. particle.translateFromPivot = false;
  52782. particle.parentId = null;
  52783. };
  52784. /**
  52785. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52786. * @returns the SPS.
  52787. */
  52788. SolidParticleSystem.prototype.rebuildMesh = function () {
  52789. for (var p = 0; p < this.particles.length; p++) {
  52790. this._rebuildParticle(this.particles[p]);
  52791. }
  52792. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52793. return this;
  52794. };
  52795. /**
  52796. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52797. * This method calls `updateParticle()` for each particle of the SPS.
  52798. * For an animated SPS, it is usually called within the render loop.
  52799. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52800. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52801. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52802. * @returns the SPS.
  52803. */
  52804. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52805. if (start === void 0) { start = 0; }
  52806. if (end === void 0) { end = this.nbParticles - 1; }
  52807. if (update === void 0) { update = true; }
  52808. if (!this._updatable) {
  52809. return this;
  52810. }
  52811. // custom beforeUpdate
  52812. this.beforeUpdateParticles(start, end, update);
  52813. this._cam_axisX.x = 1.0;
  52814. this._cam_axisX.y = 0.0;
  52815. this._cam_axisX.z = 0.0;
  52816. this._cam_axisY.x = 0.0;
  52817. this._cam_axisY.y = 1.0;
  52818. this._cam_axisY.z = 0.0;
  52819. this._cam_axisZ.x = 0.0;
  52820. this._cam_axisZ.y = 0.0;
  52821. this._cam_axisZ.z = 1.0;
  52822. // cases when the World Matrix is to be computed first
  52823. if (this.billboard || this._depthSort) {
  52824. this.mesh.computeWorldMatrix(true);
  52825. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52826. }
  52827. // if the particles will always face the camera
  52828. if (this.billboard) {
  52829. // compute the camera position and un-rotate it by the current mesh rotation
  52830. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52831. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52832. this._cam_axisZ.normalize();
  52833. // same for camera up vector extracted from the cam view matrix
  52834. var view = this._camera.getViewMatrix(true);
  52835. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52836. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52837. this._cam_axisY.normalize();
  52838. this._cam_axisX.normalize();
  52839. }
  52840. // if depthSort, compute the camera global position in the mesh local system
  52841. if (this._depthSort) {
  52842. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52843. }
  52844. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52845. var idx = 0; // current position index in the global array positions32
  52846. var index = 0; // position start index in the global array positions32 of the current particle
  52847. var colidx = 0; // current color index in the global array colors32
  52848. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52849. var uvidx = 0; // current uv index in the global array uvs32
  52850. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52851. var pt = 0; // current index in the particle model shape
  52852. if (this.mesh.isFacetDataEnabled) {
  52853. this._computeBoundingBox = true;
  52854. }
  52855. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52856. if (this._computeBoundingBox) {
  52857. if (start == 0 && end == this.nbParticles - 1) {
  52858. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52859. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52860. }
  52861. else {
  52862. if (this.mesh._boundingInfo) {
  52863. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52864. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52865. }
  52866. }
  52867. }
  52868. // particle loop
  52869. index = this.particles[start]._pos;
  52870. var vpos = (index / 3) | 0;
  52871. colorIndex = vpos * 4;
  52872. uvIndex = vpos * 2;
  52873. for (var p = start; p <= end; p++) {
  52874. this._particle = this.particles[p];
  52875. this._shape = this._particle._model._shape;
  52876. this._shapeUV = this._particle._model._shapeUV;
  52877. // call to custom user function to update the particle properties
  52878. this.updateParticle(this._particle);
  52879. // camera-particle distance for depth sorting
  52880. if (this._depthSort && this._depthSortParticles) {
  52881. var dsp = this.depthSortedParticles[p];
  52882. dsp.ind = this._particle._ind;
  52883. dsp.indicesLength = this._particle._model._indicesLength;
  52884. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52885. }
  52886. // skip the computations for inactive or already invisible particles
  52887. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52888. // increment indexes for the next particle
  52889. pt = this._shape.length;
  52890. index += pt * 3;
  52891. colorIndex += pt * 4;
  52892. uvIndex += pt * 2;
  52893. continue;
  52894. }
  52895. if (this._particle.isVisible) {
  52896. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52897. this._particleHasParent = (this._particle.parentId !== null);
  52898. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52899. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52900. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52901. // particle rotation matrix
  52902. if (this.billboard) {
  52903. this._particle.rotation.x = 0.0;
  52904. this._particle.rotation.y = 0.0;
  52905. }
  52906. if (this._computeParticleRotation || this.billboard) {
  52907. if (this._particle.rotationQuaternion) {
  52908. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52909. }
  52910. else {
  52911. this._yaw = this._particle.rotation.y;
  52912. this._pitch = this._particle.rotation.x;
  52913. this._roll = this._particle.rotation.z;
  52914. this._quaternionRotationYPR();
  52915. }
  52916. this._quaternionToRotationMatrix();
  52917. }
  52918. if (this._particleHasParent) {
  52919. this._parent = this.particles[this._particle.parentId];
  52920. 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];
  52921. 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];
  52922. 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];
  52923. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52924. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52925. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52926. if (this._computeParticleRotation || this.billboard) {
  52927. 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];
  52928. 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];
  52929. 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];
  52930. 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];
  52931. 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];
  52932. 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];
  52933. 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];
  52934. 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];
  52935. 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];
  52936. }
  52937. }
  52938. else {
  52939. this._particle._globalPosition.x = this._particle.position.x;
  52940. this._particle._globalPosition.y = this._particle.position.y;
  52941. this._particle._globalPosition.z = this._particle.position.z;
  52942. if (this._computeParticleRotation || this.billboard) {
  52943. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52944. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52945. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52946. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52947. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52948. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52949. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52950. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52951. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52952. }
  52953. }
  52954. if (this._particle.translateFromPivot) {
  52955. this._pivotBackTranslation.x = 0.0;
  52956. this._pivotBackTranslation.y = 0.0;
  52957. this._pivotBackTranslation.z = 0.0;
  52958. }
  52959. else {
  52960. this._pivotBackTranslation.x = this._scaledPivot.x;
  52961. this._pivotBackTranslation.y = this._scaledPivot.y;
  52962. this._pivotBackTranslation.z = this._scaledPivot.z;
  52963. }
  52964. // particle vertex loop
  52965. for (pt = 0; pt < this._shape.length; pt++) {
  52966. idx = index + pt * 3;
  52967. colidx = colorIndex + pt * 4;
  52968. uvidx = uvIndex + pt * 2;
  52969. this._vertex.x = this._shape[pt].x;
  52970. this._vertex.y = this._shape[pt].y;
  52971. this._vertex.z = this._shape[pt].z;
  52972. if (this._computeParticleVertex) {
  52973. this.updateParticleVertex(this._particle, this._vertex, pt);
  52974. }
  52975. // positions
  52976. this._vertex.x *= this._particle.scaling.x;
  52977. this._vertex.y *= this._particle.scaling.y;
  52978. this._vertex.z *= this._particle.scaling.z;
  52979. this._vertex.x -= this._scaledPivot.x;
  52980. this._vertex.y -= this._scaledPivot.y;
  52981. this._vertex.z -= this._scaledPivot.z;
  52982. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52983. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52984. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52985. this._rotated.x += this._pivotBackTranslation.x;
  52986. this._rotated.y += this._pivotBackTranslation.y;
  52987. this._rotated.z += this._pivotBackTranslation.z;
  52988. 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;
  52989. 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;
  52990. 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;
  52991. if (this._computeBoundingBox) {
  52992. if (this._positions32[idx] < this._minimum.x) {
  52993. this._minimum.x = this._positions32[idx];
  52994. }
  52995. if (this._positions32[idx] > this._maximum.x) {
  52996. this._maximum.x = this._positions32[idx];
  52997. }
  52998. if (this._positions32[idx + 1] < this._minimum.y) {
  52999. this._minimum.y = this._positions32[idx + 1];
  53000. }
  53001. if (this._positions32[idx + 1] > this._maximum.y) {
  53002. this._maximum.y = this._positions32[idx + 1];
  53003. }
  53004. if (this._positions32[idx + 2] < this._minimum.z) {
  53005. this._minimum.z = this._positions32[idx + 2];
  53006. }
  53007. if (this._positions32[idx + 2] > this._maximum.z) {
  53008. this._maximum.z = this._positions32[idx + 2];
  53009. }
  53010. }
  53011. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53012. if (!this._computeParticleVertex) {
  53013. this._normal.x = this._fixedNormal32[idx];
  53014. this._normal.y = this._fixedNormal32[idx + 1];
  53015. this._normal.z = this._fixedNormal32[idx + 2];
  53016. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53017. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53018. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53019. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53020. 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;
  53021. 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;
  53022. }
  53023. if (this._computeParticleColor && this._particle.color) {
  53024. this._colors32[colidx] = this._particle.color.r;
  53025. this._colors32[colidx + 1] = this._particle.color.g;
  53026. this._colors32[colidx + 2] = this._particle.color.b;
  53027. this._colors32[colidx + 3] = this._particle.color.a;
  53028. }
  53029. if (this._computeParticleTexture) {
  53030. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53031. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53032. }
  53033. }
  53034. }
  53035. else {
  53036. this._particle._stillInvisible = true; // mark the particle as invisible
  53037. for (pt = 0; pt < this._shape.length; pt++) {
  53038. idx = index + pt * 3;
  53039. colidx = colorIndex + pt * 4;
  53040. uvidx = uvIndex + pt * 2;
  53041. this._positions32[idx] = 0.0;
  53042. this._positions32[idx + 1] = 0.0;
  53043. this._positions32[idx + 2] = 0.0;
  53044. this._normals32[idx] = 0.0;
  53045. this._normals32[idx + 1] = 0.0;
  53046. this._normals32[idx + 2] = 0.0;
  53047. if (this._computeParticleColor && this._particle.color) {
  53048. this._colors32[colidx] = this._particle.color.r;
  53049. this._colors32[colidx + 1] = this._particle.color.g;
  53050. this._colors32[colidx + 2] = this._particle.color.b;
  53051. this._colors32[colidx + 3] = this._particle.color.a;
  53052. }
  53053. if (this._computeParticleTexture) {
  53054. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53055. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53056. }
  53057. }
  53058. }
  53059. // if the particle intersections must be computed : update the bbInfo
  53060. if (this._particlesIntersect) {
  53061. var bInfo = this._particle._boundingInfo;
  53062. var bBox = bInfo.boundingBox;
  53063. var bSphere = bInfo.boundingSphere;
  53064. if (!this._bSphereOnly) {
  53065. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53066. for (var b = 0; b < bBox.vectors.length; b++) {
  53067. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53068. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53069. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53070. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53071. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53072. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53073. 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;
  53074. 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;
  53075. 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;
  53076. }
  53077. bBox._update(this.mesh._worldMatrix);
  53078. }
  53079. // place and scale the particle bouding sphere in the SPS local system, then update it
  53080. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53081. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53082. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53083. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53084. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53085. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53086. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53087. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53088. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53089. 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));
  53090. bSphere._update(this.mesh._worldMatrix);
  53091. }
  53092. // increment indexes for the next particle
  53093. index = idx + 3;
  53094. colorIndex = colidx + 4;
  53095. uvIndex = uvidx + 2;
  53096. }
  53097. // if the VBO must be updated
  53098. if (update) {
  53099. if (this._computeParticleColor) {
  53100. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53101. }
  53102. if (this._computeParticleTexture) {
  53103. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53104. }
  53105. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53106. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53107. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53108. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53109. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53110. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53111. for (var i = 0; i < this._normals32.length; i++) {
  53112. this._fixedNormal32[i] = this._normals32[i];
  53113. }
  53114. }
  53115. if (!this.mesh.areNormalsFrozen) {
  53116. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53117. }
  53118. }
  53119. if (this._depthSort && this._depthSortParticles) {
  53120. this.depthSortedParticles.sort(this._depthSortFunction);
  53121. var dspl = this.depthSortedParticles.length;
  53122. var sorted = 0;
  53123. var lind = 0;
  53124. var sind = 0;
  53125. var sid = 0;
  53126. for (sorted = 0; sorted < dspl; sorted++) {
  53127. lind = this.depthSortedParticles[sorted].indicesLength;
  53128. sind = this.depthSortedParticles[sorted].ind;
  53129. for (var i = 0; i < lind; i++) {
  53130. this._indices32[sid] = this._indices[sind + i];
  53131. sid++;
  53132. }
  53133. }
  53134. this.mesh.updateIndices(this._indices32);
  53135. }
  53136. }
  53137. if (this._computeBoundingBox) {
  53138. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53139. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53140. }
  53141. this.afterUpdateParticles(start, end, update);
  53142. return this;
  53143. };
  53144. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53145. this._halfroll = this._roll * 0.5;
  53146. this._halfpitch = this._pitch * 0.5;
  53147. this._halfyaw = this._yaw * 0.5;
  53148. this._sinRoll = Math.sin(this._halfroll);
  53149. this._cosRoll = Math.cos(this._halfroll);
  53150. this._sinPitch = Math.sin(this._halfpitch);
  53151. this._cosPitch = Math.cos(this._halfpitch);
  53152. this._sinYaw = Math.sin(this._halfyaw);
  53153. this._cosYaw = Math.cos(this._halfyaw);
  53154. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53155. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53156. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53157. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53158. };
  53159. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53160. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53161. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53162. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53163. this._rotMatrix.m[3] = 0;
  53164. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53165. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53166. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53167. this._rotMatrix.m[7] = 0;
  53168. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53169. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53170. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53171. this._rotMatrix.m[11] = 0;
  53172. this._rotMatrix.m[12] = 0;
  53173. this._rotMatrix.m[13] = 0;
  53174. this._rotMatrix.m[14] = 0;
  53175. this._rotMatrix.m[15] = 1.0;
  53176. };
  53177. /**
  53178. * Disposes the SPS.
  53179. */
  53180. SolidParticleSystem.prototype.dispose = function () {
  53181. this.mesh.dispose();
  53182. this.vars = null;
  53183. // drop references to internal big arrays for the GC
  53184. this._positions = null;
  53185. this._indices = null;
  53186. this._normals = null;
  53187. this._uvs = null;
  53188. this._colors = null;
  53189. this._indices32 = null;
  53190. this._positions32 = null;
  53191. this._normals32 = null;
  53192. this._fixedNormal32 = null;
  53193. this._uvs32 = null;
  53194. this._colors32 = null;
  53195. this.pickedParticles = null;
  53196. };
  53197. /**
  53198. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53199. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53200. * @returns the SPS.
  53201. */
  53202. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53203. if (!this._isVisibilityBoxLocked) {
  53204. this.mesh.refreshBoundingInfo();
  53205. }
  53206. return this;
  53207. };
  53208. /**
  53209. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53210. * @param size the size (float) of the visibility box
  53211. * note : this doesn't lock the SPS mesh bounding box.
  53212. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53213. */
  53214. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53215. var vis = size / 2;
  53216. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53217. };
  53218. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53219. /**
  53220. * Gets whether the SPS as always visible or not
  53221. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53222. */
  53223. get: function () {
  53224. return this._alwaysVisible;
  53225. },
  53226. /**
  53227. * Sets the SPS as always visible or not
  53228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53229. */
  53230. set: function (val) {
  53231. this._alwaysVisible = val;
  53232. this.mesh.alwaysSelectAsActiveMesh = val;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53238. /**
  53239. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53240. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53241. */
  53242. get: function () {
  53243. return this._isVisibilityBoxLocked;
  53244. },
  53245. /**
  53246. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53247. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53248. */
  53249. set: function (val) {
  53250. this._isVisibilityBoxLocked = val;
  53251. var boundingInfo = this.mesh.getBoundingInfo();
  53252. boundingInfo.isLocked = val;
  53253. },
  53254. enumerable: true,
  53255. configurable: true
  53256. });
  53257. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53258. /**
  53259. * Gets if `setParticles()` computes the particle rotations or not.
  53260. * Default value : true. The SPS is faster when it's set to false.
  53261. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53262. */
  53263. get: function () {
  53264. return this._computeParticleRotation;
  53265. },
  53266. /**
  53267. * Tells to `setParticles()` to compute the particle rotations or not.
  53268. * Default value : true. The SPS is faster when it's set to false.
  53269. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53270. */
  53271. set: function (val) {
  53272. this._computeParticleRotation = val;
  53273. },
  53274. enumerable: true,
  53275. configurable: true
  53276. });
  53277. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53278. /**
  53279. * Gets if `setParticles()` computes the particle colors or not.
  53280. * Default value : true. The SPS is faster when it's set to false.
  53281. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53282. */
  53283. get: function () {
  53284. return this._computeParticleColor;
  53285. },
  53286. /**
  53287. * Tells to `setParticles()` to compute the particle colors or not.
  53288. * Default value : true. The SPS is faster when it's set to false.
  53289. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53290. */
  53291. set: function (val) {
  53292. this._computeParticleColor = val;
  53293. },
  53294. enumerable: true,
  53295. configurable: true
  53296. });
  53297. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53298. /**
  53299. * Gets if `setParticles()` computes the particle textures or not.
  53300. * Default value : true. The SPS is faster when it's set to false.
  53301. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53302. */
  53303. get: function () {
  53304. return this._computeParticleTexture;
  53305. },
  53306. set: function (val) {
  53307. this._computeParticleTexture = val;
  53308. },
  53309. enumerable: true,
  53310. configurable: true
  53311. });
  53312. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53313. /**
  53314. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53315. * Default value : false. The SPS is faster when it's set to false.
  53316. * Note : the particle custom vertex positions aren't stored values.
  53317. */
  53318. get: function () {
  53319. return this._computeParticleVertex;
  53320. },
  53321. /**
  53322. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53323. * Default value : false. The SPS is faster when it's set to false.
  53324. * Note : the particle custom vertex positions aren't stored values.
  53325. */
  53326. set: function (val) {
  53327. this._computeParticleVertex = val;
  53328. },
  53329. enumerable: true,
  53330. configurable: true
  53331. });
  53332. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53333. /**
  53334. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53335. */
  53336. get: function () {
  53337. return this._computeBoundingBox;
  53338. },
  53339. /**
  53340. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53341. */
  53342. set: function (val) {
  53343. this._computeBoundingBox = val;
  53344. },
  53345. enumerable: true,
  53346. configurable: true
  53347. });
  53348. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53349. /**
  53350. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53351. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53352. * Default : `true`
  53353. */
  53354. get: function () {
  53355. return this._depthSortParticles;
  53356. },
  53357. /**
  53358. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53359. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53360. * Default : `true`
  53361. */
  53362. set: function (val) {
  53363. this._depthSortParticles = val;
  53364. },
  53365. enumerable: true,
  53366. configurable: true
  53367. });
  53368. // =======================================================================
  53369. // Particle behavior logic
  53370. // these following methods may be overwritten by the user to fit his needs
  53371. /**
  53372. * This function does nothing. It may be overwritten to set all the particle first values.
  53373. * The SPS doesn't call this function, you may have to call it by your own.
  53374. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53375. */
  53376. SolidParticleSystem.prototype.initParticles = function () {
  53377. };
  53378. /**
  53379. * This function does nothing. It may be overwritten to recycle a particle.
  53380. * The SPS doesn't call this function, you may have to call it by your own.
  53381. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53382. * @param particle The particle to recycle
  53383. * @returns the recycled particle
  53384. */
  53385. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53386. return particle;
  53387. };
  53388. /**
  53389. * Updates a particle : this function should be overwritten by the user.
  53390. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53391. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53392. * @example : just set a particle position or velocity and recycle conditions
  53393. * @param particle The particle to update
  53394. * @returns the updated particle
  53395. */
  53396. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53397. return particle;
  53398. };
  53399. /**
  53400. * Updates a vertex of a particle : it can be overwritten by the user.
  53401. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53402. * @param particle the current particle
  53403. * @param vertex the current index of the current particle
  53404. * @param pt the index of the current vertex in the particle shape
  53405. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53406. * @example : just set a vertex particle position
  53407. * @returns the updated vertex
  53408. */
  53409. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53410. return vertex;
  53411. };
  53412. /**
  53413. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53414. * This does nothing and may be overwritten by the user.
  53415. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53416. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53417. * @param update the boolean update value actually passed to setParticles()
  53418. */
  53419. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53420. };
  53421. /**
  53422. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53423. * This will be passed three parameters.
  53424. * This does nothing and may be overwritten by the user.
  53425. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53426. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53427. * @param update the boolean update value actually passed to setParticles()
  53428. */
  53429. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53430. };
  53431. return SolidParticleSystem;
  53432. }());
  53433. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53434. })(BABYLON || (BABYLON = {}));
  53435. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53436. var BABYLON;
  53437. (function (BABYLON) {
  53438. var ShaderMaterial = /** @class */ (function (_super) {
  53439. __extends(ShaderMaterial, _super);
  53440. function ShaderMaterial(name, scene, shaderPath, options) {
  53441. var _this = _super.call(this, name, scene) || this;
  53442. _this._textures = {};
  53443. _this._textureArrays = {};
  53444. _this._floats = {};
  53445. _this._ints = {};
  53446. _this._floatsArrays = {};
  53447. _this._colors3 = {};
  53448. _this._colors3Arrays = {};
  53449. _this._colors4 = {};
  53450. _this._vectors2 = {};
  53451. _this._vectors3 = {};
  53452. _this._vectors4 = {};
  53453. _this._matrices = {};
  53454. _this._matrices3x3 = {};
  53455. _this._matrices2x2 = {};
  53456. _this._vectors2Arrays = {};
  53457. _this._vectors3Arrays = {};
  53458. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53459. _this._shaderPath = shaderPath;
  53460. options.needAlphaBlending = options.needAlphaBlending || false;
  53461. options.needAlphaTesting = options.needAlphaTesting || false;
  53462. options.attributes = options.attributes || ["position", "normal", "uv"];
  53463. options.uniforms = options.uniforms || ["worldViewProjection"];
  53464. options.uniformBuffers = options.uniformBuffers || [];
  53465. options.samplers = options.samplers || [];
  53466. options.defines = options.defines || [];
  53467. _this._options = options;
  53468. return _this;
  53469. }
  53470. ShaderMaterial.prototype.getClassName = function () {
  53471. return "ShaderMaterial";
  53472. };
  53473. ShaderMaterial.prototype.needAlphaBlending = function () {
  53474. return this._options.needAlphaBlending;
  53475. };
  53476. ShaderMaterial.prototype.needAlphaTesting = function () {
  53477. return this._options.needAlphaTesting;
  53478. };
  53479. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53480. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53481. this._options.uniforms.push(uniformName);
  53482. }
  53483. };
  53484. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53485. if (this._options.samplers.indexOf(name) === -1) {
  53486. this._options.samplers.push(name);
  53487. }
  53488. this._textures[name] = texture;
  53489. return this;
  53490. };
  53491. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53492. if (this._options.samplers.indexOf(name) === -1) {
  53493. this._options.samplers.push(name);
  53494. }
  53495. this._checkUniform(name);
  53496. this._textureArrays[name] = textures;
  53497. return this;
  53498. };
  53499. ShaderMaterial.prototype.setFloat = function (name, value) {
  53500. this._checkUniform(name);
  53501. this._floats[name] = value;
  53502. return this;
  53503. };
  53504. ShaderMaterial.prototype.setInt = function (name, value) {
  53505. this._checkUniform(name);
  53506. this._ints[name] = value;
  53507. return this;
  53508. };
  53509. ShaderMaterial.prototype.setFloats = function (name, value) {
  53510. this._checkUniform(name);
  53511. this._floatsArrays[name] = value;
  53512. return this;
  53513. };
  53514. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53515. this._checkUniform(name);
  53516. this._colors3[name] = value;
  53517. return this;
  53518. };
  53519. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53520. this._checkUniform(name);
  53521. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53522. color.toArray(arr, arr.length);
  53523. return arr;
  53524. }, []);
  53525. return this;
  53526. };
  53527. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53528. this._checkUniform(name);
  53529. this._colors4[name] = value;
  53530. return this;
  53531. };
  53532. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53533. this._checkUniform(name);
  53534. this._vectors2[name] = value;
  53535. return this;
  53536. };
  53537. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53538. this._checkUniform(name);
  53539. this._vectors3[name] = value;
  53540. return this;
  53541. };
  53542. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53543. this._checkUniform(name);
  53544. this._vectors4[name] = value;
  53545. return this;
  53546. };
  53547. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53548. this._checkUniform(name);
  53549. this._matrices[name] = value;
  53550. return this;
  53551. };
  53552. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53553. this._checkUniform(name);
  53554. this._matrices3x3[name] = value;
  53555. return this;
  53556. };
  53557. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53558. this._checkUniform(name);
  53559. this._matrices2x2[name] = value;
  53560. return this;
  53561. };
  53562. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53563. this._checkUniform(name);
  53564. this._vectors2Arrays[name] = value;
  53565. return this;
  53566. };
  53567. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53568. this._checkUniform(name);
  53569. this._vectors3Arrays[name] = value;
  53570. return this;
  53571. };
  53572. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53573. if (!mesh) {
  53574. return true;
  53575. }
  53576. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53577. return false;
  53578. }
  53579. return false;
  53580. };
  53581. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53582. var scene = this.getScene();
  53583. var engine = scene.getEngine();
  53584. if (!this.checkReadyOnEveryCall) {
  53585. if (this._renderId === scene.getRenderId()) {
  53586. if (this._checkCache(scene, mesh, useInstances)) {
  53587. return true;
  53588. }
  53589. }
  53590. }
  53591. // Instances
  53592. var defines = [];
  53593. var attribs = [];
  53594. var fallbacks = new BABYLON.EffectFallbacks();
  53595. if (useInstances) {
  53596. defines.push("#define INSTANCES");
  53597. }
  53598. for (var index = 0; index < this._options.defines.length; index++) {
  53599. defines.push(this._options.defines[index]);
  53600. }
  53601. for (var index = 0; index < this._options.attributes.length; index++) {
  53602. attribs.push(this._options.attributes[index]);
  53603. }
  53604. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53605. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53606. defines.push("#define VERTEXCOLOR");
  53607. }
  53608. // Bones
  53609. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53610. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53611. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53612. if (mesh.numBoneInfluencers > 4) {
  53613. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53614. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53615. }
  53616. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53617. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53618. fallbacks.addCPUSkinningFallback(0, mesh);
  53619. if (this._options.uniforms.indexOf("mBones") === -1) {
  53620. this._options.uniforms.push("mBones");
  53621. }
  53622. }
  53623. else {
  53624. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53625. }
  53626. // Textures
  53627. for (var name in this._textures) {
  53628. if (!this._textures[name].isReady()) {
  53629. return false;
  53630. }
  53631. }
  53632. // Alpha test
  53633. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53634. defines.push("#define ALPHATEST");
  53635. }
  53636. var previousEffect = this._effect;
  53637. var join = defines.join("\n");
  53638. this._effect = engine.createEffect(this._shaderPath, {
  53639. attributes: attribs,
  53640. uniformsNames: this._options.uniforms,
  53641. uniformBuffersNames: this._options.uniformBuffers,
  53642. samplers: this._options.samplers,
  53643. defines: join,
  53644. fallbacks: fallbacks,
  53645. onCompiled: this.onCompiled,
  53646. onError: this.onError
  53647. }, engine);
  53648. if (!this._effect.isReady()) {
  53649. return false;
  53650. }
  53651. if (previousEffect !== this._effect) {
  53652. scene.resetCachedMaterial();
  53653. }
  53654. this._renderId = scene.getRenderId();
  53655. return true;
  53656. };
  53657. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53658. var scene = this.getScene();
  53659. if (!this._effect) {
  53660. return;
  53661. }
  53662. if (this._options.uniforms.indexOf("world") !== -1) {
  53663. this._effect.setMatrix("world", world);
  53664. }
  53665. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53666. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53667. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53668. }
  53669. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53670. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53671. }
  53672. };
  53673. ShaderMaterial.prototype.bind = function (world, mesh) {
  53674. // Std values
  53675. this.bindOnlyWorldMatrix(world);
  53676. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53677. if (this._options.uniforms.indexOf("view") !== -1) {
  53678. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53679. }
  53680. if (this._options.uniforms.indexOf("projection") !== -1) {
  53681. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53682. }
  53683. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53684. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53685. }
  53686. // Bones
  53687. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53688. var name;
  53689. // Texture
  53690. for (name in this._textures) {
  53691. this._effect.setTexture(name, this._textures[name]);
  53692. }
  53693. // Texture arrays
  53694. for (name in this._textureArrays) {
  53695. this._effect.setTextureArray(name, this._textureArrays[name]);
  53696. }
  53697. // Int
  53698. for (name in this._ints) {
  53699. this._effect.setInt(name, this._ints[name]);
  53700. }
  53701. // Float
  53702. for (name in this._floats) {
  53703. this._effect.setFloat(name, this._floats[name]);
  53704. }
  53705. // Floats
  53706. for (name in this._floatsArrays) {
  53707. this._effect.setArray(name, this._floatsArrays[name]);
  53708. }
  53709. // Color3
  53710. for (name in this._colors3) {
  53711. this._effect.setColor3(name, this._colors3[name]);
  53712. }
  53713. for (name in this._colors3Arrays) {
  53714. this._effect.setArray3(name, this._colors3Arrays[name]);
  53715. }
  53716. // Color4
  53717. for (name in this._colors4) {
  53718. var color = this._colors4[name];
  53719. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53720. }
  53721. // Vector2
  53722. for (name in this._vectors2) {
  53723. this._effect.setVector2(name, this._vectors2[name]);
  53724. }
  53725. // Vector3
  53726. for (name in this._vectors3) {
  53727. this._effect.setVector3(name, this._vectors3[name]);
  53728. }
  53729. // Vector4
  53730. for (name in this._vectors4) {
  53731. this._effect.setVector4(name, this._vectors4[name]);
  53732. }
  53733. // Matrix
  53734. for (name in this._matrices) {
  53735. this._effect.setMatrix(name, this._matrices[name]);
  53736. }
  53737. // Matrix 3x3
  53738. for (name in this._matrices3x3) {
  53739. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53740. }
  53741. // Matrix 2x2
  53742. for (name in this._matrices2x2) {
  53743. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53744. }
  53745. // Vector2Array
  53746. for (name in this._vectors2Arrays) {
  53747. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53748. }
  53749. // Vector3Array
  53750. for (name in this._vectors3Arrays) {
  53751. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53752. }
  53753. }
  53754. this._afterBind(mesh);
  53755. };
  53756. ShaderMaterial.prototype.getActiveTextures = function () {
  53757. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53758. for (var name in this._textures) {
  53759. activeTextures.push(this._textures[name]);
  53760. }
  53761. for (var name in this._textureArrays) {
  53762. var array = this._textureArrays[name];
  53763. for (var index = 0; index < array.length; index++) {
  53764. activeTextures.push(array[index]);
  53765. }
  53766. }
  53767. return activeTextures;
  53768. };
  53769. ShaderMaterial.prototype.hasTexture = function (texture) {
  53770. if (_super.prototype.hasTexture.call(this, texture)) {
  53771. return true;
  53772. }
  53773. for (var name in this._textures) {
  53774. if (this._textures[name] === texture) {
  53775. return true;
  53776. }
  53777. }
  53778. for (var name in this._textureArrays) {
  53779. var array = this._textureArrays[name];
  53780. for (var index = 0; index < array.length; index++) {
  53781. if (array[index] === texture) {
  53782. return true;
  53783. }
  53784. }
  53785. }
  53786. return false;
  53787. };
  53788. ShaderMaterial.prototype.clone = function (name) {
  53789. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53790. return newShaderMaterial;
  53791. };
  53792. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53793. if (forceDisposeTextures) {
  53794. var name;
  53795. for (name in this._textures) {
  53796. this._textures[name].dispose();
  53797. }
  53798. for (name in this._textureArrays) {
  53799. var array = this._textureArrays[name];
  53800. for (var index = 0; index < array.length; index++) {
  53801. array[index].dispose();
  53802. }
  53803. }
  53804. }
  53805. this._textures = {};
  53806. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53807. };
  53808. ShaderMaterial.prototype.serialize = function () {
  53809. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53810. serializationObject.customType = "BABYLON.ShaderMaterial";
  53811. serializationObject.options = this._options;
  53812. serializationObject.shaderPath = this._shaderPath;
  53813. var name;
  53814. // Texture
  53815. serializationObject.textures = {};
  53816. for (name in this._textures) {
  53817. serializationObject.textures[name] = this._textures[name].serialize();
  53818. }
  53819. // Texture arrays
  53820. serializationObject.textureArrays = {};
  53821. for (name in this._textureArrays) {
  53822. serializationObject.textureArrays[name] = [];
  53823. var array = this._textureArrays[name];
  53824. for (var index = 0; index < array.length; index++) {
  53825. serializationObject.textureArrays[name].push(array[index].serialize());
  53826. }
  53827. }
  53828. // Float
  53829. serializationObject.floats = {};
  53830. for (name in this._floats) {
  53831. serializationObject.floats[name] = this._floats[name];
  53832. }
  53833. // Float s
  53834. serializationObject.FloatArrays = {};
  53835. for (name in this._floatsArrays) {
  53836. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53837. }
  53838. // Color3
  53839. serializationObject.colors3 = {};
  53840. for (name in this._colors3) {
  53841. serializationObject.colors3[name] = this._colors3[name].asArray();
  53842. }
  53843. // Color3 array
  53844. serializationObject.colors3Arrays = {};
  53845. for (name in this._colors3Arrays) {
  53846. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53847. }
  53848. // Color4
  53849. serializationObject.colors4 = {};
  53850. for (name in this._colors4) {
  53851. serializationObject.colors4[name] = this._colors4[name].asArray();
  53852. }
  53853. // Vector2
  53854. serializationObject.vectors2 = {};
  53855. for (name in this._vectors2) {
  53856. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53857. }
  53858. // Vector3
  53859. serializationObject.vectors3 = {};
  53860. for (name in this._vectors3) {
  53861. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53862. }
  53863. // Vector4
  53864. serializationObject.vectors4 = {};
  53865. for (name in this._vectors4) {
  53866. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53867. }
  53868. // Matrix
  53869. serializationObject.matrices = {};
  53870. for (name in this._matrices) {
  53871. serializationObject.matrices[name] = this._matrices[name].asArray();
  53872. }
  53873. // Matrix 3x3
  53874. serializationObject.matrices3x3 = {};
  53875. for (name in this._matrices3x3) {
  53876. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53877. }
  53878. // Matrix 2x2
  53879. serializationObject.matrices2x2 = {};
  53880. for (name in this._matrices2x2) {
  53881. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53882. }
  53883. // Vector2Array
  53884. serializationObject.vectors2Arrays = {};
  53885. for (name in this._vectors2Arrays) {
  53886. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53887. }
  53888. // Vector3Array
  53889. serializationObject.vectors3Arrays = {};
  53890. for (name in this._vectors3Arrays) {
  53891. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53892. }
  53893. return serializationObject;
  53894. };
  53895. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53896. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53897. var name;
  53898. // Texture
  53899. for (name in source.textures) {
  53900. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53901. }
  53902. // Texture arrays
  53903. for (name in source.textureArrays) {
  53904. var array = source.textureArrays[name];
  53905. var textureArray = new Array();
  53906. for (var index = 0; index < array.length; index++) {
  53907. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53908. }
  53909. material.setTextureArray(name, textureArray);
  53910. }
  53911. // Float
  53912. for (name in source.floats) {
  53913. material.setFloat(name, source.floats[name]);
  53914. }
  53915. // Float s
  53916. for (name in source.floatsArrays) {
  53917. material.setFloats(name, source.floatsArrays[name]);
  53918. }
  53919. // Color3
  53920. for (name in source.colors3) {
  53921. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53922. }
  53923. // Color3 arrays
  53924. for (name in source.colors3Arrays) {
  53925. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53926. if (i % 3 === 0) {
  53927. arr.push([num]);
  53928. }
  53929. else {
  53930. arr[arr.length - 1].push(num);
  53931. }
  53932. return arr;
  53933. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53934. material.setColor3Array(name, colors);
  53935. }
  53936. // Color4
  53937. for (name in source.colors4) {
  53938. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53939. }
  53940. // Vector2
  53941. for (name in source.vectors2) {
  53942. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53943. }
  53944. // Vector3
  53945. for (name in source.vectors3) {
  53946. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53947. }
  53948. // Vector4
  53949. for (name in source.vectors4) {
  53950. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53951. }
  53952. // Matrix
  53953. for (name in source.matrices) {
  53954. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53955. }
  53956. // Matrix 3x3
  53957. for (name in source.matrices3x3) {
  53958. material.setMatrix3x3(name, source.matrices3x3[name]);
  53959. }
  53960. // Matrix 2x2
  53961. for (name in source.matrices2x2) {
  53962. material.setMatrix2x2(name, source.matrices2x2[name]);
  53963. }
  53964. // Vector2Array
  53965. for (name in source.vectors2Arrays) {
  53966. material.setArray2(name, source.vectors2Arrays[name]);
  53967. }
  53968. // Vector3Array
  53969. for (name in source.vectors3Arrays) {
  53970. material.setArray3(name, source.vectors3Arrays[name]);
  53971. }
  53972. return material;
  53973. };
  53974. return ShaderMaterial;
  53975. }(BABYLON.Material));
  53976. BABYLON.ShaderMaterial = ShaderMaterial;
  53977. })(BABYLON || (BABYLON = {}));
  53978. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53979. var BABYLON;
  53980. (function (BABYLON) {
  53981. var GroundMesh = /** @class */ (function (_super) {
  53982. __extends(GroundMesh, _super);
  53983. function GroundMesh(name, scene) {
  53984. var _this = _super.call(this, name, scene) || this;
  53985. _this.generateOctree = false;
  53986. return _this;
  53987. }
  53988. GroundMesh.prototype.getClassName = function () {
  53989. return "GroundMesh";
  53990. };
  53991. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53992. get: function () {
  53993. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53994. },
  53995. enumerable: true,
  53996. configurable: true
  53997. });
  53998. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53999. get: function () {
  54000. return this._subdivisionsX;
  54001. },
  54002. enumerable: true,
  54003. configurable: true
  54004. });
  54005. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54006. get: function () {
  54007. return this._subdivisionsY;
  54008. },
  54009. enumerable: true,
  54010. configurable: true
  54011. });
  54012. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54013. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54014. this._subdivisionsX = chunksCount;
  54015. this._subdivisionsY = chunksCount;
  54016. this.subdivide(chunksCount);
  54017. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54018. };
  54019. /**
  54020. * Returns a height (y) value in the Worl system :
  54021. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54022. * Returns the ground y position if (x, z) are outside the ground surface.
  54023. */
  54024. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54025. var world = this.getWorldMatrix();
  54026. var invMat = BABYLON.Tmp.Matrix[5];
  54027. world.invertToRef(invMat);
  54028. var tmpVect = BABYLON.Tmp.Vector3[8];
  54029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54030. x = tmpVect.x;
  54031. z = tmpVect.z;
  54032. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54033. return this.position.y;
  54034. }
  54035. if (!this._heightQuads || this._heightQuads.length == 0) {
  54036. this._initHeightQuads();
  54037. this._computeHeightQuads();
  54038. }
  54039. var facet = this._getFacetAt(x, z);
  54040. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54041. // return y in the World system
  54042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54043. return tmpVect.y;
  54044. };
  54045. /**
  54046. * Returns a normalized vector (Vector3) orthogonal to the ground
  54047. * at the ground coordinates (x, z) expressed in the World system.
  54048. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54049. */
  54050. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54051. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54052. this.getNormalAtCoordinatesToRef(x, z, normal);
  54053. return normal;
  54054. };
  54055. /**
  54056. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54057. * at the ground coordinates (x, z) expressed in the World system.
  54058. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54059. * Returns the GroundMesh.
  54060. */
  54061. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54062. var world = this.getWorldMatrix();
  54063. var tmpMat = BABYLON.Tmp.Matrix[5];
  54064. world.invertToRef(tmpMat);
  54065. var tmpVect = BABYLON.Tmp.Vector3[8];
  54066. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54067. x = tmpVect.x;
  54068. z = tmpVect.z;
  54069. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54070. return this;
  54071. }
  54072. if (!this._heightQuads || this._heightQuads.length == 0) {
  54073. this._initHeightQuads();
  54074. this._computeHeightQuads();
  54075. }
  54076. var facet = this._getFacetAt(x, z);
  54077. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54078. return this;
  54079. };
  54080. /**
  54081. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54082. * if the ground has been updated.
  54083. * This can be used in the render loop.
  54084. * Returns the GroundMesh.
  54085. */
  54086. GroundMesh.prototype.updateCoordinateHeights = function () {
  54087. if (!this._heightQuads || this._heightQuads.length == 0) {
  54088. this._initHeightQuads();
  54089. }
  54090. this._computeHeightQuads();
  54091. return this;
  54092. };
  54093. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54094. GroundMesh.prototype._getFacetAt = function (x, z) {
  54095. // retrieve col and row from x, z coordinates in the ground local system
  54096. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54097. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54098. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54099. var facet;
  54100. if (z < quad.slope.x * x + quad.slope.y) {
  54101. facet = quad.facet1;
  54102. }
  54103. else {
  54104. facet = quad.facet2;
  54105. }
  54106. return facet;
  54107. };
  54108. // Creates and populates the heightMap array with "facet" elements :
  54109. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54110. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54111. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54112. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54113. // Returns the GroundMesh.
  54114. GroundMesh.prototype._initHeightQuads = function () {
  54115. var subdivisionsX = this._subdivisionsX;
  54116. var subdivisionsY = this._subdivisionsY;
  54117. this._heightQuads = new Array();
  54118. for (var row = 0; row < subdivisionsY; row++) {
  54119. for (var col = 0; col < subdivisionsX; col++) {
  54120. 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) };
  54121. this._heightQuads[row * subdivisionsX + col] = quad;
  54122. }
  54123. }
  54124. return this;
  54125. };
  54126. // Compute each quad element values and update the the heightMap array :
  54127. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54128. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54129. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54130. // Returns the GroundMesh.
  54131. GroundMesh.prototype._computeHeightQuads = function () {
  54132. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54133. if (!positions) {
  54134. return this;
  54135. }
  54136. var v1 = BABYLON.Tmp.Vector3[3];
  54137. var v2 = BABYLON.Tmp.Vector3[2];
  54138. var v3 = BABYLON.Tmp.Vector3[1];
  54139. var v4 = BABYLON.Tmp.Vector3[0];
  54140. var v1v2 = BABYLON.Tmp.Vector3[4];
  54141. var v1v3 = BABYLON.Tmp.Vector3[5];
  54142. var v1v4 = BABYLON.Tmp.Vector3[6];
  54143. var norm1 = BABYLON.Tmp.Vector3[7];
  54144. var norm2 = BABYLON.Tmp.Vector3[8];
  54145. var i = 0;
  54146. var j = 0;
  54147. var k = 0;
  54148. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54149. var h = 0;
  54150. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54151. var d2 = 0;
  54152. var subdivisionsX = this._subdivisionsX;
  54153. var subdivisionsY = this._subdivisionsY;
  54154. for (var row = 0; row < subdivisionsY; row++) {
  54155. for (var col = 0; col < subdivisionsX; col++) {
  54156. i = col * 3;
  54157. j = row * (subdivisionsX + 1) * 3;
  54158. k = (row + 1) * (subdivisionsX + 1) * 3;
  54159. v1.x = positions[j + i];
  54160. v1.y = positions[j + i + 1];
  54161. v1.z = positions[j + i + 2];
  54162. v2.x = positions[j + i + 3];
  54163. v2.y = positions[j + i + 4];
  54164. v2.z = positions[j + i + 5];
  54165. v3.x = positions[k + i];
  54166. v3.y = positions[k + i + 1];
  54167. v3.z = positions[k + i + 2];
  54168. v4.x = positions[k + i + 3];
  54169. v4.y = positions[k + i + 4];
  54170. v4.z = positions[k + i + 5];
  54171. // 2D slope V1V4
  54172. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54173. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54174. // facet equations :
  54175. // we compute each facet normal vector
  54176. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54177. // we compute the value d by applying the equation to v1 which belongs to the plane
  54178. // then we store the facet equation in a Vector4
  54179. v2.subtractToRef(v1, v1v2);
  54180. v3.subtractToRef(v1, v1v3);
  54181. v4.subtractToRef(v1, v1v4);
  54182. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54183. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54184. norm1.normalize();
  54185. norm2.normalize();
  54186. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54187. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54188. var quad = this._heightQuads[row * subdivisionsX + col];
  54189. quad.slope.copyFromFloats(cd, h);
  54190. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54191. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54192. }
  54193. }
  54194. return this;
  54195. };
  54196. GroundMesh.prototype.serialize = function (serializationObject) {
  54197. _super.prototype.serialize.call(this, serializationObject);
  54198. serializationObject.subdivisionsX = this._subdivisionsX;
  54199. serializationObject.subdivisionsY = this._subdivisionsY;
  54200. serializationObject.minX = this._minX;
  54201. serializationObject.maxX = this._maxX;
  54202. serializationObject.minZ = this._minZ;
  54203. serializationObject.maxZ = this._maxZ;
  54204. serializationObject.width = this._width;
  54205. serializationObject.height = this._height;
  54206. };
  54207. GroundMesh.Parse = function (parsedMesh, scene) {
  54208. var result = new GroundMesh(parsedMesh.name, scene);
  54209. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54210. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54211. result._minX = parsedMesh.minX;
  54212. result._maxX = parsedMesh.maxX;
  54213. result._minZ = parsedMesh.minZ;
  54214. result._maxZ = parsedMesh.maxZ;
  54215. result._width = parsedMesh.width;
  54216. result._height = parsedMesh.height;
  54217. return result;
  54218. };
  54219. return GroundMesh;
  54220. }(BABYLON.Mesh));
  54221. BABYLON.GroundMesh = GroundMesh;
  54222. })(BABYLON || (BABYLON = {}));
  54223. //# sourceMappingURL=babylon.groundMesh.js.map
  54224. var BABYLON;
  54225. (function (BABYLON) {
  54226. /**
  54227. * Creates an instance based on a source mesh.
  54228. */
  54229. var InstancedMesh = /** @class */ (function (_super) {
  54230. __extends(InstancedMesh, _super);
  54231. function InstancedMesh(name, source) {
  54232. var _this = _super.call(this, name, source.getScene()) || this;
  54233. source.instances.push(_this);
  54234. _this._sourceMesh = source;
  54235. _this.position.copyFrom(source.position);
  54236. _this.rotation.copyFrom(source.rotation);
  54237. _this.scaling.copyFrom(source.scaling);
  54238. if (source.rotationQuaternion) {
  54239. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54240. }
  54241. _this.infiniteDistance = source.infiniteDistance;
  54242. _this.setPivotMatrix(source.getPivotMatrix());
  54243. _this.refreshBoundingInfo();
  54244. _this._syncSubMeshes();
  54245. return _this;
  54246. }
  54247. /**
  54248. * Returns the string "InstancedMesh".
  54249. */
  54250. InstancedMesh.prototype.getClassName = function () {
  54251. return "InstancedMesh";
  54252. };
  54253. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54254. // Methods
  54255. get: function () {
  54256. return this._sourceMesh.receiveShadows;
  54257. },
  54258. enumerable: true,
  54259. configurable: true
  54260. });
  54261. Object.defineProperty(InstancedMesh.prototype, "material", {
  54262. get: function () {
  54263. return this._sourceMesh.material;
  54264. },
  54265. enumerable: true,
  54266. configurable: true
  54267. });
  54268. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54269. get: function () {
  54270. return this._sourceMesh.visibility;
  54271. },
  54272. enumerable: true,
  54273. configurable: true
  54274. });
  54275. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54276. get: function () {
  54277. return this._sourceMesh.skeleton;
  54278. },
  54279. enumerable: true,
  54280. configurable: true
  54281. });
  54282. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54283. get: function () {
  54284. return this._sourceMesh.renderingGroupId;
  54285. },
  54286. enumerable: true,
  54287. configurable: true
  54288. });
  54289. /**
  54290. * Returns the total number of vertices (integer).
  54291. */
  54292. InstancedMesh.prototype.getTotalVertices = function () {
  54293. return this._sourceMesh.getTotalVertices();
  54294. };
  54295. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54296. get: function () {
  54297. return this._sourceMesh;
  54298. },
  54299. enumerable: true,
  54300. configurable: true
  54301. });
  54302. /**
  54303. * Is this node ready to be used/rendered
  54304. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54305. * @return {boolean} is it ready
  54306. */
  54307. InstancedMesh.prototype.isReady = function (completeCheck) {
  54308. if (completeCheck === void 0) { completeCheck = false; }
  54309. return this._sourceMesh.isReady(completeCheck, true);
  54310. };
  54311. /**
  54312. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54313. */
  54314. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54315. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54316. };
  54317. /**
  54318. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54319. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54320. * The `data` are either a numeric array either a Float32Array.
  54321. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54322. * 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).
  54323. * Note that a new underlying VertexBuffer object is created each call.
  54324. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54325. *
  54326. * Possible `kind` values :
  54327. * - BABYLON.VertexBuffer.PositionKind
  54328. * - BABYLON.VertexBuffer.UVKind
  54329. * - BABYLON.VertexBuffer.UV2Kind
  54330. * - BABYLON.VertexBuffer.UV3Kind
  54331. * - BABYLON.VertexBuffer.UV4Kind
  54332. * - BABYLON.VertexBuffer.UV5Kind
  54333. * - BABYLON.VertexBuffer.UV6Kind
  54334. * - BABYLON.VertexBuffer.ColorKind
  54335. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54336. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54337. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54338. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54339. *
  54340. * Returns the Mesh.
  54341. */
  54342. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54343. if (this.sourceMesh) {
  54344. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54345. }
  54346. return this.sourceMesh;
  54347. };
  54348. /**
  54349. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54350. * If the mesh has no geometry, it is simply returned as it is.
  54351. * The `data` are either a numeric array either a Float32Array.
  54352. * No new underlying VertexBuffer object is created.
  54353. * 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.
  54354. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54355. *
  54356. * Possible `kind` values :
  54357. * - BABYLON.VertexBuffer.PositionKind
  54358. * - BABYLON.VertexBuffer.UVKind
  54359. * - BABYLON.VertexBuffer.UV2Kind
  54360. * - BABYLON.VertexBuffer.UV3Kind
  54361. * - BABYLON.VertexBuffer.UV4Kind
  54362. * - BABYLON.VertexBuffer.UV5Kind
  54363. * - BABYLON.VertexBuffer.UV6Kind
  54364. * - BABYLON.VertexBuffer.ColorKind
  54365. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54366. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54367. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54368. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54369. *
  54370. * Returns the Mesh.
  54371. */
  54372. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54373. if (this.sourceMesh) {
  54374. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54375. }
  54376. return this.sourceMesh;
  54377. };
  54378. /**
  54379. * Sets the mesh indices.
  54380. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54381. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54382. * This method creates a new index buffer each call.
  54383. * Returns the Mesh.
  54384. */
  54385. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54386. if (totalVertices === void 0) { totalVertices = null; }
  54387. if (this.sourceMesh) {
  54388. this.sourceMesh.setIndices(indices, totalVertices);
  54389. }
  54390. return this.sourceMesh;
  54391. };
  54392. /**
  54393. * Boolean : True if the mesh owns the requested kind of data.
  54394. */
  54395. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54396. return this._sourceMesh.isVerticesDataPresent(kind);
  54397. };
  54398. /**
  54399. * Returns an array of indices (IndicesArray).
  54400. */
  54401. InstancedMesh.prototype.getIndices = function () {
  54402. return this._sourceMesh.getIndices();
  54403. };
  54404. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54405. get: function () {
  54406. return this._sourceMesh._positions;
  54407. },
  54408. enumerable: true,
  54409. configurable: true
  54410. });
  54411. /**
  54412. * Sets a new updated BoundingInfo to the mesh.
  54413. * Returns the mesh.
  54414. */
  54415. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54416. var meshBB = this._sourceMesh.getBoundingInfo();
  54417. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54418. this._updateBoundingInfo();
  54419. return this;
  54420. };
  54421. InstancedMesh.prototype._preActivate = function () {
  54422. if (this._currentLOD) {
  54423. this._currentLOD._preActivate();
  54424. }
  54425. return this;
  54426. };
  54427. InstancedMesh.prototype._activate = function (renderId) {
  54428. if (this._currentLOD) {
  54429. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54430. }
  54431. return this;
  54432. };
  54433. /**
  54434. * Returns the current associated LOD AbstractMesh.
  54435. */
  54436. InstancedMesh.prototype.getLOD = function (camera) {
  54437. if (!camera) {
  54438. return this;
  54439. }
  54440. var boundingInfo = this.getBoundingInfo();
  54441. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54442. if (this._currentLOD === this.sourceMesh) {
  54443. return this;
  54444. }
  54445. return this._currentLOD;
  54446. };
  54447. InstancedMesh.prototype._syncSubMeshes = function () {
  54448. this.releaseSubMeshes();
  54449. if (this._sourceMesh.subMeshes) {
  54450. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54451. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54452. }
  54453. }
  54454. return this;
  54455. };
  54456. InstancedMesh.prototype._generatePointsArray = function () {
  54457. return this._sourceMesh._generatePointsArray();
  54458. };
  54459. /**
  54460. * Creates a new InstancedMesh from the current mesh.
  54461. * - name (string) : the cloned mesh name
  54462. * - newParent (optional Node) : the optional Node to parent the clone to.
  54463. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54464. *
  54465. * Returns the clone.
  54466. */
  54467. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54468. var result = this._sourceMesh.createInstance(name);
  54469. // Deep copy
  54470. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54471. // Bounding info
  54472. this.refreshBoundingInfo();
  54473. // Parent
  54474. if (newParent) {
  54475. result.parent = newParent;
  54476. }
  54477. if (!doNotCloneChildren) {
  54478. // Children
  54479. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54480. var mesh = this.getScene().meshes[index];
  54481. if (mesh.parent === this) {
  54482. mesh.clone(mesh.name, result);
  54483. }
  54484. }
  54485. }
  54486. result.computeWorldMatrix(true);
  54487. return result;
  54488. };
  54489. /**
  54490. * Disposes the InstancedMesh.
  54491. * Returns nothing.
  54492. */
  54493. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54494. // Remove from mesh
  54495. var index = this._sourceMesh.instances.indexOf(this);
  54496. this._sourceMesh.instances.splice(index, 1);
  54497. _super.prototype.dispose.call(this, doNotRecurse);
  54498. };
  54499. return InstancedMesh;
  54500. }(BABYLON.AbstractMesh));
  54501. BABYLON.InstancedMesh = InstancedMesh;
  54502. })(BABYLON || (BABYLON = {}));
  54503. //# sourceMappingURL=babylon.instancedMesh.js.map
  54504. var BABYLON;
  54505. (function (BABYLON) {
  54506. var LinesMesh = /** @class */ (function (_super) {
  54507. __extends(LinesMesh, _super);
  54508. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54509. if (scene === void 0) { scene = null; }
  54510. if (parent === void 0) { parent = null; }
  54511. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54512. _this.useVertexColor = useVertexColor;
  54513. _this.useVertexAlpha = useVertexAlpha;
  54514. _this.color = new BABYLON.Color3(1, 1, 1);
  54515. _this.alpha = 1;
  54516. if (source) {
  54517. _this.color = source.color.clone();
  54518. _this.alpha = source.alpha;
  54519. _this.useVertexColor = source.useVertexColor;
  54520. _this.useVertexAlpha = source.useVertexAlpha;
  54521. }
  54522. _this._intersectionThreshold = 0.1;
  54523. var defines = [];
  54524. var options = {
  54525. attributes: [BABYLON.VertexBuffer.PositionKind],
  54526. uniforms: ["world", "viewProjection"],
  54527. needAlphaBlending: true,
  54528. defines: defines
  54529. };
  54530. if (useVertexAlpha === false) {
  54531. options.needAlphaBlending = false;
  54532. }
  54533. if (!useVertexColor) {
  54534. options.uniforms.push("color");
  54535. }
  54536. else {
  54537. options.defines.push("#define VERTEXCOLOR");
  54538. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54539. }
  54540. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54541. return _this;
  54542. }
  54543. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54544. /**
  54545. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54546. * This margin is expressed in world space coordinates, so its value may vary.
  54547. * Default value is 0.1
  54548. * @returns the intersection Threshold value.
  54549. */
  54550. get: function () {
  54551. return this._intersectionThreshold;
  54552. },
  54553. /**
  54554. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54555. * This margin is expressed in world space coordinates, so its value may vary.
  54556. * @param value the new threshold to apply
  54557. */
  54558. set: function (value) {
  54559. if (this._intersectionThreshold === value) {
  54560. return;
  54561. }
  54562. this._intersectionThreshold = value;
  54563. if (this.geometry) {
  54564. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54565. }
  54566. },
  54567. enumerable: true,
  54568. configurable: true
  54569. });
  54570. /**
  54571. * Returns the string "LineMesh"
  54572. */
  54573. LinesMesh.prototype.getClassName = function () {
  54574. return "LinesMesh";
  54575. };
  54576. Object.defineProperty(LinesMesh.prototype, "material", {
  54577. get: function () {
  54578. return this._colorShader;
  54579. },
  54580. set: function (value) {
  54581. // Do nothing
  54582. },
  54583. enumerable: true,
  54584. configurable: true
  54585. });
  54586. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54587. get: function () {
  54588. return false;
  54589. },
  54590. enumerable: true,
  54591. configurable: true
  54592. });
  54593. LinesMesh.prototype.createInstance = function (name) {
  54594. throw new Error("LinesMeshes do not support createInstance.");
  54595. };
  54596. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54597. if (!this._geometry) {
  54598. return this;
  54599. }
  54600. // VBOs
  54601. this._geometry._bind(this._colorShader.getEffect());
  54602. // Color
  54603. if (!this.useVertexColor) {
  54604. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54605. }
  54606. return this;
  54607. };
  54608. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54609. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54610. return this;
  54611. }
  54612. var engine = this.getScene().getEngine();
  54613. // Draw order
  54614. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54615. return this;
  54616. };
  54617. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54618. this._colorShader.dispose();
  54619. _super.prototype.dispose.call(this, doNotRecurse);
  54620. };
  54621. /**
  54622. * Returns a new LineMesh object cloned from the current one.
  54623. */
  54624. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54625. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54626. };
  54627. return LinesMesh;
  54628. }(BABYLON.Mesh));
  54629. BABYLON.LinesMesh = LinesMesh;
  54630. })(BABYLON || (BABYLON = {}));
  54631. //# sourceMappingURL=babylon.linesMesh.js.map
  54632. var BABYLON;
  54633. (function (BABYLON) {
  54634. var MeshBuilder = /** @class */ (function () {
  54635. function MeshBuilder() {
  54636. }
  54637. MeshBuilder.updateSideOrientation = function (orientation) {
  54638. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54639. return BABYLON.Mesh.DOUBLESIDE;
  54640. }
  54641. if (orientation === undefined || orientation === null) {
  54642. return BABYLON.Mesh.FRONTSIDE;
  54643. }
  54644. return orientation;
  54645. };
  54646. /**
  54647. * Creates a box mesh.
  54648. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54649. * The parameter `size` sets the size (float) of each box side (default 1).
  54650. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54651. * 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).
  54652. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54653. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54654. * 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).
  54655. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54657. */
  54658. MeshBuilder.CreateBox = function (name, options, scene) {
  54659. if (scene === void 0) { scene = null; }
  54660. var box = new BABYLON.Mesh(name, scene);
  54661. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54662. box._originalBuilderSideOrientation = options.sideOrientation;
  54663. var vertexData = BABYLON.VertexData.CreateBox(options);
  54664. vertexData.applyToMesh(box, options.updatable);
  54665. return box;
  54666. };
  54667. /**
  54668. * Creates a sphere mesh.
  54669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54670. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54671. * 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`).
  54672. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54673. * 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
  54674. * 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).
  54675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54676. * 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).
  54677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54679. */
  54680. MeshBuilder.CreateSphere = function (name, options, scene) {
  54681. var sphere = new BABYLON.Mesh(name, scene);
  54682. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54683. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54684. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54685. vertexData.applyToMesh(sphere, options.updatable);
  54686. return sphere;
  54687. };
  54688. /**
  54689. * Creates a plane polygonal mesh. By default, this is a disc.
  54690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54691. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54692. * 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.
  54693. * 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
  54694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54695. * 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).
  54696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54698. */
  54699. MeshBuilder.CreateDisc = function (name, options, scene) {
  54700. if (scene === void 0) { scene = null; }
  54701. var disc = new BABYLON.Mesh(name, scene);
  54702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54703. disc._originalBuilderSideOrientation = options.sideOrientation;
  54704. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54705. vertexData.applyToMesh(disc, options.updatable);
  54706. return disc;
  54707. };
  54708. /**
  54709. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54710. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54711. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54712. * 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`).
  54713. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54714. * 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.
  54715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54716. * 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).
  54717. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54719. */
  54720. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54721. var sphere = new BABYLON.Mesh(name, scene);
  54722. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54723. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54724. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54725. vertexData.applyToMesh(sphere, options.updatable);
  54726. return sphere;
  54727. };
  54728. ;
  54729. /**
  54730. * Creates a ribbon mesh.
  54731. * 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.
  54732. *
  54733. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54734. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54735. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54736. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54737. * 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.
  54738. * 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.
  54739. * 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
  54740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54741. * 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).
  54742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54743. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54744. * 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.
  54745. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54746. * 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
  54747. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54748. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54750. */
  54751. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54752. if (scene === void 0) { scene = null; }
  54753. var pathArray = options.pathArray;
  54754. var closeArray = options.closeArray;
  54755. var closePath = options.closePath;
  54756. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54757. var instance = options.instance;
  54758. var updatable = options.updatable;
  54759. if (instance) {
  54760. // positionFunction : ribbon case
  54761. // only pathArray and sideOrientation parameters are taken into account for positions update
  54762. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54763. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54764. var positionFunction = function (positions) {
  54765. var minlg = pathArray[0].length;
  54766. var i = 0;
  54767. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54768. for (var si = 1; si <= ns; si++) {
  54769. for (var p = 0; p < pathArray.length; p++) {
  54770. var path = pathArray[p];
  54771. var l = path.length;
  54772. minlg = (minlg < l) ? minlg : l;
  54773. var j = 0;
  54774. while (j < minlg) {
  54775. positions[i] = path[j].x;
  54776. positions[i + 1] = path[j].y;
  54777. positions[i + 2] = path[j].z;
  54778. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54779. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54780. }
  54781. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54782. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54783. }
  54784. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54785. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54786. }
  54787. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54788. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54789. }
  54790. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54791. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54792. }
  54793. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54794. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54795. }
  54796. j++;
  54797. i += 3;
  54798. }
  54799. if (instance._closePath) {
  54800. positions[i] = path[0].x;
  54801. positions[i + 1] = path[0].y;
  54802. positions[i + 2] = path[0].z;
  54803. i += 3;
  54804. }
  54805. }
  54806. }
  54807. };
  54808. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54809. positionFunction(positions);
  54810. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54811. instance._boundingInfo.update(instance._worldMatrix);
  54812. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54813. if (options.colors) {
  54814. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54815. for (var c = 0; c < options.colors.length; c++) {
  54816. colors[c * 4] = options.colors[c].r;
  54817. colors[c * 4 + 1] = options.colors[c].g;
  54818. colors[c * 4 + 2] = options.colors[c].b;
  54819. colors[c * 4 + 3] = options.colors[c].a;
  54820. }
  54821. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54822. }
  54823. if (options.uvs) {
  54824. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54825. for (var i = 0; i < options.uvs.length; i++) {
  54826. uvs[i * 2] = options.uvs[i].x;
  54827. uvs[i * 2 + 1] = options.uvs[i].y;
  54828. }
  54829. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54830. }
  54831. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54832. var indices = instance.getIndices();
  54833. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54834. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54835. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54836. if (instance._closePath) {
  54837. var indexFirst = 0;
  54838. var indexLast = 0;
  54839. for (var p = 0; p < pathArray.length; p++) {
  54840. indexFirst = instance._idx[p] * 3;
  54841. if (p + 1 < pathArray.length) {
  54842. indexLast = (instance._idx[p + 1] - 1) * 3;
  54843. }
  54844. else {
  54845. indexLast = normals.length - 3;
  54846. }
  54847. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54848. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54849. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54850. normals[indexLast] = normals[indexFirst];
  54851. normals[indexLast + 1] = normals[indexFirst + 1];
  54852. normals[indexLast + 2] = normals[indexFirst + 2];
  54853. }
  54854. }
  54855. if (!(instance.areNormalsFrozen)) {
  54856. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54857. }
  54858. }
  54859. return instance;
  54860. }
  54861. else {
  54862. var ribbon = new BABYLON.Mesh(name, scene);
  54863. ribbon._originalBuilderSideOrientation = sideOrientation;
  54864. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54865. if (closePath) {
  54866. ribbon._idx = vertexData._idx;
  54867. }
  54868. ribbon._closePath = closePath;
  54869. ribbon._closeArray = closeArray;
  54870. vertexData.applyToMesh(ribbon, updatable);
  54871. return ribbon;
  54872. }
  54873. };
  54874. /**
  54875. * Creates a cylinder or a cone mesh.
  54876. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54877. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54878. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54879. * 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.
  54880. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54881. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54882. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54883. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54884. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54885. * 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).
  54886. * 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
  54887. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54888. * 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
  54889. * 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.
  54890. * If `enclose` is false, a ring surface is one element.
  54891. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54892. * 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
  54893. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54894. * 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).
  54895. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54896. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54897. */
  54898. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54899. var cylinder = new BABYLON.Mesh(name, scene);
  54900. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54901. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54902. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54903. vertexData.applyToMesh(cylinder, options.updatable);
  54904. return cylinder;
  54905. };
  54906. /**
  54907. * Creates a torus mesh.
  54908. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54909. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54910. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54911. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54913. * 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).
  54914. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54916. */
  54917. MeshBuilder.CreateTorus = function (name, options, scene) {
  54918. var torus = new BABYLON.Mesh(name, scene);
  54919. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54920. torus._originalBuilderSideOrientation = options.sideOrientation;
  54921. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54922. vertexData.applyToMesh(torus, options.updatable);
  54923. return torus;
  54924. };
  54925. /**
  54926. * Creates a torus knot mesh.
  54927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54928. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54929. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54930. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54931. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54932. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54933. * 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).
  54934. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54935. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54936. */
  54937. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54938. var torusKnot = new BABYLON.Mesh(name, scene);
  54939. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54940. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54941. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54942. vertexData.applyToMesh(torusKnot, options.updatable);
  54943. return torusKnot;
  54944. };
  54945. /**
  54946. * Creates a line system mesh.
  54947. * A line system is a pool of many lines gathered in a single mesh.
  54948. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54949. * 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.
  54950. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54951. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54952. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  54953. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54954. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54955. * 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
  54956. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54958. */
  54959. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54960. var instance = options.instance;
  54961. var lines = options.lines;
  54962. var colors = options.colors;
  54963. if (instance) {
  54964. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54965. var vertexColor;
  54966. var lineColors;
  54967. if (colors) {
  54968. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54969. }
  54970. var i = 0;
  54971. var c = 0;
  54972. for (var l = 0; l < lines.length; l++) {
  54973. var points = lines[l];
  54974. for (var p = 0; p < points.length; p++) {
  54975. positions[i] = points[p].x;
  54976. positions[i + 1] = points[p].y;
  54977. positions[i + 2] = points[p].z;
  54978. if (colors && vertexColor) {
  54979. lineColors = colors[l];
  54980. vertexColor[c] = lineColors[p].r;
  54981. vertexColor[c + 1] = lineColors[p].g;
  54982. vertexColor[c + 2] = lineColors[p].b;
  54983. vertexColor[c + 3] = lineColors[p].a;
  54984. c += 4;
  54985. }
  54986. i += 3;
  54987. }
  54988. }
  54989. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54990. if (colors && vertexColor) {
  54991. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54992. }
  54993. return instance;
  54994. }
  54995. // line system creation
  54996. var useVertexColor = (colors) ? true : false;
  54997. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54998. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54999. vertexData.applyToMesh(lineSystem, options.updatable);
  55000. return lineSystem;
  55001. };
  55002. /**
  55003. * Creates a line mesh.
  55004. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55005. * 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.
  55006. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55007. * The parameter `points` is an array successive Vector3.
  55008. * 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
  55009. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55010. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55011. * When updating an instance, remember that only point positions can change, not the number of points.
  55012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55013. */
  55014. MeshBuilder.CreateLines = function (name, options, scene) {
  55015. if (scene === void 0) { scene = null; }
  55016. var colors = (options.colors) ? [options.colors] : null;
  55017. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55018. return lines;
  55019. };
  55020. /**
  55021. * Creates a dashed line mesh.
  55022. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55023. * 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.
  55024. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55025. * The parameter `points` is an array successive Vector3.
  55026. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55027. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55028. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55029. * 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
  55030. * When updating an instance, remember that only point positions can change, not the number of points.
  55031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55032. */
  55033. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55034. if (scene === void 0) { scene = null; }
  55035. var points = options.points;
  55036. var instance = options.instance;
  55037. var gapSize = options.gapSize || 1;
  55038. var dashSize = options.dashSize || 3;
  55039. if (instance) {
  55040. var positionFunction = function (positions) {
  55041. var curvect = BABYLON.Vector3.Zero();
  55042. var nbSeg = positions.length / 6;
  55043. var lg = 0;
  55044. var nb = 0;
  55045. var shft = 0;
  55046. var dashshft = 0;
  55047. var curshft = 0;
  55048. var p = 0;
  55049. var i = 0;
  55050. var j = 0;
  55051. for (i = 0; i < points.length - 1; i++) {
  55052. points[i + 1].subtractToRef(points[i], curvect);
  55053. lg += curvect.length();
  55054. }
  55055. shft = lg / nbSeg;
  55056. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55057. for (i = 0; i < points.length - 1; i++) {
  55058. points[i + 1].subtractToRef(points[i], curvect);
  55059. nb = Math.floor(curvect.length() / shft);
  55060. curvect.normalize();
  55061. j = 0;
  55062. while (j < nb && p < positions.length) {
  55063. curshft = shft * j;
  55064. positions[p] = points[i].x + curshft * curvect.x;
  55065. positions[p + 1] = points[i].y + curshft * curvect.y;
  55066. positions[p + 2] = points[i].z + curshft * curvect.z;
  55067. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55068. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55069. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55070. p += 6;
  55071. j++;
  55072. }
  55073. }
  55074. while (p < positions.length) {
  55075. positions[p] = points[i].x;
  55076. positions[p + 1] = points[i].y;
  55077. positions[p + 2] = points[i].z;
  55078. p += 3;
  55079. }
  55080. };
  55081. instance.updateMeshPositions(positionFunction, false);
  55082. return instance;
  55083. }
  55084. // dashed lines creation
  55085. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55086. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55087. vertexData.applyToMesh(dashedLines, options.updatable);
  55088. dashedLines.dashSize = dashSize;
  55089. dashedLines.gapSize = gapSize;
  55090. return dashedLines;
  55091. };
  55092. /**
  55093. * Creates an extruded shape mesh.
  55094. * 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.
  55095. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55096. *
  55097. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55098. * 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
  55099. * extruded along the Z axis.
  55100. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55101. * 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.
  55102. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55103. * 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
  55104. * 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
  55105. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55107. * 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).
  55108. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55109. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55111. */
  55112. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55113. if (scene === void 0) { scene = null; }
  55114. var path = options.path;
  55115. var shape = options.shape;
  55116. var scale = options.scale || 1;
  55117. var rotation = options.rotation || 0;
  55118. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55119. var updatable = options.updatable;
  55120. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55121. var instance = options.instance || null;
  55122. var invertUV = options.invertUV || false;
  55123. 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);
  55124. };
  55125. /**
  55126. * Creates an custom extruded shape mesh.
  55127. * 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.
  55128. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55129. *
  55130. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55131. * 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
  55132. * extruded along the Z axis.
  55133. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55134. * 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
  55135. * and the distance of this point from the begining of the path :
  55136. * ```javascript
  55137. * var rotationFunction = function(i, distance) {
  55138. * // do things
  55139. * return rotationValue; }
  55140. * ```
  55141. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55142. * 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
  55143. * and the distance of this point from the begining of the path :
  55144. * ```javascript
  55145. * var scaleFunction = function(i, distance) {
  55146. * // do things
  55147. * return scaleValue;}
  55148. * ```
  55149. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55150. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55151. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55152. * 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
  55153. * 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
  55154. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55155. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55156. * 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).
  55157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55158. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55160. */
  55161. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55162. var path = options.path;
  55163. var shape = options.shape;
  55164. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55165. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55166. var ribbonCloseArray = options.ribbonCloseArray || false;
  55167. var ribbonClosePath = options.ribbonClosePath || false;
  55168. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55169. var updatable = options.updatable;
  55170. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55171. var instance = options.instance;
  55172. var invertUV = options.invertUV || false;
  55173. 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);
  55174. };
  55175. /**
  55176. * Creates lathe mesh.
  55177. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55178. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55179. *
  55180. * 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
  55181. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55182. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55183. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55184. * 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.
  55185. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55186. * 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
  55187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55188. * 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).
  55189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55190. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55192. */
  55193. MeshBuilder.CreateLathe = function (name, options, scene) {
  55194. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55195. var closed = (options.closed === undefined) ? true : options.closed;
  55196. var shape = options.shape;
  55197. var radius = options.radius || 1;
  55198. var tessellation = options.tessellation || 64;
  55199. var updatable = options.updatable;
  55200. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55201. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55202. var pi2 = Math.PI * 2;
  55203. var paths = new Array();
  55204. var invertUV = options.invertUV || false;
  55205. var i = 0;
  55206. var p = 0;
  55207. var step = pi2 / tessellation * arc;
  55208. var rotated;
  55209. var path = new Array();
  55210. ;
  55211. for (i = 0; i <= tessellation; i++) {
  55212. var path = [];
  55213. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55214. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55215. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55216. }
  55217. for (p = 0; p < shape.length; p++) {
  55218. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55219. path.push(rotated);
  55220. }
  55221. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55222. 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));
  55223. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55224. }
  55225. paths.push(path);
  55226. }
  55227. // lathe ribbon
  55228. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55229. return lathe;
  55230. };
  55231. /**
  55232. * Creates a plane mesh.
  55233. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55234. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55235. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55236. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55238. * 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).
  55239. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55241. */
  55242. MeshBuilder.CreatePlane = function (name, options, scene) {
  55243. var plane = new BABYLON.Mesh(name, scene);
  55244. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55245. plane._originalBuilderSideOrientation = options.sideOrientation;
  55246. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55247. vertexData.applyToMesh(plane, options.updatable);
  55248. if (options.sourcePlane) {
  55249. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55250. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55251. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55252. plane.rotate(vectorProduct, product);
  55253. }
  55254. return plane;
  55255. };
  55256. /**
  55257. * Creates a ground mesh.
  55258. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55259. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55260. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55261. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55262. */
  55263. MeshBuilder.CreateGround = function (name, options, scene) {
  55264. var ground = new BABYLON.GroundMesh(name, scene);
  55265. ground._setReady(false);
  55266. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55267. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55268. ground._width = options.width || 1;
  55269. ground._height = options.height || 1;
  55270. ground._maxX = ground._width / 2;
  55271. ground._maxZ = ground._height / 2;
  55272. ground._minX = -ground._maxX;
  55273. ground._minZ = -ground._maxZ;
  55274. var vertexData = BABYLON.VertexData.CreateGround(options);
  55275. vertexData.applyToMesh(ground, options.updatable);
  55276. ground._setReady(true);
  55277. return ground;
  55278. };
  55279. /**
  55280. * Creates a tiled ground mesh.
  55281. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55282. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55283. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55284. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55285. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55286. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55287. * numbers of subdivisions on the ground width and height of each tile.
  55288. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55289. */
  55290. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55291. var tiledGround = new BABYLON.Mesh(name, scene);
  55292. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55293. vertexData.applyToMesh(tiledGround, options.updatable);
  55294. return tiledGround;
  55295. };
  55296. /**
  55297. * Creates a ground mesh from a height map.
  55298. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55299. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55300. * The parameter `url` sets the URL of the height map image resource.
  55301. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55302. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55303. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55304. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55305. * 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.
  55306. * 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).
  55307. * This function is passed the newly built mesh :
  55308. * ```javascript
  55309. * function(mesh) { // do things
  55310. * return; }
  55311. * ```
  55312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55313. */
  55314. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55315. var width = options.width || 10.0;
  55316. var height = options.height || 10.0;
  55317. var subdivisions = options.subdivisions || 1 | 0;
  55318. var minHeight = options.minHeight || 0.0;
  55319. var maxHeight = options.maxHeight || 1.0;
  55320. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55321. var updatable = options.updatable;
  55322. var onReady = options.onReady;
  55323. var ground = new BABYLON.GroundMesh(name, scene);
  55324. ground._subdivisionsX = subdivisions;
  55325. ground._subdivisionsY = subdivisions;
  55326. ground._width = width;
  55327. ground._height = height;
  55328. ground._maxX = ground._width / 2.0;
  55329. ground._maxZ = ground._height / 2.0;
  55330. ground._minX = -ground._maxX;
  55331. ground._minZ = -ground._maxZ;
  55332. ground._setReady(false);
  55333. var onload = function (img) {
  55334. // Getting height map data
  55335. var canvas = document.createElement("canvas");
  55336. var context = canvas.getContext("2d");
  55337. if (!context) {
  55338. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55339. }
  55340. if (scene.isDisposed) {
  55341. return;
  55342. }
  55343. var bufferWidth = img.width;
  55344. var bufferHeight = img.height;
  55345. canvas.width = bufferWidth;
  55346. canvas.height = bufferHeight;
  55347. context.drawImage(img, 0, 0);
  55348. // Create VertexData from map data
  55349. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55350. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55351. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55352. width: width, height: height,
  55353. subdivisions: subdivisions,
  55354. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55355. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55356. });
  55357. vertexData.applyToMesh(ground, updatable);
  55358. ground._setReady(true);
  55359. //execute ready callback, if set
  55360. if (onReady) {
  55361. onReady(ground);
  55362. }
  55363. };
  55364. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55365. return ground;
  55366. };
  55367. /**
  55368. * Creates a polygon mesh.
  55369. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55370. * 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.
  55371. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55373. * 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).
  55374. * Remember you can only change the shape positions, not their number when updating a polygon.
  55375. */
  55376. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55377. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55378. var shape = options.shape;
  55379. var holes = options.holes || [];
  55380. var depth = options.depth || 0;
  55381. var contours = [];
  55382. var hole = [];
  55383. for (var i = 0; i < shape.length; i++) {
  55384. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55385. }
  55386. var epsilon = 0.00000001;
  55387. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55388. contours.pop();
  55389. }
  55390. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55391. for (var hNb = 0; hNb < holes.length; hNb++) {
  55392. hole = [];
  55393. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55394. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55395. }
  55396. polygonTriangulation.addHole(hole);
  55397. }
  55398. var polygon = polygonTriangulation.build(options.updatable, depth);
  55399. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55400. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55401. vertexData.applyToMesh(polygon, options.updatable);
  55402. return polygon;
  55403. };
  55404. ;
  55405. /**
  55406. * Creates an extruded polygon mesh, with depth in the Y direction.
  55407. * 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).
  55408. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55409. */
  55410. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55411. return MeshBuilder.CreatePolygon(name, options, scene);
  55412. };
  55413. ;
  55414. /**
  55415. * Creates a tube mesh.
  55416. * 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.
  55417. *
  55418. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55419. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55420. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55421. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55422. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55423. * 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.
  55424. * It must return a radius value (positive float) :
  55425. * ```javascript
  55426. * var radiusFunction = function(i, distance) {
  55427. * // do things
  55428. * return radius; }
  55429. * ```
  55430. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55431. * 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
  55432. * 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
  55433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55434. * 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).
  55435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55436. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55438. */
  55439. MeshBuilder.CreateTube = function (name, options, scene) {
  55440. var path = options.path;
  55441. var instance = options.instance;
  55442. var radius = 1.0;
  55443. if (instance) {
  55444. radius = instance.radius;
  55445. }
  55446. if (options.radius !== undefined) {
  55447. radius = options.radius;
  55448. }
  55449. ;
  55450. var tessellation = options.tessellation || 64 | 0;
  55451. var radiusFunction = options.radiusFunction || null;
  55452. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55453. var invertUV = options.invertUV || false;
  55454. var updatable = options.updatable;
  55455. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55456. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55457. // tube geometry
  55458. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55459. var tangents = path3D.getTangents();
  55460. var normals = path3D.getNormals();
  55461. var distances = path3D.getDistances();
  55462. var pi2 = Math.PI * 2;
  55463. var step = pi2 / tessellation * arc;
  55464. var returnRadius = function () { return radius; };
  55465. var radiusFunctionFinal = radiusFunction || returnRadius;
  55466. var circlePath;
  55467. var rad;
  55468. var normal;
  55469. var rotated;
  55470. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55471. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55472. for (var i = 0; i < path.length; i++) {
  55473. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55474. circlePath = Array(); // current circle array
  55475. normal = normals[i]; // current normal
  55476. for (var t = 0; t < tessellation; t++) {
  55477. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55478. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55479. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55480. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55481. circlePath[t] = rotated;
  55482. }
  55483. circlePaths[index] = circlePath;
  55484. index++;
  55485. }
  55486. // cap
  55487. var capPath = function (nbPoints, pathIndex) {
  55488. var pointCap = Array();
  55489. for (var i = 0; i < nbPoints; i++) {
  55490. pointCap.push(path[pathIndex]);
  55491. }
  55492. return pointCap;
  55493. };
  55494. switch (cap) {
  55495. case BABYLON.Mesh.NO_CAP:
  55496. break;
  55497. case BABYLON.Mesh.CAP_START:
  55498. circlePaths[0] = capPath(tessellation, 0);
  55499. circlePaths[1] = circlePaths[2].slice(0);
  55500. break;
  55501. case BABYLON.Mesh.CAP_END:
  55502. circlePaths[index] = circlePaths[index - 1].slice(0);
  55503. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55504. break;
  55505. case BABYLON.Mesh.CAP_ALL:
  55506. circlePaths[0] = capPath(tessellation, 0);
  55507. circlePaths[1] = circlePaths[2].slice(0);
  55508. circlePaths[index] = circlePaths[index - 1].slice(0);
  55509. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55510. break;
  55511. default:
  55512. break;
  55513. }
  55514. return circlePaths;
  55515. };
  55516. var path3D;
  55517. var pathArray;
  55518. if (instance) {
  55519. var arc = options.arc || instance.arc;
  55520. path3D = (instance.path3D).update(path);
  55521. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55522. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55523. instance.path3D = path3D;
  55524. instance.pathArray = pathArray;
  55525. instance.arc = arc;
  55526. instance.radius = radius;
  55527. return instance;
  55528. }
  55529. // tube creation
  55530. path3D = new BABYLON.Path3D(path);
  55531. var newPathArray = new Array();
  55532. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55533. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55534. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55535. tube.pathArray = pathArray;
  55536. tube.path3D = path3D;
  55537. tube.tessellation = tessellation;
  55538. tube.cap = cap;
  55539. tube.arc = options.arc;
  55540. tube.radius = radius;
  55541. return tube;
  55542. };
  55543. /**
  55544. * Creates a polyhedron mesh.
  55545. *
  55546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55547. * 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
  55548. * to choose the wanted type.
  55549. * The parameter `size` (positive float, default 1) sets the polygon size.
  55550. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55551. * 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`.
  55552. * 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
  55553. * 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)`).
  55554. * 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
  55555. * 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.
  55556. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55557. * 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).
  55558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55560. */
  55561. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55562. var polyhedron = new BABYLON.Mesh(name, scene);
  55563. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55564. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55565. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55566. vertexData.applyToMesh(polyhedron, options.updatable);
  55567. return polyhedron;
  55568. };
  55569. /**
  55570. * Creates a decal mesh.
  55571. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55572. * 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.
  55573. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55574. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55575. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55576. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55577. */
  55578. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55579. var indices = sourceMesh.getIndices();
  55580. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55581. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55582. var position = options.position || BABYLON.Vector3.Zero();
  55583. var normal = options.normal || BABYLON.Vector3.Up();
  55584. var size = options.size || BABYLON.Vector3.One();
  55585. var angle = options.angle || 0;
  55586. // Getting correct rotation
  55587. if (!normal) {
  55588. var target = new BABYLON.Vector3(0, 0, 1);
  55589. var camera = sourceMesh.getScene().activeCamera;
  55590. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55591. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55592. }
  55593. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55594. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55595. var pitch = Math.atan2(normal.y, len);
  55596. // Matrix
  55597. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55598. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55599. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55600. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55601. var vertexData = new BABYLON.VertexData();
  55602. vertexData.indices = [];
  55603. vertexData.positions = [];
  55604. vertexData.normals = [];
  55605. vertexData.uvs = [];
  55606. var currentVertexDataIndex = 0;
  55607. var extractDecalVector3 = function (indexId) {
  55608. var result = new BABYLON.PositionNormalVertex();
  55609. if (!indices || !positions || !normals) {
  55610. return result;
  55611. }
  55612. var vertexId = indices[indexId];
  55613. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55614. // Send vector to decal local world
  55615. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55616. // Get normal
  55617. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55618. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55619. return result;
  55620. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55621. var clip = function (vertices, axis) {
  55622. if (vertices.length === 0) {
  55623. return vertices;
  55624. }
  55625. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55626. var clipVertices = function (v0, v1) {
  55627. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55628. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55629. };
  55630. var result = new Array();
  55631. for (var index = 0; index < vertices.length; index += 3) {
  55632. var v1Out;
  55633. var v2Out;
  55634. var v3Out;
  55635. var total = 0;
  55636. var nV1 = null;
  55637. var nV2 = null;
  55638. var nV3 = null;
  55639. var nV4 = null;
  55640. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55641. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55642. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55643. v1Out = d1 > 0;
  55644. v2Out = d2 > 0;
  55645. v3Out = d3 > 0;
  55646. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55647. switch (total) {
  55648. case 0:
  55649. result.push(vertices[index]);
  55650. result.push(vertices[index + 1]);
  55651. result.push(vertices[index + 2]);
  55652. break;
  55653. case 1:
  55654. if (v1Out) {
  55655. nV1 = vertices[index + 1];
  55656. nV2 = vertices[index + 2];
  55657. nV3 = clipVertices(vertices[index], nV1);
  55658. nV4 = clipVertices(vertices[index], nV2);
  55659. }
  55660. if (v2Out) {
  55661. nV1 = vertices[index];
  55662. nV2 = vertices[index + 2];
  55663. nV3 = clipVertices(vertices[index + 1], nV1);
  55664. nV4 = clipVertices(vertices[index + 1], nV2);
  55665. result.push(nV3);
  55666. result.push(nV2.clone());
  55667. result.push(nV1.clone());
  55668. result.push(nV2.clone());
  55669. result.push(nV3.clone());
  55670. result.push(nV4);
  55671. break;
  55672. }
  55673. if (v3Out) {
  55674. nV1 = vertices[index];
  55675. nV2 = vertices[index + 1];
  55676. nV3 = clipVertices(vertices[index + 2], nV1);
  55677. nV4 = clipVertices(vertices[index + 2], nV2);
  55678. }
  55679. if (nV1 && nV2 && nV3 && nV4) {
  55680. result.push(nV1.clone());
  55681. result.push(nV2.clone());
  55682. result.push(nV3);
  55683. result.push(nV4);
  55684. result.push(nV3.clone());
  55685. result.push(nV2.clone());
  55686. }
  55687. break;
  55688. case 2:
  55689. if (!v1Out) {
  55690. nV1 = vertices[index].clone();
  55691. nV2 = clipVertices(nV1, vertices[index + 1]);
  55692. nV3 = clipVertices(nV1, vertices[index + 2]);
  55693. result.push(nV1);
  55694. result.push(nV2);
  55695. result.push(nV3);
  55696. }
  55697. if (!v2Out) {
  55698. nV1 = vertices[index + 1].clone();
  55699. nV2 = clipVertices(nV1, vertices[index + 2]);
  55700. nV3 = clipVertices(nV1, vertices[index]);
  55701. result.push(nV1);
  55702. result.push(nV2);
  55703. result.push(nV3);
  55704. }
  55705. if (!v3Out) {
  55706. nV1 = vertices[index + 2].clone();
  55707. nV2 = clipVertices(nV1, vertices[index]);
  55708. nV3 = clipVertices(nV1, vertices[index + 1]);
  55709. result.push(nV1);
  55710. result.push(nV2);
  55711. result.push(nV3);
  55712. }
  55713. break;
  55714. case 3:
  55715. break;
  55716. }
  55717. }
  55718. return result;
  55719. };
  55720. for (var index = 0; index < indices.length; index += 3) {
  55721. var faceVertices = new Array();
  55722. faceVertices.push(extractDecalVector3(index));
  55723. faceVertices.push(extractDecalVector3(index + 1));
  55724. faceVertices.push(extractDecalVector3(index + 2));
  55725. // Clip
  55726. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55727. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55728. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55729. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55730. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55731. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55732. if (faceVertices.length === 0) {
  55733. continue;
  55734. }
  55735. // Add UVs and get back to world
  55736. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55737. var vertex = faceVertices[vIndex];
  55738. //TODO check for Int32Array | Uint32Array | Uint16Array
  55739. vertexData.indices.push(currentVertexDataIndex);
  55740. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55741. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55742. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55743. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55744. currentVertexDataIndex++;
  55745. }
  55746. }
  55747. // Return mesh
  55748. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55749. vertexData.applyToMesh(decal);
  55750. decal.position = position.clone();
  55751. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55752. return decal;
  55753. };
  55754. // Privates
  55755. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55756. // extrusion geometry
  55757. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55758. var tangents = path3D.getTangents();
  55759. var normals = path3D.getNormals();
  55760. var binormals = path3D.getBinormals();
  55761. var distances = path3D.getDistances();
  55762. var angle = 0;
  55763. var returnScale = function () { return scale !== null ? scale : 1; };
  55764. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55765. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55766. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55767. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55768. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55769. for (var i = 0; i < curve.length; i++) {
  55770. var shapePath = new Array();
  55771. var angleStep = rotate(i, distances[i]);
  55772. var scaleRatio = scl(i, distances[i]);
  55773. for (var p = 0; p < shape.length; p++) {
  55774. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55775. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55776. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55777. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55778. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55779. shapePath[p] = rotated;
  55780. }
  55781. shapePaths[index] = shapePath;
  55782. angle += angleStep;
  55783. index++;
  55784. }
  55785. // cap
  55786. var capPath = function (shapePath) {
  55787. var pointCap = Array();
  55788. var barycenter = BABYLON.Vector3.Zero();
  55789. var i;
  55790. for (i = 0; i < shapePath.length; i++) {
  55791. barycenter.addInPlace(shapePath[i]);
  55792. }
  55793. barycenter.scaleInPlace(1.0 / shapePath.length);
  55794. for (i = 0; i < shapePath.length; i++) {
  55795. pointCap.push(barycenter);
  55796. }
  55797. return pointCap;
  55798. };
  55799. switch (cap) {
  55800. case BABYLON.Mesh.NO_CAP:
  55801. break;
  55802. case BABYLON.Mesh.CAP_START:
  55803. shapePaths[0] = capPath(shapePaths[2]);
  55804. shapePaths[1] = shapePaths[2];
  55805. break;
  55806. case BABYLON.Mesh.CAP_END:
  55807. shapePaths[index] = shapePaths[index - 1];
  55808. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55809. break;
  55810. case BABYLON.Mesh.CAP_ALL:
  55811. shapePaths[0] = capPath(shapePaths[2]);
  55812. shapePaths[1] = shapePaths[2];
  55813. shapePaths[index] = shapePaths[index - 1];
  55814. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55815. break;
  55816. default:
  55817. break;
  55818. }
  55819. return shapePaths;
  55820. };
  55821. var path3D;
  55822. var pathArray;
  55823. if (instance) {
  55824. path3D = (instance.path3D).update(curve);
  55825. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55826. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55827. return instance;
  55828. }
  55829. // extruded shape creation
  55830. path3D = new BABYLON.Path3D(curve);
  55831. var newShapePaths = new Array();
  55832. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55833. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55834. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55835. extrudedGeneric.pathArray = pathArray;
  55836. extrudedGeneric.path3D = path3D;
  55837. extrudedGeneric.cap = cap;
  55838. return extrudedGeneric;
  55839. };
  55840. return MeshBuilder;
  55841. }());
  55842. BABYLON.MeshBuilder = MeshBuilder;
  55843. })(BABYLON || (BABYLON = {}));
  55844. //# sourceMappingURL=babylon.meshBuilder.js.map
  55845. var BABYLON;
  55846. (function (BABYLON) {
  55847. /**
  55848. * Draco compression (https://google.github.io/draco/)
  55849. */
  55850. var DracoCompression = /** @class */ (function () {
  55851. /**
  55852. * Constructor
  55853. * @param numWorkers The number of workers for async operations
  55854. */
  55855. function DracoCompression(numWorkers) {
  55856. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55857. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55858. if (!workerBlobUrl || !Worker) {
  55859. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  55860. return;
  55861. }
  55862. var workers = new Array(numWorkers);
  55863. for (var i = 0; i < workers.length; i++) {
  55864. var worker = new Worker(workerBlobUrl);
  55865. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55866. workers[i] = worker;
  55867. }
  55868. this._workerPool = new BABYLON.WorkerPool(workers);
  55869. }
  55870. /**
  55871. * Stop all async operations and release resources.
  55872. */
  55873. DracoCompression.prototype.dispose = function () {
  55874. this._workerPool.dispose();
  55875. delete this._workerPool;
  55876. };
  55877. /**
  55878. * Decode Draco compressed mesh data to vertex data.
  55879. * @param data The array buffer view for the Draco compression data
  55880. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55881. * @returns A promise that resolves with the decoded vertex data
  55882. */
  55883. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55884. var _this = this;
  55885. return new Promise(function (resolve, reject) {
  55886. _this._workerPool.push(function (worker, onComplete) {
  55887. var vertexData = new BABYLON.VertexData();
  55888. var onError = function (error) {
  55889. worker.removeEventListener("error", onError);
  55890. worker.removeEventListener("message", onMessage);
  55891. reject(error);
  55892. onComplete();
  55893. };
  55894. var onMessage = function (message) {
  55895. if (message.data === "done") {
  55896. worker.removeEventListener("error", onError);
  55897. worker.removeEventListener("message", onMessage);
  55898. resolve(vertexData);
  55899. onComplete();
  55900. }
  55901. else if (message.data.id === "indices") {
  55902. vertexData.indices = message.data.value;
  55903. }
  55904. else {
  55905. vertexData.set(message.data.value, message.data.id);
  55906. }
  55907. };
  55908. worker.addEventListener("error", onError);
  55909. worker.addEventListener("message", onMessage);
  55910. var dataCopy = new Uint8Array(data.byteLength);
  55911. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55912. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55913. });
  55914. });
  55915. };
  55916. /**
  55917. * The worker function that gets converted to a blob url to pass into a worker.
  55918. */
  55919. DracoCompression._Worker = function () {
  55920. // self is actually a DedicatedWorkerGlobalScope
  55921. var _self = self;
  55922. var decodeMesh = function (data, attributes) {
  55923. var dracoModule = new DracoDecoderModule();
  55924. var buffer = new dracoModule.DecoderBuffer();
  55925. buffer.Init(data, data.byteLength);
  55926. var decoder = new dracoModule.Decoder();
  55927. var geometry;
  55928. var status;
  55929. try {
  55930. var type = decoder.GetEncodedGeometryType(buffer);
  55931. switch (type) {
  55932. case dracoModule.TRIANGULAR_MESH:
  55933. geometry = new dracoModule.Mesh();
  55934. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55935. break;
  55936. case dracoModule.POINT_CLOUD:
  55937. geometry = new dracoModule.PointCloud();
  55938. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55939. break;
  55940. default:
  55941. throw new Error("Invalid geometry type " + type);
  55942. }
  55943. if (!status.ok() || !geometry.ptr) {
  55944. throw new Error(status.error_msg());
  55945. }
  55946. var numPoints = geometry.num_points();
  55947. if (type === dracoModule.TRIANGULAR_MESH) {
  55948. var numFaces = geometry.num_faces();
  55949. var faceIndices = new dracoModule.DracoInt32Array();
  55950. try {
  55951. var indices = new Uint32Array(numFaces * 3);
  55952. for (var i = 0; i < numFaces; i++) {
  55953. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  55954. var offset = i * 3;
  55955. indices[offset + 0] = faceIndices.GetValue(0);
  55956. indices[offset + 1] = faceIndices.GetValue(1);
  55957. indices[offset + 2] = faceIndices.GetValue(2);
  55958. }
  55959. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  55960. }
  55961. finally {
  55962. dracoModule.destroy(faceIndices);
  55963. }
  55964. }
  55965. for (var kind in attributes) {
  55966. var uniqueId = attributes[kind];
  55967. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  55968. var dracoData = new dracoModule.DracoFloat32Array();
  55969. try {
  55970. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  55971. var babylonData = new Float32Array(numPoints * attribute.num_components());
  55972. for (var i = 0; i < babylonData.length; i++) {
  55973. babylonData[i] = dracoData.GetValue(i);
  55974. }
  55975. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  55976. }
  55977. finally {
  55978. dracoModule.destroy(dracoData);
  55979. }
  55980. }
  55981. }
  55982. finally {
  55983. if (geometry) {
  55984. dracoModule.destroy(geometry);
  55985. }
  55986. dracoModule.destroy(decoder);
  55987. dracoModule.destroy(buffer);
  55988. }
  55989. _self.postMessage("done");
  55990. };
  55991. _self.onmessage = function (event) {
  55992. switch (event.data.id) {
  55993. case "initDecoder": {
  55994. importScripts(event.data.url);
  55995. break;
  55996. }
  55997. case "decodeMesh": {
  55998. decodeMesh(event.data.data, event.data.attributes);
  55999. break;
  56000. }
  56001. }
  56002. };
  56003. };
  56004. DracoCompression._GetDefaultDecoderUrl = function () {
  56005. for (var i = 0; i < document.scripts.length; i++) {
  56006. if (document.scripts[i].type === "text/x-draco-decoder") {
  56007. return document.scripts[i].src;
  56008. }
  56009. }
  56010. return null;
  56011. };
  56012. /**
  56013. * Gets the url to the draco decoder if available.
  56014. */
  56015. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56016. return DracoCompression;
  56017. }());
  56018. BABYLON.DracoCompression = DracoCompression;
  56019. })(BABYLON || (BABYLON = {}));
  56020. //# sourceMappingURL=babylon.dracoCompression.js.map
  56021. var BABYLON;
  56022. (function (BABYLON) {
  56023. var AudioEngine = /** @class */ (function () {
  56024. function AudioEngine() {
  56025. this._audioContext = null;
  56026. this._audioContextInitialized = false;
  56027. this.canUseWebAudio = false;
  56028. this.WarnedWebAudioUnsupported = false;
  56029. this.unlocked = false;
  56030. this.isMP3supported = false;
  56031. this.isOGGsupported = false;
  56032. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56033. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56034. this.canUseWebAudio = true;
  56035. }
  56036. var audioElem = document.createElement('audio');
  56037. try {
  56038. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56039. this.isMP3supported = true;
  56040. }
  56041. }
  56042. catch (e) {
  56043. // protect error during capability check.
  56044. }
  56045. try {
  56046. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56047. this.isOGGsupported = true;
  56048. }
  56049. }
  56050. catch (e) {
  56051. // protect error during capability check.
  56052. }
  56053. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56054. this._unlockiOSaudio();
  56055. }
  56056. else {
  56057. this.unlocked = true;
  56058. }
  56059. }
  56060. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56061. get: function () {
  56062. if (!this._audioContextInitialized) {
  56063. this._initializeAudioContext();
  56064. }
  56065. return this._audioContext;
  56066. },
  56067. enumerable: true,
  56068. configurable: true
  56069. });
  56070. AudioEngine.prototype._unlockiOSaudio = function () {
  56071. var _this = this;
  56072. var unlockaudio = function () {
  56073. if (!_this.audioContext) {
  56074. return;
  56075. }
  56076. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56077. var source = _this.audioContext.createBufferSource();
  56078. source.buffer = buffer;
  56079. source.connect(_this.audioContext.destination);
  56080. source.start(0);
  56081. setTimeout(function () {
  56082. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56083. _this.unlocked = true;
  56084. window.removeEventListener('touchend', unlockaudio, false);
  56085. if (_this.onAudioUnlocked) {
  56086. _this.onAudioUnlocked();
  56087. }
  56088. }
  56089. }, 0);
  56090. };
  56091. window.addEventListener('touchend', unlockaudio, false);
  56092. };
  56093. AudioEngine.prototype._initializeAudioContext = function () {
  56094. try {
  56095. if (this.canUseWebAudio) {
  56096. this._audioContext = new AudioContext();
  56097. // create a global volume gain node
  56098. this.masterGain = this._audioContext.createGain();
  56099. this.masterGain.gain.value = 1;
  56100. this.masterGain.connect(this._audioContext.destination);
  56101. this._audioContextInitialized = true;
  56102. }
  56103. }
  56104. catch (e) {
  56105. this.canUseWebAudio = false;
  56106. BABYLON.Tools.Error("Web Audio: " + e.message);
  56107. }
  56108. };
  56109. AudioEngine.prototype.dispose = function () {
  56110. if (this.canUseWebAudio && this._audioContextInitialized) {
  56111. if (this._connectedAnalyser && this._audioContext) {
  56112. this._connectedAnalyser.stopDebugCanvas();
  56113. this._connectedAnalyser.dispose();
  56114. this.masterGain.disconnect();
  56115. this.masterGain.connect(this._audioContext.destination);
  56116. this._connectedAnalyser = null;
  56117. }
  56118. this.masterGain.gain.value = 1;
  56119. }
  56120. this.WarnedWebAudioUnsupported = false;
  56121. };
  56122. AudioEngine.prototype.getGlobalVolume = function () {
  56123. if (this.canUseWebAudio && this._audioContextInitialized) {
  56124. return this.masterGain.gain.value;
  56125. }
  56126. else {
  56127. return -1;
  56128. }
  56129. };
  56130. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56131. if (this.canUseWebAudio && this._audioContextInitialized) {
  56132. this.masterGain.gain.value = newVolume;
  56133. }
  56134. };
  56135. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56136. if (this._connectedAnalyser) {
  56137. this._connectedAnalyser.stopDebugCanvas();
  56138. }
  56139. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56140. this._connectedAnalyser = analyser;
  56141. this.masterGain.disconnect();
  56142. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56143. }
  56144. };
  56145. return AudioEngine;
  56146. }());
  56147. BABYLON.AudioEngine = AudioEngine;
  56148. })(BABYLON || (BABYLON = {}));
  56149. //# sourceMappingURL=babylon.audioEngine.js.map
  56150. var BABYLON;
  56151. (function (BABYLON) {
  56152. var Sound = /** @class */ (function () {
  56153. /**
  56154. * Create a sound and attach it to a scene
  56155. * @param name Name of your sound
  56156. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56157. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56158. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56159. */
  56160. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56161. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56162. var _this = this;
  56163. this.autoplay = false;
  56164. this.loop = false;
  56165. this.useCustomAttenuation = false;
  56166. this.spatialSound = false;
  56167. this.refDistance = 1;
  56168. this.rolloffFactor = 1;
  56169. this.maxDistance = 100;
  56170. this.distanceModel = "linear";
  56171. this._panningModel = "equalpower";
  56172. this._playbackRate = 1;
  56173. this._streaming = false;
  56174. this._startTime = 0;
  56175. this._startOffset = 0;
  56176. this._position = BABYLON.Vector3.Zero();
  56177. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56178. this._volume = 1;
  56179. this._isReadyToPlay = false;
  56180. this.isPlaying = false;
  56181. this.isPaused = false;
  56182. this._isDirectional = false;
  56183. // Used if you'd like to create a directional sound.
  56184. // If not set, the sound will be omnidirectional
  56185. this._coneInnerAngle = 360;
  56186. this._coneOuterAngle = 360;
  56187. this._coneOuterGain = 0;
  56188. this._isOutputConnected = false;
  56189. this._urlType = "Unknown";
  56190. this.name = name;
  56191. this._scene = scene;
  56192. this._readyToPlayCallback = readyToPlayCallback;
  56193. // Default custom attenuation function is a linear attenuation
  56194. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56195. if (currentDistance < maxDistance) {
  56196. return currentVolume * (1 - currentDistance / maxDistance);
  56197. }
  56198. else {
  56199. return 0;
  56200. }
  56201. };
  56202. if (options) {
  56203. this.autoplay = options.autoplay || false;
  56204. this.loop = options.loop || false;
  56205. // if volume === 0, we need another way to check this option
  56206. if (options.volume !== undefined) {
  56207. this._volume = options.volume;
  56208. }
  56209. this.spatialSound = options.spatialSound || false;
  56210. this.maxDistance = options.maxDistance || 100;
  56211. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56212. this.rolloffFactor = options.rolloffFactor || 1;
  56213. this.refDistance = options.refDistance || 1;
  56214. this.distanceModel = options.distanceModel || "linear";
  56215. this._playbackRate = options.playbackRate || 1;
  56216. this._streaming = options.streaming || false;
  56217. }
  56218. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56219. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56220. this._soundGain.gain.value = this._volume;
  56221. this._inputAudioNode = this._soundGain;
  56222. this._ouputAudioNode = this._soundGain;
  56223. if (this.spatialSound) {
  56224. this._createSpatialParameters();
  56225. }
  56226. this._scene.mainSoundTrack.AddSound(this);
  56227. var validParameter = true;
  56228. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56229. if (urlOrArrayBuffer) {
  56230. if (typeof (urlOrArrayBuffer) === "string")
  56231. this._urlType = "String";
  56232. if (Array.isArray(urlOrArrayBuffer))
  56233. this._urlType = "Array";
  56234. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56235. this._urlType = "ArrayBuffer";
  56236. var urls = [];
  56237. var codecSupportedFound = false;
  56238. switch (this._urlType) {
  56239. case "ArrayBuffer":
  56240. if (urlOrArrayBuffer.byteLength > 0) {
  56241. codecSupportedFound = true;
  56242. this._soundLoaded(urlOrArrayBuffer);
  56243. }
  56244. break;
  56245. case "String":
  56246. urls.push(urlOrArrayBuffer);
  56247. case "Array":
  56248. if (urls.length === 0)
  56249. urls = urlOrArrayBuffer;
  56250. // If we found a supported format, we load it immediately and stop the loop
  56251. for (var i = 0; i < urls.length; i++) {
  56252. var url = urls[i];
  56253. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56254. codecSupportedFound = true;
  56255. }
  56256. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56257. codecSupportedFound = true;
  56258. }
  56259. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56260. codecSupportedFound = true;
  56261. }
  56262. if (url.indexOf("blob:") !== -1) {
  56263. codecSupportedFound = true;
  56264. }
  56265. if (codecSupportedFound) {
  56266. // Loading sound using XHR2
  56267. if (!this._streaming) {
  56268. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56269. }
  56270. else {
  56271. this._htmlAudioElement = new Audio(url);
  56272. this._htmlAudioElement.controls = false;
  56273. this._htmlAudioElement.loop = this.loop;
  56274. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56275. this._htmlAudioElement.preload = "auto";
  56276. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56277. _this._isReadyToPlay = true;
  56278. if (_this.autoplay) {
  56279. _this.play();
  56280. }
  56281. if (_this._readyToPlayCallback) {
  56282. _this._readyToPlayCallback();
  56283. }
  56284. });
  56285. document.body.appendChild(this._htmlAudioElement);
  56286. }
  56287. break;
  56288. }
  56289. }
  56290. break;
  56291. default:
  56292. validParameter = false;
  56293. break;
  56294. }
  56295. if (!validParameter) {
  56296. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56297. }
  56298. else {
  56299. if (!codecSupportedFound) {
  56300. this._isReadyToPlay = true;
  56301. // Simulating a ready to play event to avoid breaking code path
  56302. if (this._readyToPlayCallback) {
  56303. window.setTimeout(function () {
  56304. if (_this._readyToPlayCallback) {
  56305. _this._readyToPlayCallback();
  56306. }
  56307. }, 1000);
  56308. }
  56309. }
  56310. }
  56311. }
  56312. }
  56313. else {
  56314. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56315. this._scene.mainSoundTrack.AddSound(this);
  56316. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56317. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56318. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56319. }
  56320. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56321. if (this._readyToPlayCallback) {
  56322. window.setTimeout(function () {
  56323. if (_this._readyToPlayCallback) {
  56324. _this._readyToPlayCallback();
  56325. }
  56326. }, 1000);
  56327. }
  56328. }
  56329. }
  56330. Sound.prototype.dispose = function () {
  56331. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56332. if (this.isPlaying) {
  56333. this.stop();
  56334. }
  56335. this._isReadyToPlay = false;
  56336. if (this.soundTrackId === -1) {
  56337. this._scene.mainSoundTrack.RemoveSound(this);
  56338. }
  56339. else {
  56340. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56341. }
  56342. if (this._soundGain) {
  56343. this._soundGain.disconnect();
  56344. this._soundGain = null;
  56345. }
  56346. if (this._soundPanner) {
  56347. this._soundPanner.disconnect();
  56348. this._soundPanner = null;
  56349. }
  56350. if (this._soundSource) {
  56351. this._soundSource.disconnect();
  56352. this._soundSource = null;
  56353. }
  56354. this._audioBuffer = null;
  56355. if (this._htmlAudioElement) {
  56356. this._htmlAudioElement.pause();
  56357. this._htmlAudioElement.src = "";
  56358. document.body.removeChild(this._htmlAudioElement);
  56359. }
  56360. if (this._connectedMesh && this._registerFunc) {
  56361. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56362. this._connectedMesh = null;
  56363. }
  56364. }
  56365. };
  56366. Sound.prototype.isReady = function () {
  56367. return this._isReadyToPlay;
  56368. };
  56369. Sound.prototype._soundLoaded = function (audioData) {
  56370. var _this = this;
  56371. if (!BABYLON.Engine.audioEngine.audioContext) {
  56372. return;
  56373. }
  56374. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56375. _this._audioBuffer = buffer;
  56376. _this._isReadyToPlay = true;
  56377. if (_this.autoplay) {
  56378. _this.play();
  56379. }
  56380. if (_this._readyToPlayCallback) {
  56381. _this._readyToPlayCallback();
  56382. }
  56383. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56384. };
  56385. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56386. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56387. this._audioBuffer = audioBuffer;
  56388. this._isReadyToPlay = true;
  56389. }
  56390. };
  56391. Sound.prototype.updateOptions = function (options) {
  56392. if (options) {
  56393. this.loop = options.loop || this.loop;
  56394. this.maxDistance = options.maxDistance || this.maxDistance;
  56395. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56396. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56397. this.refDistance = options.refDistance || this.refDistance;
  56398. this.distanceModel = options.distanceModel || this.distanceModel;
  56399. this._playbackRate = options.playbackRate || this._playbackRate;
  56400. this._updateSpatialParameters();
  56401. if (this.isPlaying) {
  56402. if (this._streaming) {
  56403. this._htmlAudioElement.playbackRate = this._playbackRate;
  56404. }
  56405. else {
  56406. if (this._soundSource) {
  56407. this._soundSource.playbackRate.value = this._playbackRate;
  56408. }
  56409. }
  56410. }
  56411. }
  56412. };
  56413. Sound.prototype._createSpatialParameters = function () {
  56414. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56415. if (this._scene.headphone) {
  56416. this._panningModel = "HRTF";
  56417. }
  56418. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56419. this._updateSpatialParameters();
  56420. this._soundPanner.connect(this._ouputAudioNode);
  56421. this._inputAudioNode = this._soundPanner;
  56422. }
  56423. };
  56424. Sound.prototype._updateSpatialParameters = function () {
  56425. if (this.spatialSound && this._soundPanner) {
  56426. if (this.useCustomAttenuation) {
  56427. // Tricks to disable in a way embedded Web Audio attenuation
  56428. this._soundPanner.distanceModel = "linear";
  56429. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56430. this._soundPanner.refDistance = 1;
  56431. this._soundPanner.rolloffFactor = 1;
  56432. this._soundPanner.panningModel = this._panningModel;
  56433. }
  56434. else {
  56435. this._soundPanner.distanceModel = this.distanceModel;
  56436. this._soundPanner.maxDistance = this.maxDistance;
  56437. this._soundPanner.refDistance = this.refDistance;
  56438. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56439. this._soundPanner.panningModel = this._panningModel;
  56440. }
  56441. }
  56442. };
  56443. Sound.prototype.switchPanningModelToHRTF = function () {
  56444. this._panningModel = "HRTF";
  56445. this._switchPanningModel();
  56446. };
  56447. Sound.prototype.switchPanningModelToEqualPower = function () {
  56448. this._panningModel = "equalpower";
  56449. this._switchPanningModel();
  56450. };
  56451. Sound.prototype._switchPanningModel = function () {
  56452. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56453. this._soundPanner.panningModel = this._panningModel;
  56454. }
  56455. };
  56456. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56457. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56458. if (this._isOutputConnected) {
  56459. this._ouputAudioNode.disconnect();
  56460. }
  56461. this._ouputAudioNode.connect(soundTrackAudioNode);
  56462. this._isOutputConnected = true;
  56463. }
  56464. };
  56465. /**
  56466. * Transform this sound into a directional source
  56467. * @param coneInnerAngle Size of the inner cone in degree
  56468. * @param coneOuterAngle Size of the outer cone in degree
  56469. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56470. */
  56471. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56472. if (coneOuterAngle < coneInnerAngle) {
  56473. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56474. return;
  56475. }
  56476. this._coneInnerAngle = coneInnerAngle;
  56477. this._coneOuterAngle = coneOuterAngle;
  56478. this._coneOuterGain = coneOuterGain;
  56479. this._isDirectional = true;
  56480. if (this.isPlaying && this.loop) {
  56481. this.stop();
  56482. this.play();
  56483. }
  56484. };
  56485. Sound.prototype.setPosition = function (newPosition) {
  56486. this._position = newPosition;
  56487. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56488. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56489. }
  56490. };
  56491. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56492. this._localDirection = newLocalDirection;
  56493. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56494. this._updateDirection();
  56495. }
  56496. };
  56497. Sound.prototype._updateDirection = function () {
  56498. if (!this._connectedMesh || !this._soundPanner) {
  56499. return;
  56500. }
  56501. var mat = this._connectedMesh.getWorldMatrix();
  56502. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56503. direction.normalize();
  56504. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56505. };
  56506. Sound.prototype.updateDistanceFromListener = function () {
  56507. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56508. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56509. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56510. }
  56511. };
  56512. Sound.prototype.setAttenuationFunction = function (callback) {
  56513. this._customAttenuationFunction = callback;
  56514. };
  56515. /**
  56516. * Play the sound
  56517. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56518. * @param offset (optional) Start the sound setting it at a specific time
  56519. */
  56520. Sound.prototype.play = function (time, offset) {
  56521. var _this = this;
  56522. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56523. try {
  56524. if (this._startOffset < 0) {
  56525. time = -this._startOffset;
  56526. this._startOffset = 0;
  56527. }
  56528. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56529. if (!this._soundSource || !this._streamingSource) {
  56530. if (this.spatialSound && this._soundPanner) {
  56531. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56532. if (this._isDirectional) {
  56533. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56534. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56535. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56536. if (this._connectedMesh) {
  56537. this._updateDirection();
  56538. }
  56539. else {
  56540. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56541. }
  56542. }
  56543. }
  56544. }
  56545. if (this._streaming) {
  56546. if (!this._streamingSource) {
  56547. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56548. this._htmlAudioElement.onended = function () { _this._onended(); };
  56549. this._htmlAudioElement.playbackRate = this._playbackRate;
  56550. }
  56551. this._streamingSource.disconnect();
  56552. this._streamingSource.connect(this._inputAudioNode);
  56553. this._htmlAudioElement.play();
  56554. }
  56555. else {
  56556. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56557. this._soundSource.buffer = this._audioBuffer;
  56558. this._soundSource.connect(this._inputAudioNode);
  56559. this._soundSource.loop = this.loop;
  56560. this._soundSource.playbackRate.value = this._playbackRate;
  56561. this._soundSource.onended = function () { _this._onended(); };
  56562. if (this._soundSource.buffer) {
  56563. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56564. }
  56565. }
  56566. this._startTime = startTime;
  56567. this.isPlaying = true;
  56568. this.isPaused = false;
  56569. }
  56570. catch (ex) {
  56571. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56572. }
  56573. }
  56574. };
  56575. Sound.prototype._onended = function () {
  56576. this.isPlaying = false;
  56577. if (this.onended) {
  56578. this.onended();
  56579. }
  56580. };
  56581. /**
  56582. * Stop the sound
  56583. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56584. */
  56585. Sound.prototype.stop = function (time) {
  56586. if (this.isPlaying) {
  56587. if (this._streaming) {
  56588. this._htmlAudioElement.pause();
  56589. // Test needed for Firefox or it will generate an Invalid State Error
  56590. if (this._htmlAudioElement.currentTime > 0) {
  56591. this._htmlAudioElement.currentTime = 0;
  56592. }
  56593. }
  56594. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56595. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56596. this._soundSource.stop(stopTime);
  56597. this._soundSource.onended = function () { };
  56598. if (!this.isPaused) {
  56599. this._startOffset = 0;
  56600. }
  56601. }
  56602. this.isPlaying = false;
  56603. }
  56604. };
  56605. Sound.prototype.pause = function () {
  56606. if (this.isPlaying) {
  56607. this.isPaused = true;
  56608. if (this._streaming) {
  56609. this._htmlAudioElement.pause();
  56610. }
  56611. else if (BABYLON.Engine.audioEngine.audioContext) {
  56612. this.stop(0);
  56613. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56614. }
  56615. }
  56616. };
  56617. Sound.prototype.setVolume = function (newVolume, time) {
  56618. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56619. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56620. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56621. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56622. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56623. }
  56624. else {
  56625. this._soundGain.gain.value = newVolume;
  56626. }
  56627. }
  56628. this._volume = newVolume;
  56629. };
  56630. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56631. this._playbackRate = newPlaybackRate;
  56632. if (this.isPlaying) {
  56633. if (this._streaming) {
  56634. this._htmlAudioElement.playbackRate = this._playbackRate;
  56635. }
  56636. else if (this._soundSource) {
  56637. this._soundSource.playbackRate.value = this._playbackRate;
  56638. }
  56639. }
  56640. };
  56641. Sound.prototype.getVolume = function () {
  56642. return this._volume;
  56643. };
  56644. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56645. var _this = this;
  56646. if (this._connectedMesh && this._registerFunc) {
  56647. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56648. this._registerFunc = null;
  56649. }
  56650. this._connectedMesh = meshToConnectTo;
  56651. if (!this.spatialSound) {
  56652. this.spatialSound = true;
  56653. this._createSpatialParameters();
  56654. if (this.isPlaying && this.loop) {
  56655. this.stop();
  56656. this.play();
  56657. }
  56658. }
  56659. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56660. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56661. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56662. };
  56663. Sound.prototype.detachFromMesh = function () {
  56664. if (this._connectedMesh && this._registerFunc) {
  56665. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56666. this._registerFunc = null;
  56667. this._connectedMesh = null;
  56668. }
  56669. };
  56670. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56671. if (!node.getBoundingInfo) {
  56672. return;
  56673. }
  56674. var mesh = node;
  56675. var boundingInfo = mesh.getBoundingInfo();
  56676. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56677. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56678. this._updateDirection();
  56679. }
  56680. };
  56681. Sound.prototype.clone = function () {
  56682. var _this = this;
  56683. if (!this._streaming) {
  56684. var setBufferAndRun = function () {
  56685. if (_this._isReadyToPlay) {
  56686. clonedSound._audioBuffer = _this.getAudioBuffer();
  56687. clonedSound._isReadyToPlay = true;
  56688. if (clonedSound.autoplay) {
  56689. clonedSound.play();
  56690. }
  56691. }
  56692. else {
  56693. window.setTimeout(setBufferAndRun, 300);
  56694. }
  56695. };
  56696. var currentOptions = {
  56697. autoplay: this.autoplay, loop: this.loop,
  56698. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56699. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56700. refDistance: this.refDistance, distanceModel: this.distanceModel
  56701. };
  56702. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56703. if (this.useCustomAttenuation) {
  56704. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56705. }
  56706. clonedSound.setPosition(this._position);
  56707. clonedSound.setPlaybackRate(this._playbackRate);
  56708. setBufferAndRun();
  56709. return clonedSound;
  56710. }
  56711. else {
  56712. return null;
  56713. }
  56714. };
  56715. Sound.prototype.getAudioBuffer = function () {
  56716. return this._audioBuffer;
  56717. };
  56718. Sound.prototype.serialize = function () {
  56719. var serializationObject = {
  56720. name: this.name,
  56721. url: this.name,
  56722. autoplay: this.autoplay,
  56723. loop: this.loop,
  56724. volume: this._volume,
  56725. spatialSound: this.spatialSound,
  56726. maxDistance: this.maxDistance,
  56727. rolloffFactor: this.rolloffFactor,
  56728. refDistance: this.refDistance,
  56729. distanceModel: this.distanceModel,
  56730. playbackRate: this._playbackRate,
  56731. panningModel: this._panningModel,
  56732. soundTrackId: this.soundTrackId
  56733. };
  56734. if (this.spatialSound) {
  56735. if (this._connectedMesh)
  56736. serializationObject.connectedMeshId = this._connectedMesh.id;
  56737. serializationObject.position = this._position.asArray();
  56738. serializationObject.refDistance = this.refDistance;
  56739. serializationObject.distanceModel = this.distanceModel;
  56740. serializationObject.isDirectional = this._isDirectional;
  56741. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56742. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56743. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56744. serializationObject.coneOuterGain = this._coneOuterGain;
  56745. }
  56746. return serializationObject;
  56747. };
  56748. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56749. var soundName = parsedSound.name;
  56750. var soundUrl;
  56751. if (parsedSound.url) {
  56752. soundUrl = rootUrl + parsedSound.url;
  56753. }
  56754. else {
  56755. soundUrl = rootUrl + soundName;
  56756. }
  56757. var options = {
  56758. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56759. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56760. rolloffFactor: parsedSound.rolloffFactor,
  56761. refDistance: parsedSound.refDistance,
  56762. distanceModel: parsedSound.distanceModel,
  56763. playbackRate: parsedSound.playbackRate
  56764. };
  56765. var newSound;
  56766. if (!sourceSound) {
  56767. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56768. scene._addPendingData(newSound);
  56769. }
  56770. else {
  56771. var setBufferAndRun = function () {
  56772. if (sourceSound._isReadyToPlay) {
  56773. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56774. newSound._isReadyToPlay = true;
  56775. if (newSound.autoplay) {
  56776. newSound.play();
  56777. }
  56778. }
  56779. else {
  56780. window.setTimeout(setBufferAndRun, 300);
  56781. }
  56782. };
  56783. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56784. setBufferAndRun();
  56785. }
  56786. if (parsedSound.position) {
  56787. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56788. newSound.setPosition(soundPosition);
  56789. }
  56790. if (parsedSound.isDirectional) {
  56791. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56792. if (parsedSound.localDirectionToMesh) {
  56793. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56794. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56795. }
  56796. }
  56797. if (parsedSound.connectedMeshId) {
  56798. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56799. if (connectedMesh) {
  56800. newSound.attachToMesh(connectedMesh);
  56801. }
  56802. }
  56803. return newSound;
  56804. };
  56805. return Sound;
  56806. }());
  56807. BABYLON.Sound = Sound;
  56808. })(BABYLON || (BABYLON = {}));
  56809. //# sourceMappingURL=babylon.sound.js.map
  56810. var BABYLON;
  56811. (function (BABYLON) {
  56812. var SoundTrack = /** @class */ (function () {
  56813. function SoundTrack(scene, options) {
  56814. this.id = -1;
  56815. this._isMainTrack = false;
  56816. this._isInitialized = false;
  56817. this._scene = scene;
  56818. this.soundCollection = new Array();
  56819. this._options = options;
  56820. if (!this._isMainTrack) {
  56821. this._scene.soundTracks.push(this);
  56822. this.id = this._scene.soundTracks.length - 1;
  56823. }
  56824. }
  56825. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56826. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56827. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56828. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56829. if (this._options) {
  56830. if (this._options.volume) {
  56831. this._outputAudioNode.gain.value = this._options.volume;
  56832. }
  56833. if (this._options.mainTrack) {
  56834. this._isMainTrack = this._options.mainTrack;
  56835. }
  56836. }
  56837. this._isInitialized = true;
  56838. }
  56839. };
  56840. SoundTrack.prototype.dispose = function () {
  56841. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56842. if (this._connectedAnalyser) {
  56843. this._connectedAnalyser.stopDebugCanvas();
  56844. }
  56845. while (this.soundCollection.length) {
  56846. this.soundCollection[0].dispose();
  56847. }
  56848. if (this._outputAudioNode) {
  56849. this._outputAudioNode.disconnect();
  56850. }
  56851. this._outputAudioNode = null;
  56852. }
  56853. };
  56854. SoundTrack.prototype.AddSound = function (sound) {
  56855. if (!this._isInitialized) {
  56856. this._initializeSoundTrackAudioGraph();
  56857. }
  56858. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56859. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56860. }
  56861. if (sound.soundTrackId) {
  56862. if (sound.soundTrackId === -1) {
  56863. this._scene.mainSoundTrack.RemoveSound(sound);
  56864. }
  56865. else {
  56866. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56867. }
  56868. }
  56869. this.soundCollection.push(sound);
  56870. sound.soundTrackId = this.id;
  56871. };
  56872. SoundTrack.prototype.RemoveSound = function (sound) {
  56873. var index = this.soundCollection.indexOf(sound);
  56874. if (index !== -1) {
  56875. this.soundCollection.splice(index, 1);
  56876. }
  56877. };
  56878. SoundTrack.prototype.setVolume = function (newVolume) {
  56879. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56880. this._outputAudioNode.gain.value = newVolume;
  56881. }
  56882. };
  56883. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56884. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56885. for (var i = 0; i < this.soundCollection.length; i++) {
  56886. this.soundCollection[i].switchPanningModelToHRTF();
  56887. }
  56888. }
  56889. };
  56890. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56891. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56892. for (var i = 0; i < this.soundCollection.length; i++) {
  56893. this.soundCollection[i].switchPanningModelToEqualPower();
  56894. }
  56895. }
  56896. };
  56897. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56898. if (this._connectedAnalyser) {
  56899. this._connectedAnalyser.stopDebugCanvas();
  56900. }
  56901. this._connectedAnalyser = analyser;
  56902. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56903. this._outputAudioNode.disconnect();
  56904. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56905. }
  56906. };
  56907. return SoundTrack;
  56908. }());
  56909. BABYLON.SoundTrack = SoundTrack;
  56910. })(BABYLON || (BABYLON = {}));
  56911. //# sourceMappingURL=babylon.soundtrack.js.map
  56912. var BABYLON;
  56913. (function (BABYLON) {
  56914. var Analyser = /** @class */ (function () {
  56915. function Analyser(scene) {
  56916. this.SMOOTHING = 0.75;
  56917. this.FFT_SIZE = 512;
  56918. this.BARGRAPHAMPLITUDE = 256;
  56919. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56920. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56921. this._scene = scene;
  56922. this._audioEngine = BABYLON.Engine.audioEngine;
  56923. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56924. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56925. this._webAudioAnalyser.minDecibels = -140;
  56926. this._webAudioAnalyser.maxDecibels = 0;
  56927. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56928. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56929. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56930. }
  56931. }
  56932. Analyser.prototype.getFrequencyBinCount = function () {
  56933. if (this._audioEngine.canUseWebAudio) {
  56934. return this._webAudioAnalyser.frequencyBinCount;
  56935. }
  56936. else {
  56937. return 0;
  56938. }
  56939. };
  56940. Analyser.prototype.getByteFrequencyData = function () {
  56941. if (this._audioEngine.canUseWebAudio) {
  56942. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56943. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56944. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56945. }
  56946. return this._byteFreqs;
  56947. };
  56948. Analyser.prototype.getByteTimeDomainData = function () {
  56949. if (this._audioEngine.canUseWebAudio) {
  56950. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56951. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56952. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56953. }
  56954. return this._byteTime;
  56955. };
  56956. Analyser.prototype.getFloatFrequencyData = function () {
  56957. if (this._audioEngine.canUseWebAudio) {
  56958. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56959. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56960. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56961. }
  56962. return this._floatFreqs;
  56963. };
  56964. Analyser.prototype.drawDebugCanvas = function () {
  56965. var _this = this;
  56966. if (this._audioEngine.canUseWebAudio) {
  56967. if (!this._debugCanvas) {
  56968. this._debugCanvas = document.createElement("canvas");
  56969. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56970. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56971. this._debugCanvas.style.position = "absolute";
  56972. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56973. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56974. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56975. document.body.appendChild(this._debugCanvas);
  56976. this._registerFunc = function () {
  56977. _this.drawDebugCanvas();
  56978. };
  56979. this._scene.registerBeforeRender(this._registerFunc);
  56980. }
  56981. if (this._registerFunc && this._debugCanvasContext) {
  56982. var workingArray = this.getByteFrequencyData();
  56983. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56984. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56985. // Draw the frequency domain chart.
  56986. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56987. var value = workingArray[i];
  56988. var percent = value / this.BARGRAPHAMPLITUDE;
  56989. var height = this.DEBUGCANVASSIZE.height * percent;
  56990. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56991. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56992. var hue = i / this.getFrequencyBinCount() * 360;
  56993. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56994. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56995. }
  56996. }
  56997. }
  56998. };
  56999. Analyser.prototype.stopDebugCanvas = function () {
  57000. if (this._debugCanvas) {
  57001. if (this._registerFunc) {
  57002. this._scene.unregisterBeforeRender(this._registerFunc);
  57003. this._registerFunc = null;
  57004. }
  57005. document.body.removeChild(this._debugCanvas);
  57006. this._debugCanvas = null;
  57007. this._debugCanvasContext = null;
  57008. }
  57009. };
  57010. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57011. if (this._audioEngine.canUseWebAudio) {
  57012. inputAudioNode.connect(this._webAudioAnalyser);
  57013. this._webAudioAnalyser.connect(outputAudioNode);
  57014. }
  57015. };
  57016. Analyser.prototype.dispose = function () {
  57017. if (this._audioEngine.canUseWebAudio) {
  57018. this._webAudioAnalyser.disconnect();
  57019. }
  57020. };
  57021. return Analyser;
  57022. }());
  57023. BABYLON.Analyser = Analyser;
  57024. })(BABYLON || (BABYLON = {}));
  57025. //# sourceMappingURL=babylon.analyser.js.map
  57026. var BABYLON;
  57027. (function (BABYLON) {
  57028. var CubeTexture = /** @class */ (function (_super) {
  57029. __extends(CubeTexture, _super);
  57030. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57031. if (extensions === void 0) { extensions = null; }
  57032. if (noMipmap === void 0) { noMipmap = false; }
  57033. if (files === void 0) { files = null; }
  57034. if (onLoad === void 0) { onLoad = null; }
  57035. if (onError === void 0) { onError = null; }
  57036. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57037. if (prefiltered === void 0) { prefiltered = false; }
  57038. if (forcedExtension === void 0) { forcedExtension = null; }
  57039. var _this = _super.call(this, scene) || this;
  57040. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57041. /**
  57042. * Gets or sets the center of the bounding box associated with the cube texture
  57043. * It must define where the camera used to render the texture was set
  57044. */
  57045. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57046. _this.name = rootUrl;
  57047. _this.url = rootUrl;
  57048. _this._noMipmap = noMipmap;
  57049. _this.hasAlpha = false;
  57050. _this._format = format;
  57051. _this._prefiltered = prefiltered;
  57052. _this.isCube = true;
  57053. _this._textureMatrix = BABYLON.Matrix.Identity();
  57054. if (prefiltered) {
  57055. _this.gammaSpace = false;
  57056. }
  57057. if (!rootUrl && !files) {
  57058. return _this;
  57059. }
  57060. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57061. var lastDot = rootUrl.lastIndexOf(".");
  57062. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57063. var isDDS = (extension === ".dds");
  57064. if (!files) {
  57065. if (!isDDS && !extensions) {
  57066. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57067. }
  57068. files = [];
  57069. if (extensions) {
  57070. for (var index = 0; index < extensions.length; index++) {
  57071. files.push(rootUrl + extensions[index]);
  57072. }
  57073. }
  57074. }
  57075. _this._files = files;
  57076. if (!_this._texture) {
  57077. if (!scene.useDelayedTextureLoading) {
  57078. if (prefiltered) {
  57079. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57080. }
  57081. else {
  57082. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57083. }
  57084. }
  57085. else {
  57086. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57087. }
  57088. }
  57089. else if (onLoad) {
  57090. if (_this._texture.isReady) {
  57091. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57092. }
  57093. else {
  57094. _this._texture.onLoadedObservable.add(onLoad);
  57095. }
  57096. }
  57097. return _this;
  57098. }
  57099. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57100. get: function () {
  57101. return this._boundingBoxSize;
  57102. },
  57103. /**
  57104. * Gets or sets the size of the bounding box associated with the cube texture
  57105. * When defined, the cubemap will switch to local mode
  57106. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57107. * @example https://www.babylonjs-playground.com/#RNASML
  57108. */
  57109. set: function (value) {
  57110. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57111. return;
  57112. }
  57113. this._boundingBoxSize = value;
  57114. var scene = this.getScene();
  57115. if (scene) {
  57116. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57117. }
  57118. },
  57119. enumerable: true,
  57120. configurable: true
  57121. });
  57122. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57123. var rootUrlKey = "";
  57124. files.forEach(function (url) { return rootUrlKey += url; });
  57125. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57126. };
  57127. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57128. if (forcedExtension === void 0) { forcedExtension = null; }
  57129. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57130. };
  57131. // Methods
  57132. CubeTexture.prototype.delayLoad = function () {
  57133. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57134. return;
  57135. }
  57136. var scene = this.getScene();
  57137. if (!scene) {
  57138. return;
  57139. }
  57140. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57141. this._texture = this._getFromCache(this.url, this._noMipmap);
  57142. if (!this._texture) {
  57143. if (this._prefiltered) {
  57144. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57145. }
  57146. else {
  57147. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57148. }
  57149. }
  57150. };
  57151. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57152. return this._textureMatrix;
  57153. };
  57154. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57155. this._textureMatrix = value;
  57156. };
  57157. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57158. var texture = BABYLON.SerializationHelper.Parse(function () {
  57159. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57160. }, parsedTexture, scene);
  57161. // Local Cubemaps
  57162. if (parsedTexture.boundingBoxPosition) {
  57163. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57164. }
  57165. if (parsedTexture.boundingBoxSize) {
  57166. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57167. }
  57168. // Animations
  57169. if (parsedTexture.animations) {
  57170. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57171. var parsedAnimation = parsedTexture.animations[animationIndex];
  57172. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57173. }
  57174. }
  57175. return texture;
  57176. };
  57177. CubeTexture.prototype.clone = function () {
  57178. var _this = this;
  57179. return BABYLON.SerializationHelper.Clone(function () {
  57180. var scene = _this.getScene();
  57181. if (!scene) {
  57182. return _this;
  57183. }
  57184. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57185. }, this);
  57186. };
  57187. return CubeTexture;
  57188. }(BABYLON.BaseTexture));
  57189. BABYLON.CubeTexture = CubeTexture;
  57190. })(BABYLON || (BABYLON = {}));
  57191. //# sourceMappingURL=babylon.cubeTexture.js.map
  57192. var BABYLON;
  57193. (function (BABYLON) {
  57194. var RenderTargetTexture = /** @class */ (function (_super) {
  57195. __extends(RenderTargetTexture, _super);
  57196. /**
  57197. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57198. * or used a shadow, depth texture...
  57199. * @param name The friendly name of the texture
  57200. * @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)
  57201. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57202. * @param generateMipMaps True if mip maps need to be generated after render.
  57203. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57204. * @param type The type of the buffer in the RTT (int, half float, float...)
  57205. * @param isCube True if a cube texture needs to be created
  57206. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57207. * @param generateDepthBuffer True to generate a depth buffer
  57208. * @param generateStencilBuffer True to generate a stencil buffer
  57209. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57210. */
  57211. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57212. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57213. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57214. if (isCube === void 0) { isCube = false; }
  57215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57216. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57217. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57218. if (isMulti === void 0) { isMulti = false; }
  57219. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57220. _this.isCube = isCube;
  57221. /**
  57222. * Use this list to define the list of mesh you want to render.
  57223. */
  57224. _this.renderList = new Array();
  57225. _this.renderParticles = true;
  57226. _this.renderSprites = false;
  57227. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57228. _this.ignoreCameraViewport = false;
  57229. // Events
  57230. /**
  57231. * An event triggered when the texture is unbind.
  57232. * @type {BABYLON.Observable}
  57233. */
  57234. _this.onBeforeBindObservable = new BABYLON.Observable();
  57235. /**
  57236. * An event triggered when the texture is unbind.
  57237. * @type {BABYLON.Observable}
  57238. */
  57239. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57240. /**
  57241. * An event triggered before rendering the texture
  57242. * @type {BABYLON.Observable}
  57243. */
  57244. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57245. /**
  57246. * An event triggered after rendering the texture
  57247. * @type {BABYLON.Observable}
  57248. */
  57249. _this.onAfterRenderObservable = new BABYLON.Observable();
  57250. /**
  57251. * An event triggered after the texture clear
  57252. * @type {BABYLON.Observable}
  57253. */
  57254. _this.onClearObservable = new BABYLON.Observable();
  57255. _this._currentRefreshId = -1;
  57256. _this._refreshRate = 1;
  57257. _this._samples = 1;
  57258. /**
  57259. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57260. * It must define where the camera used to render the texture is set
  57261. */
  57262. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57263. scene = _this.getScene();
  57264. if (!scene) {
  57265. return _this;
  57266. }
  57267. _this._engine = scene.getEngine();
  57268. _this.name = name;
  57269. _this.isRenderTarget = true;
  57270. _this._initialSizeParameter = size;
  57271. _this._processSizeParameter(size);
  57272. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57273. });
  57274. _this._generateMipMaps = generateMipMaps ? true : false;
  57275. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57276. // Rendering groups
  57277. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57278. if (isMulti) {
  57279. return _this;
  57280. }
  57281. _this._renderTargetOptions = {
  57282. generateMipMaps: generateMipMaps,
  57283. type: type,
  57284. samplingMode: samplingMode,
  57285. generateDepthBuffer: generateDepthBuffer,
  57286. generateStencilBuffer: generateStencilBuffer
  57287. };
  57288. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57289. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57290. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57291. }
  57292. if (isCube) {
  57293. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57294. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57295. _this._textureMatrix = BABYLON.Matrix.Identity();
  57296. }
  57297. else {
  57298. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57299. }
  57300. return _this;
  57301. }
  57302. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57303. get: function () {
  57304. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57305. },
  57306. enumerable: true,
  57307. configurable: true
  57308. });
  57309. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57310. get: function () {
  57311. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57312. },
  57313. enumerable: true,
  57314. configurable: true
  57315. });
  57316. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57317. get: function () {
  57318. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57319. },
  57320. enumerable: true,
  57321. configurable: true
  57322. });
  57323. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57324. set: function (callback) {
  57325. if (this._onAfterUnbindObserver) {
  57326. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57327. }
  57328. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57329. },
  57330. enumerable: true,
  57331. configurable: true
  57332. });
  57333. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57334. set: function (callback) {
  57335. if (this._onBeforeRenderObserver) {
  57336. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57337. }
  57338. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57339. },
  57340. enumerable: true,
  57341. configurable: true
  57342. });
  57343. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57344. set: function (callback) {
  57345. if (this._onAfterRenderObserver) {
  57346. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57347. }
  57348. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57349. },
  57350. enumerable: true,
  57351. configurable: true
  57352. });
  57353. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57354. set: function (callback) {
  57355. if (this._onClearObserver) {
  57356. this.onClearObservable.remove(this._onClearObserver);
  57357. }
  57358. this._onClearObserver = this.onClearObservable.add(callback);
  57359. },
  57360. enumerable: true,
  57361. configurable: true
  57362. });
  57363. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57364. get: function () {
  57365. return this._renderTargetOptions;
  57366. },
  57367. enumerable: true,
  57368. configurable: true
  57369. });
  57370. RenderTargetTexture.prototype._onRatioRescale = function () {
  57371. if (this._sizeRatio) {
  57372. this.resize(this._initialSizeParameter);
  57373. }
  57374. };
  57375. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57376. get: function () {
  57377. return this._boundingBoxSize;
  57378. },
  57379. /**
  57380. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57381. * When defined, the cubemap will switch to local mode
  57382. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57383. * @example https://www.babylonjs-playground.com/#RNASML
  57384. */
  57385. set: function (value) {
  57386. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57387. return;
  57388. }
  57389. this._boundingBoxSize = value;
  57390. var scene = this.getScene();
  57391. if (scene) {
  57392. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57393. }
  57394. },
  57395. enumerable: true,
  57396. configurable: true
  57397. });
  57398. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57399. if (size.ratio) {
  57400. this._sizeRatio = size.ratio;
  57401. this._size = {
  57402. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57403. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57404. };
  57405. }
  57406. else {
  57407. this._size = size;
  57408. }
  57409. };
  57410. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57411. get: function () {
  57412. return this._samples;
  57413. },
  57414. set: function (value) {
  57415. if (this._samples === value) {
  57416. return;
  57417. }
  57418. var scene = this.getScene();
  57419. if (!scene) {
  57420. return;
  57421. }
  57422. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57423. },
  57424. enumerable: true,
  57425. configurable: true
  57426. });
  57427. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57428. this._currentRefreshId = -1;
  57429. };
  57430. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57431. get: function () {
  57432. return this._refreshRate;
  57433. },
  57434. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57435. set: function (value) {
  57436. this._refreshRate = value;
  57437. this.resetRefreshCounter();
  57438. },
  57439. enumerable: true,
  57440. configurable: true
  57441. });
  57442. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57443. if (!this._postProcessManager) {
  57444. var scene = this.getScene();
  57445. if (!scene) {
  57446. return;
  57447. }
  57448. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57449. this._postProcesses = new Array();
  57450. }
  57451. this._postProcesses.push(postProcess);
  57452. this._postProcesses[0].autoClear = false;
  57453. };
  57454. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57455. if (!this._postProcesses) {
  57456. return;
  57457. }
  57458. if (dispose) {
  57459. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57460. var postProcess = _a[_i];
  57461. postProcess.dispose();
  57462. }
  57463. }
  57464. this._postProcesses = [];
  57465. };
  57466. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57467. if (!this._postProcesses) {
  57468. return;
  57469. }
  57470. var index = this._postProcesses.indexOf(postProcess);
  57471. if (index === -1) {
  57472. return;
  57473. }
  57474. this._postProcesses.splice(index, 1);
  57475. if (this._postProcesses.length > 0) {
  57476. this._postProcesses[0].autoClear = false;
  57477. }
  57478. };
  57479. RenderTargetTexture.prototype._shouldRender = function () {
  57480. if (this._currentRefreshId === -1) {
  57481. this._currentRefreshId = 1;
  57482. return true;
  57483. }
  57484. if (this.refreshRate === this._currentRefreshId) {
  57485. this._currentRefreshId = 1;
  57486. return true;
  57487. }
  57488. this._currentRefreshId++;
  57489. return false;
  57490. };
  57491. RenderTargetTexture.prototype.getRenderSize = function () {
  57492. if (this._size.width) {
  57493. return this._size.width;
  57494. }
  57495. return this._size;
  57496. };
  57497. RenderTargetTexture.prototype.getRenderWidth = function () {
  57498. if (this._size.width) {
  57499. return this._size.width;
  57500. }
  57501. return this._size;
  57502. };
  57503. RenderTargetTexture.prototype.getRenderHeight = function () {
  57504. if (this._size.width) {
  57505. return this._size.height;
  57506. }
  57507. return this._size;
  57508. };
  57509. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57510. get: function () {
  57511. return true;
  57512. },
  57513. enumerable: true,
  57514. configurable: true
  57515. });
  57516. RenderTargetTexture.prototype.scale = function (ratio) {
  57517. var newSize = this.getRenderSize() * ratio;
  57518. this.resize(newSize);
  57519. };
  57520. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57521. if (this.isCube) {
  57522. return this._textureMatrix;
  57523. }
  57524. return _super.prototype.getReflectionTextureMatrix.call(this);
  57525. };
  57526. RenderTargetTexture.prototype.resize = function (size) {
  57527. this.releaseInternalTexture();
  57528. var scene = this.getScene();
  57529. if (!scene) {
  57530. return;
  57531. }
  57532. this._processSizeParameter(size);
  57533. if (this.isCube) {
  57534. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57535. }
  57536. else {
  57537. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57538. }
  57539. };
  57540. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57541. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57542. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57543. var scene = this.getScene();
  57544. if (!scene) {
  57545. return;
  57546. }
  57547. var engine = scene.getEngine();
  57548. if (this.useCameraPostProcesses !== undefined) {
  57549. useCameraPostProcess = this.useCameraPostProcesses;
  57550. }
  57551. if (this._waitingRenderList) {
  57552. this.renderList = [];
  57553. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57554. var id = this._waitingRenderList[index];
  57555. var mesh_1 = scene.getMeshByID(id);
  57556. if (mesh_1) {
  57557. this.renderList.push(mesh_1);
  57558. }
  57559. }
  57560. delete this._waitingRenderList;
  57561. }
  57562. // Is predicate defined?
  57563. if (this.renderListPredicate) {
  57564. if (this.renderList) {
  57565. this.renderList.splice(0); // Clear previous renderList
  57566. }
  57567. else {
  57568. this.renderList = [];
  57569. }
  57570. var scene = this.getScene();
  57571. if (!scene) {
  57572. return;
  57573. }
  57574. var sceneMeshes = scene.meshes;
  57575. for (var index = 0; index < sceneMeshes.length; index++) {
  57576. var mesh = sceneMeshes[index];
  57577. if (this.renderListPredicate(mesh)) {
  57578. this.renderList.push(mesh);
  57579. }
  57580. }
  57581. }
  57582. this.onBeforeBindObservable.notifyObservers(this);
  57583. // Set custom projection.
  57584. // Needs to be before binding to prevent changing the aspect ratio.
  57585. var camera;
  57586. if (this.activeCamera) {
  57587. camera = this.activeCamera;
  57588. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57589. if (this.activeCamera !== scene.activeCamera) {
  57590. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57591. }
  57592. }
  57593. else {
  57594. camera = scene.activeCamera;
  57595. if (camera) {
  57596. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57597. }
  57598. }
  57599. // Prepare renderingManager
  57600. this._renderingManager.reset();
  57601. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57602. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57603. var sceneRenderId = scene.getRenderId();
  57604. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57605. var mesh = currentRenderList[meshIndex];
  57606. if (mesh) {
  57607. if (!mesh.isReady()) {
  57608. // Reset _currentRefreshId
  57609. this.resetRefreshCounter();
  57610. continue;
  57611. }
  57612. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57613. var isMasked = void 0;
  57614. if (!this.renderList && camera) {
  57615. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57616. }
  57617. else {
  57618. isMasked = false;
  57619. }
  57620. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57621. mesh._activate(sceneRenderId);
  57622. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57623. var subMesh = mesh.subMeshes[subIndex];
  57624. scene._activeIndices.addCount(subMesh.indexCount, false);
  57625. this._renderingManager.dispatch(subMesh, mesh);
  57626. }
  57627. }
  57628. }
  57629. }
  57630. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57631. var particleSystem = scene.particleSystems[particleIndex];
  57632. var emitter = particleSystem.emitter;
  57633. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57634. continue;
  57635. }
  57636. if (currentRenderList.indexOf(emitter) >= 0) {
  57637. this._renderingManager.dispatchParticles(particleSystem);
  57638. }
  57639. }
  57640. if (this.isCube) {
  57641. for (var face = 0; face < 6; face++) {
  57642. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57643. scene.incrementRenderId();
  57644. scene.resetCachedMaterial();
  57645. }
  57646. }
  57647. else {
  57648. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57649. }
  57650. this.onAfterUnbindObservable.notifyObservers(this);
  57651. if (scene.activeCamera) {
  57652. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57653. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57654. }
  57655. engine.setViewport(scene.activeCamera.viewport);
  57656. }
  57657. scene.resetCachedMaterial();
  57658. };
  57659. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57660. var minimum = 128;
  57661. var x = renderDimension * scale;
  57662. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57663. // Ensure we don't exceed the render dimension (while staying POT)
  57664. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57665. };
  57666. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57667. var _this = this;
  57668. if (!this._texture) {
  57669. return;
  57670. }
  57671. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57672. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57673. });
  57674. };
  57675. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57676. var scene = this.getScene();
  57677. if (!scene) {
  57678. return;
  57679. }
  57680. var engine = scene.getEngine();
  57681. if (!this._texture) {
  57682. return;
  57683. }
  57684. // Bind
  57685. if (this._postProcessManager) {
  57686. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57687. }
  57688. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57689. if (this._texture) {
  57690. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57691. }
  57692. }
  57693. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57694. // Clear
  57695. if (this.onClearObservable.hasObservers()) {
  57696. this.onClearObservable.notifyObservers(engine);
  57697. }
  57698. else {
  57699. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57700. }
  57701. if (!this._doNotChangeAspectRatio) {
  57702. scene.updateTransformMatrix(true);
  57703. }
  57704. // Render
  57705. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57706. if (this._postProcessManager) {
  57707. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57708. }
  57709. else if (useCameraPostProcess) {
  57710. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57711. }
  57712. if (!this._doNotChangeAspectRatio) {
  57713. scene.updateTransformMatrix(true);
  57714. }
  57715. // Dump ?
  57716. if (dumpForDebug) {
  57717. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57718. }
  57719. // Unbind
  57720. if (!this.isCube || faceIndex === 5) {
  57721. if (this.isCube) {
  57722. if (faceIndex === 5) {
  57723. engine.generateMipMapsForCubemap(this._texture);
  57724. }
  57725. }
  57726. this.unbindFrameBuffer(engine, faceIndex);
  57727. }
  57728. else {
  57729. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57730. }
  57731. };
  57732. /**
  57733. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57734. * This allowed control for front to back rendering or reversly depending of the special needs.
  57735. *
  57736. * @param renderingGroupId The rendering group id corresponding to its index
  57737. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57738. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57739. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57740. */
  57741. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57742. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57743. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57744. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57745. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57746. };
  57747. /**
  57748. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57749. *
  57750. * @param renderingGroupId The rendering group id corresponding to its index
  57751. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57752. */
  57753. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57754. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57755. };
  57756. RenderTargetTexture.prototype.clone = function () {
  57757. var textureSize = this.getSize();
  57758. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  57759. // Base texture
  57760. newTexture.hasAlpha = this.hasAlpha;
  57761. newTexture.level = this.level;
  57762. // RenderTarget Texture
  57763. newTexture.coordinatesMode = this.coordinatesMode;
  57764. if (this.renderList) {
  57765. newTexture.renderList = this.renderList.slice(0);
  57766. }
  57767. return newTexture;
  57768. };
  57769. RenderTargetTexture.prototype.serialize = function () {
  57770. if (!this.name) {
  57771. return null;
  57772. }
  57773. var serializationObject = _super.prototype.serialize.call(this);
  57774. serializationObject.renderTargetSize = this.getRenderSize();
  57775. serializationObject.renderList = [];
  57776. if (this.renderList) {
  57777. for (var index = 0; index < this.renderList.length; index++) {
  57778. serializationObject.renderList.push(this.renderList[index].id);
  57779. }
  57780. }
  57781. return serializationObject;
  57782. };
  57783. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57784. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57785. var objBuffer = this.getInternalTexture();
  57786. var scene = this.getScene();
  57787. if (objBuffer && scene) {
  57788. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57789. }
  57790. };
  57791. RenderTargetTexture.prototype.dispose = function () {
  57792. if (this._postProcessManager) {
  57793. this._postProcessManager.dispose();
  57794. this._postProcessManager = null;
  57795. }
  57796. this.clearPostProcesses(true);
  57797. if (this._resizeObserver) {
  57798. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57799. this._resizeObserver = null;
  57800. }
  57801. this.renderList = null;
  57802. // Remove from custom render targets
  57803. var scene = this.getScene();
  57804. if (!scene) {
  57805. return;
  57806. }
  57807. var index = scene.customRenderTargets.indexOf(this);
  57808. if (index >= 0) {
  57809. scene.customRenderTargets.splice(index, 1);
  57810. }
  57811. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57812. var camera = _a[_i];
  57813. index = camera.customRenderTargets.indexOf(this);
  57814. if (index >= 0) {
  57815. camera.customRenderTargets.splice(index, 1);
  57816. }
  57817. }
  57818. _super.prototype.dispose.call(this);
  57819. };
  57820. RenderTargetTexture.prototype._rebuild = function () {
  57821. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57822. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57823. }
  57824. if (this._postProcessManager) {
  57825. this._postProcessManager._rebuild();
  57826. }
  57827. };
  57828. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57829. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57830. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57831. return RenderTargetTexture;
  57832. }(BABYLON.Texture));
  57833. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57834. })(BABYLON || (BABYLON = {}));
  57835. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57836. var BABYLON;
  57837. (function (BABYLON) {
  57838. ;
  57839. var MultiRenderTarget = /** @class */ (function (_super) {
  57840. __extends(MultiRenderTarget, _super);
  57841. function MultiRenderTarget(name, size, count, scene, options) {
  57842. var _this = this;
  57843. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57844. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57845. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57846. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57847. _this._engine = scene.getEngine();
  57848. if (!_this.isSupported) {
  57849. _this.dispose();
  57850. return;
  57851. }
  57852. var types = [];
  57853. var samplingModes = [];
  57854. for (var i = 0; i < count; i++) {
  57855. if (options && options.types && options.types[i] !== undefined) {
  57856. types.push(options.types[i]);
  57857. }
  57858. else {
  57859. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57860. }
  57861. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57862. samplingModes.push(options.samplingModes[i]);
  57863. }
  57864. else {
  57865. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57866. }
  57867. }
  57868. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57869. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57870. _this._size = size;
  57871. _this._multiRenderTargetOptions = {
  57872. samplingModes: samplingModes,
  57873. generateMipMaps: generateMipMaps,
  57874. generateDepthBuffer: generateDepthBuffer,
  57875. generateStencilBuffer: generateStencilBuffer,
  57876. generateDepthTexture: generateDepthTexture,
  57877. types: types,
  57878. textureCount: count
  57879. };
  57880. _this._createInternalTextures();
  57881. _this._createTextures();
  57882. return _this;
  57883. }
  57884. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57885. get: function () {
  57886. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57887. },
  57888. enumerable: true,
  57889. configurable: true
  57890. });
  57891. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57892. get: function () {
  57893. return this._textures;
  57894. },
  57895. enumerable: true,
  57896. configurable: true
  57897. });
  57898. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57899. get: function () {
  57900. return this._textures[this._textures.length - 1];
  57901. },
  57902. enumerable: true,
  57903. configurable: true
  57904. });
  57905. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57906. set: function (wrap) {
  57907. if (this._textures) {
  57908. for (var i = 0; i < this._textures.length; i++) {
  57909. this._textures[i].wrapU = wrap;
  57910. }
  57911. }
  57912. },
  57913. enumerable: true,
  57914. configurable: true
  57915. });
  57916. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57917. set: function (wrap) {
  57918. if (this._textures) {
  57919. for (var i = 0; i < this._textures.length; i++) {
  57920. this._textures[i].wrapV = wrap;
  57921. }
  57922. }
  57923. },
  57924. enumerable: true,
  57925. configurable: true
  57926. });
  57927. MultiRenderTarget.prototype._rebuild = function () {
  57928. this.releaseInternalTextures();
  57929. this._createInternalTextures();
  57930. for (var i = 0; i < this._internalTextures.length; i++) {
  57931. var texture = this._textures[i];
  57932. texture._texture = this._internalTextures[i];
  57933. }
  57934. // Keeps references to frame buffer and stencil/depth buffer
  57935. this._texture = this._internalTextures[0];
  57936. };
  57937. MultiRenderTarget.prototype._createInternalTextures = function () {
  57938. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57939. };
  57940. MultiRenderTarget.prototype._createTextures = function () {
  57941. this._textures = [];
  57942. for (var i = 0; i < this._internalTextures.length; i++) {
  57943. var texture = new BABYLON.Texture(null, this.getScene());
  57944. texture._texture = this._internalTextures[i];
  57945. this._textures.push(texture);
  57946. }
  57947. // Keeps references to frame buffer and stencil/depth buffer
  57948. this._texture = this._internalTextures[0];
  57949. };
  57950. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57951. get: function () {
  57952. return this._samples;
  57953. },
  57954. set: function (value) {
  57955. if (this._samples === value) {
  57956. return;
  57957. }
  57958. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57959. },
  57960. enumerable: true,
  57961. configurable: true
  57962. });
  57963. MultiRenderTarget.prototype.resize = function (size) {
  57964. this.releaseInternalTextures();
  57965. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57966. this._createInternalTextures();
  57967. };
  57968. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57969. var _this = this;
  57970. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57971. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57972. });
  57973. };
  57974. MultiRenderTarget.prototype.dispose = function () {
  57975. this.releaseInternalTextures();
  57976. _super.prototype.dispose.call(this);
  57977. };
  57978. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57979. if (!this._internalTextures) {
  57980. return;
  57981. }
  57982. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57983. if (this._internalTextures[i] !== undefined) {
  57984. this._internalTextures[i].dispose();
  57985. this._internalTextures.splice(i, 1);
  57986. }
  57987. }
  57988. };
  57989. return MultiRenderTarget;
  57990. }(BABYLON.RenderTargetTexture));
  57991. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57992. })(BABYLON || (BABYLON = {}));
  57993. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57994. var BABYLON;
  57995. (function (BABYLON) {
  57996. var MirrorTexture = /** @class */ (function (_super) {
  57997. __extends(MirrorTexture, _super);
  57998. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57999. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58000. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58001. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58002. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58003. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58004. _this._transformMatrix = BABYLON.Matrix.Zero();
  58005. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58006. _this._adaptiveBlurKernel = 0;
  58007. _this._blurKernelX = 0;
  58008. _this._blurKernelY = 0;
  58009. _this._blurRatio = 1.0;
  58010. _this.ignoreCameraViewport = true;
  58011. _this.onBeforeRenderObservable.add(function () {
  58012. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58013. _this._savedViewMatrix = scene.getViewMatrix();
  58014. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58015. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58016. scene.clipPlane = _this.mirrorPlane;
  58017. scene.getEngine().cullBackFaces = false;
  58018. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58019. });
  58020. _this.onAfterRenderObservable.add(function () {
  58021. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58022. scene.getEngine().cullBackFaces = true;
  58023. scene._mirroredCameraPosition = null;
  58024. delete scene.clipPlane;
  58025. });
  58026. return _this;
  58027. }
  58028. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58029. get: function () {
  58030. return this._blurRatio;
  58031. },
  58032. set: function (value) {
  58033. if (this._blurRatio === value) {
  58034. return;
  58035. }
  58036. this._blurRatio = value;
  58037. this._preparePostProcesses();
  58038. },
  58039. enumerable: true,
  58040. configurable: true
  58041. });
  58042. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58043. set: function (value) {
  58044. this._adaptiveBlurKernel = value;
  58045. this._autoComputeBlurKernel();
  58046. },
  58047. enumerable: true,
  58048. configurable: true
  58049. });
  58050. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58051. set: function (value) {
  58052. this.blurKernelX = value;
  58053. this.blurKernelY = value;
  58054. },
  58055. enumerable: true,
  58056. configurable: true
  58057. });
  58058. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58059. get: function () {
  58060. return this._blurKernelX;
  58061. },
  58062. set: function (value) {
  58063. if (this._blurKernelX === value) {
  58064. return;
  58065. }
  58066. this._blurKernelX = value;
  58067. this._preparePostProcesses();
  58068. },
  58069. enumerable: true,
  58070. configurable: true
  58071. });
  58072. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58073. get: function () {
  58074. return this._blurKernelY;
  58075. },
  58076. set: function (value) {
  58077. if (this._blurKernelY === value) {
  58078. return;
  58079. }
  58080. this._blurKernelY = value;
  58081. this._preparePostProcesses();
  58082. },
  58083. enumerable: true,
  58084. configurable: true
  58085. });
  58086. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58087. var engine = this.getScene().getEngine();
  58088. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58089. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58090. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58091. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58092. };
  58093. MirrorTexture.prototype._onRatioRescale = function () {
  58094. if (this._sizeRatio) {
  58095. this.resize(this._initialSizeParameter);
  58096. if (!this._adaptiveBlurKernel) {
  58097. this._preparePostProcesses();
  58098. }
  58099. }
  58100. if (this._adaptiveBlurKernel) {
  58101. this._autoComputeBlurKernel();
  58102. }
  58103. };
  58104. MirrorTexture.prototype._preparePostProcesses = function () {
  58105. this.clearPostProcesses(true);
  58106. if (this._blurKernelX && this._blurKernelY) {
  58107. var engine = this.getScene().getEngine();
  58108. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58109. 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);
  58110. this._blurX.autoClear = false;
  58111. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58112. this._blurX.inputTexture = this._texture;
  58113. }
  58114. else {
  58115. this._blurX.alwaysForcePOT = true;
  58116. }
  58117. 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);
  58118. this._blurY.autoClear = false;
  58119. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58120. this.addPostProcess(this._blurX);
  58121. this.addPostProcess(this._blurY);
  58122. }
  58123. else {
  58124. if (this._blurY) {
  58125. this.removePostProcess(this._blurY);
  58126. this._blurY.dispose();
  58127. this._blurY = null;
  58128. }
  58129. if (this._blurX) {
  58130. this.removePostProcess(this._blurX);
  58131. this._blurX.dispose();
  58132. this._blurX = null;
  58133. }
  58134. }
  58135. };
  58136. MirrorTexture.prototype.clone = function () {
  58137. var scene = this.getScene();
  58138. if (!scene) {
  58139. return this;
  58140. }
  58141. var textureSize = this.getSize();
  58142. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58143. // Base texture
  58144. newTexture.hasAlpha = this.hasAlpha;
  58145. newTexture.level = this.level;
  58146. // Mirror Texture
  58147. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58148. if (this.renderList) {
  58149. newTexture.renderList = this.renderList.slice(0);
  58150. }
  58151. return newTexture;
  58152. };
  58153. MirrorTexture.prototype.serialize = function () {
  58154. if (!this.name) {
  58155. return null;
  58156. }
  58157. var serializationObject = _super.prototype.serialize.call(this);
  58158. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58159. return serializationObject;
  58160. };
  58161. return MirrorTexture;
  58162. }(BABYLON.RenderTargetTexture));
  58163. BABYLON.MirrorTexture = MirrorTexture;
  58164. })(BABYLON || (BABYLON = {}));
  58165. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58166. var BABYLON;
  58167. (function (BABYLON) {
  58168. /**
  58169. * Creates a refraction texture used by refraction channel of the standard material.
  58170. * @param name the texture name
  58171. * @param size size of the underlying texture
  58172. * @param scene root scene
  58173. */
  58174. var RefractionTexture = /** @class */ (function (_super) {
  58175. __extends(RefractionTexture, _super);
  58176. function RefractionTexture(name, size, scene, generateMipMaps) {
  58177. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58178. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58179. _this.depth = 2.0;
  58180. _this.onBeforeRenderObservable.add(function () {
  58181. scene.clipPlane = _this.refractionPlane;
  58182. });
  58183. _this.onAfterRenderObservable.add(function () {
  58184. delete scene.clipPlane;
  58185. });
  58186. return _this;
  58187. }
  58188. RefractionTexture.prototype.clone = function () {
  58189. var scene = this.getScene();
  58190. if (!scene) {
  58191. return this;
  58192. }
  58193. var textureSize = this.getSize();
  58194. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58195. // Base texture
  58196. newTexture.hasAlpha = this.hasAlpha;
  58197. newTexture.level = this.level;
  58198. // Refraction Texture
  58199. newTexture.refractionPlane = this.refractionPlane.clone();
  58200. if (this.renderList) {
  58201. newTexture.renderList = this.renderList.slice(0);
  58202. }
  58203. newTexture.depth = this.depth;
  58204. return newTexture;
  58205. };
  58206. RefractionTexture.prototype.serialize = function () {
  58207. if (!this.name) {
  58208. return null;
  58209. }
  58210. var serializationObject = _super.prototype.serialize.call(this);
  58211. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58212. serializationObject.depth = this.depth;
  58213. return serializationObject;
  58214. };
  58215. return RefractionTexture;
  58216. }(BABYLON.RenderTargetTexture));
  58217. BABYLON.RefractionTexture = RefractionTexture;
  58218. })(BABYLON || (BABYLON = {}));
  58219. //# sourceMappingURL=babylon.refractionTexture.js.map
  58220. var BABYLON;
  58221. (function (BABYLON) {
  58222. var DynamicTexture = /** @class */ (function (_super) {
  58223. __extends(DynamicTexture, _super);
  58224. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58225. if (scene === void 0) { scene = null; }
  58226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58227. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58228. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58229. _this.name = name;
  58230. _this._engine = _this.getScene().getEngine();
  58231. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58232. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58233. _this._generateMipMaps = generateMipMaps;
  58234. if (options.getContext) {
  58235. _this._canvas = options;
  58236. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58237. }
  58238. else {
  58239. _this._canvas = document.createElement("canvas");
  58240. if (options.width) {
  58241. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58242. }
  58243. else {
  58244. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58245. }
  58246. }
  58247. var textureSize = _this.getSize();
  58248. _this._canvas.width = textureSize.width;
  58249. _this._canvas.height = textureSize.height;
  58250. _this._context = _this._canvas.getContext("2d");
  58251. return _this;
  58252. }
  58253. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58254. get: function () {
  58255. return true;
  58256. },
  58257. enumerable: true,
  58258. configurable: true
  58259. });
  58260. DynamicTexture.prototype._recreate = function (textureSize) {
  58261. this._canvas.width = textureSize.width;
  58262. this._canvas.height = textureSize.height;
  58263. this.releaseInternalTexture();
  58264. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58265. };
  58266. DynamicTexture.prototype.scale = function (ratio) {
  58267. var textureSize = this.getSize();
  58268. textureSize.width *= ratio;
  58269. textureSize.height *= ratio;
  58270. this._recreate(textureSize);
  58271. };
  58272. DynamicTexture.prototype.scaleTo = function (width, height) {
  58273. var textureSize = this.getSize();
  58274. textureSize.width = width;
  58275. textureSize.height = height;
  58276. this._recreate(textureSize);
  58277. };
  58278. DynamicTexture.prototype.getContext = function () {
  58279. return this._context;
  58280. };
  58281. DynamicTexture.prototype.clear = function () {
  58282. var size = this.getSize();
  58283. this._context.fillRect(0, 0, size.width, size.height);
  58284. };
  58285. DynamicTexture.prototype.update = function (invertY) {
  58286. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58287. };
  58288. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58289. if (update === void 0) { update = true; }
  58290. var size = this.getSize();
  58291. if (clearColor) {
  58292. this._context.fillStyle = clearColor;
  58293. this._context.fillRect(0, 0, size.width, size.height);
  58294. }
  58295. this._context.font = font;
  58296. if (x === null || x === undefined) {
  58297. var textSize = this._context.measureText(text);
  58298. x = (size.width - textSize.width) / 2;
  58299. }
  58300. if (y === null || y === undefined) {
  58301. var fontSize = parseInt((font.replace(/\D/g, '')));
  58302. ;
  58303. y = (size.height / 2) + (fontSize / 3.65);
  58304. }
  58305. this._context.fillStyle = color;
  58306. this._context.fillText(text, x, y);
  58307. if (update) {
  58308. this.update(invertY);
  58309. }
  58310. };
  58311. DynamicTexture.prototype.clone = function () {
  58312. var scene = this.getScene();
  58313. if (!scene) {
  58314. return this;
  58315. }
  58316. var textureSize = this.getSize();
  58317. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58318. // Base texture
  58319. newTexture.hasAlpha = this.hasAlpha;
  58320. newTexture.level = this.level;
  58321. // Dynamic Texture
  58322. newTexture.wrapU = this.wrapU;
  58323. newTexture.wrapV = this.wrapV;
  58324. return newTexture;
  58325. };
  58326. DynamicTexture.prototype._rebuild = function () {
  58327. this.update();
  58328. };
  58329. return DynamicTexture;
  58330. }(BABYLON.Texture));
  58331. BABYLON.DynamicTexture = DynamicTexture;
  58332. })(BABYLON || (BABYLON = {}));
  58333. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58334. var BABYLON;
  58335. (function (BABYLON) {
  58336. var VideoTexture = /** @class */ (function (_super) {
  58337. __extends(VideoTexture, _super);
  58338. /**
  58339. * Creates a video texture.
  58340. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58341. * @param {string | null} name optional name, will detect from video source, if not defined
  58342. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58343. * @param {BABYLON.Scene} scene is obviously the current scene.
  58344. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58345. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58346. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58347. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58348. */
  58349. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58350. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58351. if (invertY === void 0) { invertY = false; }
  58352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58353. if (settings === void 0) { settings = {
  58354. autoPlay: true,
  58355. loop: true,
  58356. autoUpdateTexture: true,
  58357. }; }
  58358. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58359. _this._createInternalTexture = function () {
  58360. if (_this._texture != null) {
  58361. return;
  58362. }
  58363. if (!_this._engine.needPOTTextures ||
  58364. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58365. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58366. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58367. }
  58368. else {
  58369. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58370. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58371. _this._generateMipMaps = false;
  58372. }
  58373. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58374. _this._texture.isReady = true;
  58375. _this._updateInternalTexture();
  58376. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  58377. _this.onLoadObservable.notifyObservers(_this);
  58378. }
  58379. };
  58380. _this.reset = function () {
  58381. if (_this._texture == null) {
  58382. return;
  58383. }
  58384. _this._texture.dispose();
  58385. _this._texture = null;
  58386. };
  58387. _this._updateInternalTexture = function (e) {
  58388. if (_this._texture == null || !_this._texture.isReady) {
  58389. return;
  58390. }
  58391. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58392. return;
  58393. }
  58394. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58395. };
  58396. _this._engine = _this.getScene().getEngine();
  58397. _this._generateMipMaps = generateMipMaps;
  58398. _this._samplingMode = samplingMode;
  58399. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58400. _this.name = name || _this._getName(src);
  58401. _this.video = _this._getVideo(src);
  58402. if (settings.autoPlay !== undefined) {
  58403. _this.video.autoplay = settings.autoPlay;
  58404. }
  58405. if (settings.loop !== undefined) {
  58406. _this.video.loop = settings.loop;
  58407. }
  58408. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58409. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58410. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58411. _this.video.addEventListener("emptied", _this.reset);
  58412. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58413. _this._createInternalTexture();
  58414. }
  58415. return _this;
  58416. }
  58417. VideoTexture.prototype._getName = function (src) {
  58418. if (src instanceof HTMLVideoElement) {
  58419. return src.currentSrc;
  58420. }
  58421. if (typeof src === "object") {
  58422. return src.toString();
  58423. }
  58424. return src;
  58425. };
  58426. ;
  58427. VideoTexture.prototype._getVideo = function (src) {
  58428. if (src instanceof HTMLVideoElement) {
  58429. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58430. return src;
  58431. }
  58432. var video = document.createElement("video");
  58433. if (typeof src === "string") {
  58434. BABYLON.Tools.SetCorsBehavior(src, video);
  58435. video.src = src;
  58436. }
  58437. else {
  58438. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58439. src.forEach(function (url) {
  58440. var source = document.createElement("source");
  58441. source.src = url;
  58442. video.appendChild(source);
  58443. });
  58444. }
  58445. return video;
  58446. };
  58447. ;
  58448. /**
  58449. * Internal method to initiate `update`.
  58450. */
  58451. VideoTexture.prototype._rebuild = function () {
  58452. this.update();
  58453. };
  58454. /**
  58455. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58456. */
  58457. VideoTexture.prototype.update = function () {
  58458. if (!this.autoUpdateTexture) {
  58459. // Expecting user to call `updateTexture` manually
  58460. return;
  58461. }
  58462. this.updateTexture(true);
  58463. };
  58464. /**
  58465. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58466. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58467. */
  58468. VideoTexture.prototype.updateTexture = function (isVisible) {
  58469. if (!isVisible) {
  58470. return;
  58471. }
  58472. if (this.video.paused) {
  58473. return;
  58474. }
  58475. this._updateInternalTexture();
  58476. };
  58477. /**
  58478. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58479. * @param url New url.
  58480. */
  58481. VideoTexture.prototype.updateURL = function (url) {
  58482. this.video.src = url;
  58483. };
  58484. VideoTexture.prototype.dispose = function () {
  58485. _super.prototype.dispose.call(this);
  58486. this.video.removeEventListener("canplay", this._createInternalTexture);
  58487. this.video.removeEventListener("paused", this._updateInternalTexture);
  58488. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58489. this.video.removeEventListener("emptied", this.reset);
  58490. this.video.pause();
  58491. };
  58492. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58493. var video = document.createElement("video");
  58494. var constraintsDeviceId;
  58495. if (constraints && constraints.deviceId) {
  58496. constraintsDeviceId = {
  58497. exact: constraints.deviceId,
  58498. };
  58499. }
  58500. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58501. if (navigator.mediaDevices) {
  58502. navigator.mediaDevices.getUserMedia({ video: constraints })
  58503. .then(function (stream) {
  58504. if (video.mozSrcObject !== undefined) {
  58505. // hack for Firefox < 19
  58506. video.mozSrcObject = stream;
  58507. }
  58508. else {
  58509. video.srcObject = stream;
  58510. }
  58511. var onPlaying = function () {
  58512. if (onReady) {
  58513. onReady(new VideoTexture("video", video, scene, true, true));
  58514. }
  58515. video.removeEventListener("playing", onPlaying);
  58516. };
  58517. video.addEventListener("playing", onPlaying);
  58518. video.play();
  58519. })
  58520. .catch(function (err) {
  58521. BABYLON.Tools.Error(err.name);
  58522. });
  58523. }
  58524. else {
  58525. navigator.getUserMedia =
  58526. navigator.getUserMedia ||
  58527. navigator.webkitGetUserMedia ||
  58528. navigator.mozGetUserMedia ||
  58529. navigator.msGetUserMedia;
  58530. if (navigator.getUserMedia) {
  58531. navigator.getUserMedia({
  58532. video: {
  58533. deviceId: constraintsDeviceId,
  58534. width: {
  58535. min: (constraints && constraints.minWidth) || 256,
  58536. max: (constraints && constraints.maxWidth) || 640,
  58537. },
  58538. height: {
  58539. min: (constraints && constraints.minHeight) || 256,
  58540. max: (constraints && constraints.maxHeight) || 480,
  58541. },
  58542. },
  58543. }, function (stream) {
  58544. if (video.mozSrcObject !== undefined) {
  58545. // hack for Firefox < 19
  58546. video.mozSrcObject = stream;
  58547. }
  58548. else {
  58549. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58550. }
  58551. video.play();
  58552. if (onReady) {
  58553. onReady(new VideoTexture("video", video, scene, true, true));
  58554. }
  58555. }, function (e) {
  58556. BABYLON.Tools.Error(e.name);
  58557. });
  58558. }
  58559. }
  58560. };
  58561. return VideoTexture;
  58562. }(BABYLON.Texture));
  58563. BABYLON.VideoTexture = VideoTexture;
  58564. })(BABYLON || (BABYLON = {}));
  58565. //# sourceMappingURL=babylon.videoTexture.js.map
  58566. var BABYLON;
  58567. (function (BABYLON) {
  58568. var RawTexture = /** @class */ (function (_super) {
  58569. __extends(RawTexture, _super);
  58570. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58572. if (invertY === void 0) { invertY = false; }
  58573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58574. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58575. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58576. _this.format = format;
  58577. _this._engine = scene.getEngine();
  58578. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58579. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58580. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58581. return _this;
  58582. }
  58583. RawTexture.prototype.update = function (data) {
  58584. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58585. };
  58586. // Statics
  58587. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58588. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58589. if (invertY === void 0) { invertY = false; }
  58590. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58591. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58592. };
  58593. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58594. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58595. if (invertY === void 0) { invertY = false; }
  58596. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58597. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58598. };
  58599. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58600. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58601. if (invertY === void 0) { invertY = false; }
  58602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58603. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58604. };
  58605. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58606. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58607. if (invertY === void 0) { invertY = false; }
  58608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58609. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58610. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58611. };
  58612. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58614. if (invertY === void 0) { invertY = false; }
  58615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58616. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58617. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58618. };
  58619. return RawTexture;
  58620. }(BABYLON.Texture));
  58621. BABYLON.RawTexture = RawTexture;
  58622. })(BABYLON || (BABYLON = {}));
  58623. //# sourceMappingURL=babylon.rawTexture.js.map
  58624. var BABYLON;
  58625. (function (BABYLON) {
  58626. /**
  58627. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58628. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58629. */
  58630. var PostProcess = /** @class */ (function () {
  58631. /**
  58632. * Creates a new instance of @see PostProcess
  58633. * @param name The name of the PostProcess.
  58634. * @param fragmentUrl The url of the fragment shader to be used.
  58635. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58636. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58637. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58638. * @param camera The camera to apply the render pass to.
  58639. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58640. * @param engine The engine which the post process will be applied. (default: current engine)
  58641. * @param reusable If the post process can be reused on the same frame. (default: false)
  58642. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58643. * @param textureType Type of textures used when performing the post process. (default: 0)
  58644. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58645. * @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
  58646. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58647. */
  58648. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58650. if (defines === void 0) { defines = null; }
  58651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58652. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58653. if (blockCompilation === void 0) { blockCompilation = false; }
  58654. this.name = name;
  58655. /**
  58656. * Width of the texture to apply the post process on
  58657. */
  58658. this.width = -1;
  58659. /**
  58660. * Height of the texture to apply the post process on
  58661. */
  58662. this.height = -1;
  58663. /**
  58664. * If the buffer needs to be cleared before applying the post process. (default: true)
  58665. * Should be set to false if shader will overwrite all previous pixels.
  58666. */
  58667. this.autoClear = true;
  58668. /**
  58669. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58670. */
  58671. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58672. /**
  58673. * Animations to be used for the post processing
  58674. */
  58675. this.animations = new Array();
  58676. /**
  58677. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58678. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58679. */
  58680. this.enablePixelPerfectMode = false;
  58681. /**
  58682. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58683. */
  58684. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58685. /**
  58686. * Force textures to be a power of two (default: false)
  58687. */
  58688. this.alwaysForcePOT = false;
  58689. /**
  58690. * Number of sample textures (default: 1)
  58691. */
  58692. this.samples = 1;
  58693. /**
  58694. * Modify the scale of the post process to be the same as the viewport (default: false)
  58695. */
  58696. this.adaptScaleToCurrentViewport = false;
  58697. this._reusable = false;
  58698. /**
  58699. * Smart array of input and output textures for the post process.
  58700. */
  58701. this._textures = new BABYLON.SmartArray(2);
  58702. /**
  58703. * The index in _textures that corresponds to the output texture.
  58704. */
  58705. this._currentRenderTextureInd = 0;
  58706. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58707. this._texelSize = BABYLON.Vector2.Zero();
  58708. // Events
  58709. /**
  58710. * An event triggered when the postprocess is activated.
  58711. * @type {BABYLON.Observable}
  58712. */
  58713. this.onActivateObservable = new BABYLON.Observable();
  58714. /**
  58715. * An event triggered when the postprocess changes its size.
  58716. * @type {BABYLON.Observable}
  58717. */
  58718. this.onSizeChangedObservable = new BABYLON.Observable();
  58719. /**
  58720. * An event triggered when the postprocess applies its effect.
  58721. * @type {BABYLON.Observable}
  58722. */
  58723. this.onApplyObservable = new BABYLON.Observable();
  58724. /**
  58725. * An event triggered before rendering the postprocess
  58726. * @type {BABYLON.Observable}
  58727. */
  58728. this.onBeforeRenderObservable = new BABYLON.Observable();
  58729. /**
  58730. * An event triggered after rendering the postprocess
  58731. * @type {BABYLON.Observable}
  58732. */
  58733. this.onAfterRenderObservable = new BABYLON.Observable();
  58734. if (camera != null) {
  58735. this._camera = camera;
  58736. this._scene = camera.getScene();
  58737. camera.attachPostProcess(this);
  58738. this._engine = this._scene.getEngine();
  58739. this._scene.postProcesses.push(this);
  58740. }
  58741. else if (engine) {
  58742. this._engine = engine;
  58743. this._engine.postProcesses.push(this);
  58744. }
  58745. this._options = options;
  58746. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58747. this._reusable = reusable || false;
  58748. this._textureType = textureType;
  58749. this._samplers = samplers || [];
  58750. this._samplers.push("textureSampler");
  58751. this._fragmentUrl = fragmentUrl;
  58752. this._vertexUrl = vertexUrl;
  58753. this._parameters = parameters || [];
  58754. this._parameters.push("scale");
  58755. this._indexParameters = indexParameters;
  58756. if (!blockCompilation) {
  58757. this.updateEffect(defines);
  58758. }
  58759. }
  58760. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58761. /**
  58762. * A function that is added to the onActivateObservable
  58763. */
  58764. set: function (callback) {
  58765. if (this._onActivateObserver) {
  58766. this.onActivateObservable.remove(this._onActivateObserver);
  58767. }
  58768. if (callback) {
  58769. this._onActivateObserver = this.onActivateObservable.add(callback);
  58770. }
  58771. },
  58772. enumerable: true,
  58773. configurable: true
  58774. });
  58775. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58776. /**
  58777. * A function that is added to the onSizeChangedObservable
  58778. */
  58779. set: function (callback) {
  58780. if (this._onSizeChangedObserver) {
  58781. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58782. }
  58783. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58784. },
  58785. enumerable: true,
  58786. configurable: true
  58787. });
  58788. Object.defineProperty(PostProcess.prototype, "onApply", {
  58789. /**
  58790. * A function that is added to the onApplyObservable
  58791. */
  58792. set: function (callback) {
  58793. if (this._onApplyObserver) {
  58794. this.onApplyObservable.remove(this._onApplyObserver);
  58795. }
  58796. this._onApplyObserver = this.onApplyObservable.add(callback);
  58797. },
  58798. enumerable: true,
  58799. configurable: true
  58800. });
  58801. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58802. /**
  58803. * A function that is added to the onBeforeRenderObservable
  58804. */
  58805. set: function (callback) {
  58806. if (this._onBeforeRenderObserver) {
  58807. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58808. }
  58809. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58810. },
  58811. enumerable: true,
  58812. configurable: true
  58813. });
  58814. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58815. /**
  58816. * A function that is added to the onAfterRenderObservable
  58817. */
  58818. set: function (callback) {
  58819. if (this._onAfterRenderObserver) {
  58820. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58821. }
  58822. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58823. },
  58824. enumerable: true,
  58825. configurable: true
  58826. });
  58827. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58828. /**
  58829. * 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
  58830. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58831. */
  58832. get: function () {
  58833. return this._textures.data[this._currentRenderTextureInd];
  58834. },
  58835. set: function (value) {
  58836. this._forcedOutputTexture = value;
  58837. },
  58838. enumerable: true,
  58839. configurable: true
  58840. });
  58841. /**
  58842. * Gets the camera which post process is applied to.
  58843. * @returns The camera the post process is applied to.
  58844. */
  58845. PostProcess.prototype.getCamera = function () {
  58846. return this._camera;
  58847. };
  58848. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58849. /**
  58850. * Gets the texel size of the postprocess.
  58851. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58852. */
  58853. get: function () {
  58854. if (this._shareOutputWithPostProcess) {
  58855. return this._shareOutputWithPostProcess.texelSize;
  58856. }
  58857. if (this._forcedOutputTexture) {
  58858. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58859. }
  58860. return this._texelSize;
  58861. },
  58862. enumerable: true,
  58863. configurable: true
  58864. });
  58865. /**
  58866. * Gets the engine which this post process belongs to.
  58867. * @returns The engine the post process was enabled with.
  58868. */
  58869. PostProcess.prototype.getEngine = function () {
  58870. return this._engine;
  58871. };
  58872. /**
  58873. * The effect that is created when initializing the post process.
  58874. * @returns The created effect corrisponding the the postprocess.
  58875. */
  58876. PostProcess.prototype.getEffect = function () {
  58877. return this._effect;
  58878. };
  58879. /**
  58880. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58881. * @param postProcess The post process to share the output with.
  58882. * @returns This post process.
  58883. */
  58884. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58885. this._disposeTextures();
  58886. this._shareOutputWithPostProcess = postProcess;
  58887. return this;
  58888. };
  58889. /**
  58890. * Updates the effect with the current post process compile time values and recompiles the shader.
  58891. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58892. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58893. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58894. * @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
  58895. * @param onCompiled Called when the shader has been compiled.
  58896. * @param onError Called if there is an error when compiling a shader.
  58897. */
  58898. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58899. if (defines === void 0) { defines = null; }
  58900. if (uniforms === void 0) { uniforms = null; }
  58901. if (samplers === void 0) { samplers = null; }
  58902. 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);
  58903. };
  58904. /**
  58905. * The post process is reusable if it can be used multiple times within one frame.
  58906. * @returns If the post process is reusable
  58907. */
  58908. PostProcess.prototype.isReusable = function () {
  58909. return this._reusable;
  58910. };
  58911. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58912. PostProcess.prototype.markTextureDirty = function () {
  58913. this.width = -1;
  58914. };
  58915. /**
  58916. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58917. * 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.
  58918. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58919. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58920. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58921. */
  58922. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58923. var _this = this;
  58924. if (sourceTexture === void 0) { sourceTexture = null; }
  58925. camera = camera || this._camera;
  58926. var scene = camera.getScene();
  58927. var engine = scene.getEngine();
  58928. var maxSize = engine.getCaps().maxTextureSize;
  58929. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58930. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58931. // 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
  58932. var webVRCamera = camera.parent;
  58933. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  58934. requiredWidth /= 2;
  58935. }
  58936. var desiredWidth = (this._options.width || requiredWidth);
  58937. var desiredHeight = this._options.height || requiredHeight;
  58938. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58939. if (this.adaptScaleToCurrentViewport) {
  58940. var currentViewport = engine.currentViewport;
  58941. if (currentViewport) {
  58942. desiredWidth *= currentViewport.width;
  58943. desiredHeight *= currentViewport.height;
  58944. }
  58945. }
  58946. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58947. if (!this._options.width) {
  58948. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58949. }
  58950. if (!this._options.height) {
  58951. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58952. }
  58953. }
  58954. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58955. if (this._textures.length > 0) {
  58956. for (var i = 0; i < this._textures.length; i++) {
  58957. this._engine._releaseTexture(this._textures.data[i]);
  58958. }
  58959. this._textures.reset();
  58960. }
  58961. this.width = desiredWidth;
  58962. this.height = desiredHeight;
  58963. var textureSize = { width: this.width, height: this.height };
  58964. var textureOptions = {
  58965. generateMipMaps: false,
  58966. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58967. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58968. samplingMode: this.renderTargetSamplingMode,
  58969. type: this._textureType
  58970. };
  58971. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58972. if (this._reusable) {
  58973. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58974. }
  58975. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58976. this.onSizeChangedObservable.notifyObservers(this);
  58977. }
  58978. this._textures.forEach(function (texture) {
  58979. if (texture.samples !== _this.samples) {
  58980. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58981. }
  58982. });
  58983. }
  58984. var target;
  58985. if (this._shareOutputWithPostProcess) {
  58986. target = this._shareOutputWithPostProcess.inputTexture;
  58987. }
  58988. else if (this._forcedOutputTexture) {
  58989. target = this._forcedOutputTexture;
  58990. this.width = this._forcedOutputTexture.width;
  58991. this.height = this._forcedOutputTexture.height;
  58992. }
  58993. else {
  58994. target = this.inputTexture;
  58995. }
  58996. // Bind the input of this post process to be used as the output of the previous post process.
  58997. if (this.enablePixelPerfectMode) {
  58998. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58999. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59000. }
  59001. else {
  59002. this._scaleRatio.copyFromFloats(1, 1);
  59003. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59004. }
  59005. this.onActivateObservable.notifyObservers(camera);
  59006. // Clear
  59007. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59008. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59009. }
  59010. if (this._reusable) {
  59011. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59012. }
  59013. };
  59014. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59015. /**
  59016. * If the post process is supported.
  59017. */
  59018. get: function () {
  59019. return this._effect.isSupported;
  59020. },
  59021. enumerable: true,
  59022. configurable: true
  59023. });
  59024. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59025. /**
  59026. * The aspect ratio of the output texture.
  59027. */
  59028. get: function () {
  59029. if (this._shareOutputWithPostProcess) {
  59030. return this._shareOutputWithPostProcess.aspectRatio;
  59031. }
  59032. if (this._forcedOutputTexture) {
  59033. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59034. }
  59035. return this.width / this.height;
  59036. },
  59037. enumerable: true,
  59038. configurable: true
  59039. });
  59040. /**
  59041. * Get a value indicating if the post-process is ready to be used
  59042. * @returns true if the post-process is ready (shader is compiled)
  59043. */
  59044. PostProcess.prototype.isReady = function () {
  59045. return this._effect && this._effect.isReady();
  59046. };
  59047. /**
  59048. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59049. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59050. */
  59051. PostProcess.prototype.apply = function () {
  59052. // Check
  59053. if (!this._effect || !this._effect.isReady())
  59054. return null;
  59055. // States
  59056. this._engine.enableEffect(this._effect);
  59057. this._engine.setState(false);
  59058. this._engine.setDepthBuffer(false);
  59059. this._engine.setDepthWrite(false);
  59060. // Alpha
  59061. this._engine.setAlphaMode(this.alphaMode);
  59062. if (this.alphaConstants) {
  59063. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59064. }
  59065. // Bind the output texture of the preivous post process as the input to this post process.
  59066. var source;
  59067. if (this._shareOutputWithPostProcess) {
  59068. source = this._shareOutputWithPostProcess.inputTexture;
  59069. }
  59070. else if (this._forcedOutputTexture) {
  59071. source = this._forcedOutputTexture;
  59072. }
  59073. else {
  59074. source = this.inputTexture;
  59075. }
  59076. this._effect._bindTexture("textureSampler", source);
  59077. // Parameters
  59078. this._effect.setVector2("scale", this._scaleRatio);
  59079. this.onApplyObservable.notifyObservers(this._effect);
  59080. return this._effect;
  59081. };
  59082. PostProcess.prototype._disposeTextures = function () {
  59083. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59084. return;
  59085. }
  59086. if (this._textures.length > 0) {
  59087. for (var i = 0; i < this._textures.length; i++) {
  59088. this._engine._releaseTexture(this._textures.data[i]);
  59089. }
  59090. }
  59091. this._textures.dispose();
  59092. };
  59093. /**
  59094. * Disposes the post process.
  59095. * @param camera The camera to dispose the post process on.
  59096. */
  59097. PostProcess.prototype.dispose = function (camera) {
  59098. camera = camera || this._camera;
  59099. this._disposeTextures();
  59100. if (this._scene) {
  59101. var index_1 = this._scene.postProcesses.indexOf(this);
  59102. if (index_1 !== -1) {
  59103. this._scene.postProcesses.splice(index_1, 1);
  59104. }
  59105. }
  59106. else {
  59107. var index_2 = this._engine.postProcesses.indexOf(this);
  59108. if (index_2 !== -1) {
  59109. this._engine.postProcesses.splice(index_2, 1);
  59110. }
  59111. }
  59112. if (!camera) {
  59113. return;
  59114. }
  59115. camera.detachPostProcess(this);
  59116. var index = camera._postProcesses.indexOf(this);
  59117. if (index === 0 && camera._postProcesses.length > 0) {
  59118. this._camera._postProcesses[0].markTextureDirty();
  59119. }
  59120. this.onActivateObservable.clear();
  59121. this.onAfterRenderObservable.clear();
  59122. this.onApplyObservable.clear();
  59123. this.onBeforeRenderObservable.clear();
  59124. this.onSizeChangedObservable.clear();
  59125. };
  59126. return PostProcess;
  59127. }());
  59128. BABYLON.PostProcess = PostProcess;
  59129. })(BABYLON || (BABYLON = {}));
  59130. //# sourceMappingURL=babylon.postProcess.js.map
  59131. var BABYLON;
  59132. (function (BABYLON) {
  59133. var PassPostProcess = /** @class */ (function (_super) {
  59134. __extends(PassPostProcess, _super);
  59135. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59136. if (camera === void 0) { camera = null; }
  59137. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59138. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59139. }
  59140. return PassPostProcess;
  59141. }(BABYLON.PostProcess));
  59142. BABYLON.PassPostProcess = PassPostProcess;
  59143. })(BABYLON || (BABYLON = {}));
  59144. //# sourceMappingURL=babylon.passPostProcess.js.map
  59145. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59146. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59147. s = arguments[i];
  59148. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59149. t[p] = s[p];
  59150. }
  59151. return t;
  59152. };
  59153. var BABYLON;
  59154. (function (BABYLON) {
  59155. /**
  59156. * Default implementation of @see IShadowGenerator.
  59157. * This is the main object responsible of generating shadows in the framework.
  59158. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59159. */
  59160. var ShadowGenerator = /** @class */ (function () {
  59161. /**
  59162. * Creates a ShadowGenerator object.
  59163. * A ShadowGenerator is the required tool to use the shadows.
  59164. * Each light casting shadows needs to use its own ShadowGenerator.
  59165. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59166. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59167. * @param light The light object generating the shadows.
  59168. * @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.
  59169. */
  59170. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59171. this._bias = 0.00005;
  59172. this._blurBoxOffset = 1;
  59173. this._blurScale = 2;
  59174. this._blurKernel = 1;
  59175. this._useKernelBlur = false;
  59176. this._filter = ShadowGenerator.FILTER_NONE;
  59177. this._darkness = 0;
  59178. this._transparencyShadow = false;
  59179. /**
  59180. * Controls the extent to which the shadows fade out at the edge of the frustum
  59181. * Used only by directionals and spots
  59182. */
  59183. this.frustumEdgeFalloff = 0;
  59184. /**
  59185. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59186. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59187. * It might on the other hand introduce peter panning.
  59188. */
  59189. this.forceBackFacesOnly = false;
  59190. this._lightDirection = BABYLON.Vector3.Zero();
  59191. this._viewMatrix = BABYLON.Matrix.Zero();
  59192. this._projectionMatrix = BABYLON.Matrix.Zero();
  59193. this._transformMatrix = BABYLON.Matrix.Zero();
  59194. this._currentFaceIndex = 0;
  59195. this._currentFaceIndexCache = 0;
  59196. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59197. this._mapSize = mapSize;
  59198. this._light = light;
  59199. this._scene = light.getScene();
  59200. light._shadowGenerator = this;
  59201. // Texture type fallback from float to int if not supported.
  59202. var caps = this._scene.getEngine().getCaps();
  59203. if (!useFullFloatFirst) {
  59204. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59205. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59206. }
  59207. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59208. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59209. }
  59210. else {
  59211. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59212. }
  59213. }
  59214. else {
  59215. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59216. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59217. }
  59218. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59219. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59220. }
  59221. else {
  59222. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59223. }
  59224. }
  59225. this._initializeGenerator();
  59226. }
  59227. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59228. /**
  59229. * Shadow generator mode None: no filtering applied.
  59230. */
  59231. get: function () {
  59232. return ShadowGenerator._FILTER_NONE;
  59233. },
  59234. enumerable: true,
  59235. configurable: true
  59236. });
  59237. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59238. /**
  59239. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59240. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59241. */
  59242. get: function () {
  59243. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59244. },
  59245. enumerable: true,
  59246. configurable: true
  59247. });
  59248. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59249. /**
  59250. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59251. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59252. */
  59253. get: function () {
  59254. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59255. },
  59256. enumerable: true,
  59257. configurable: true
  59258. });
  59259. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59260. /**
  59261. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59262. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59263. */
  59264. get: function () {
  59265. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59266. },
  59267. enumerable: true,
  59268. configurable: true
  59269. });
  59270. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59271. /**
  59272. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59273. * edge artifacts on steep falloff.
  59274. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59275. */
  59276. get: function () {
  59277. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59278. },
  59279. enumerable: true,
  59280. configurable: true
  59281. });
  59282. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59283. /**
  59284. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59285. * edge artifacts on steep falloff.
  59286. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59287. */
  59288. get: function () {
  59289. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59290. },
  59291. enumerable: true,
  59292. configurable: true
  59293. });
  59294. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59295. /**
  59296. * Gets the bias: offset applied on the depth preventing acnea.
  59297. */
  59298. get: function () {
  59299. return this._bias;
  59300. },
  59301. /**
  59302. * Sets the bias: offset applied on the depth preventing acnea.
  59303. */
  59304. set: function (bias) {
  59305. this._bias = bias;
  59306. },
  59307. enumerable: true,
  59308. configurable: true
  59309. });
  59310. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59311. /**
  59312. * Gets the blur box offset: offset applied during the blur pass.
  59313. * Only usefull if useKernelBlur = false
  59314. */
  59315. get: function () {
  59316. return this._blurBoxOffset;
  59317. },
  59318. /**
  59319. * Sets the blur box offset: offset applied during the blur pass.
  59320. * Only usefull if useKernelBlur = false
  59321. */
  59322. set: function (value) {
  59323. if (this._blurBoxOffset === value) {
  59324. return;
  59325. }
  59326. this._blurBoxOffset = value;
  59327. this._disposeBlurPostProcesses();
  59328. },
  59329. enumerable: true,
  59330. configurable: true
  59331. });
  59332. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59333. /**
  59334. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59335. * 2 means half of the size.
  59336. */
  59337. get: function () {
  59338. return this._blurScale;
  59339. },
  59340. /**
  59341. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59342. * 2 means half of the size.
  59343. */
  59344. set: function (value) {
  59345. if (this._blurScale === value) {
  59346. return;
  59347. }
  59348. this._blurScale = value;
  59349. this._disposeBlurPostProcesses();
  59350. },
  59351. enumerable: true,
  59352. configurable: true
  59353. });
  59354. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59355. /**
  59356. * Gets the blur kernel: kernel size of the blur pass.
  59357. * Only usefull if useKernelBlur = true
  59358. */
  59359. get: function () {
  59360. return this._blurKernel;
  59361. },
  59362. /**
  59363. * Sets the blur kernel: kernel size of the blur pass.
  59364. * Only usefull if useKernelBlur = true
  59365. */
  59366. set: function (value) {
  59367. if (this._blurKernel === value) {
  59368. return;
  59369. }
  59370. this._blurKernel = value;
  59371. this._disposeBlurPostProcesses();
  59372. },
  59373. enumerable: true,
  59374. configurable: true
  59375. });
  59376. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59377. /**
  59378. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59379. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59380. */
  59381. get: function () {
  59382. return this._useKernelBlur;
  59383. },
  59384. /**
  59385. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59386. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59387. */
  59388. set: function (value) {
  59389. if (this._useKernelBlur === value) {
  59390. return;
  59391. }
  59392. this._useKernelBlur = value;
  59393. this._disposeBlurPostProcesses();
  59394. },
  59395. enumerable: true,
  59396. configurable: true
  59397. });
  59398. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59399. /**
  59400. * Gets the depth scale used in ESM mode.
  59401. */
  59402. get: function () {
  59403. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59404. },
  59405. /**
  59406. * Sets the depth scale used in ESM mode.
  59407. * This can override the scale stored on the light.
  59408. */
  59409. set: function (value) {
  59410. this._depthScale = value;
  59411. },
  59412. enumerable: true,
  59413. configurable: true
  59414. });
  59415. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59416. /**
  59417. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59418. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59419. */
  59420. get: function () {
  59421. return this._filter;
  59422. },
  59423. /**
  59424. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59425. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59426. */
  59427. set: function (value) {
  59428. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59429. if (this._light.needCube()) {
  59430. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59431. this.useExponentialShadowMap = true;
  59432. return;
  59433. }
  59434. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59435. this.useCloseExponentialShadowMap = true;
  59436. return;
  59437. }
  59438. }
  59439. if (this._filter === value) {
  59440. return;
  59441. }
  59442. this._filter = value;
  59443. this._disposeBlurPostProcesses();
  59444. this._applyFilterValues();
  59445. this._light._markMeshesAsLightDirty();
  59446. },
  59447. enumerable: true,
  59448. configurable: true
  59449. });
  59450. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59451. /**
  59452. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59453. */
  59454. get: function () {
  59455. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59456. },
  59457. /**
  59458. * Sets the current filter to Poisson Sampling aka PCF.
  59459. */
  59460. set: function (value) {
  59461. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59462. return;
  59463. }
  59464. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59465. },
  59466. enumerable: true,
  59467. configurable: true
  59468. });
  59469. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59470. /**
  59471. * Gets if the current filter is set to VSM.
  59472. * DEPRECATED. Should use useExponentialShadowMap instead.
  59473. */
  59474. get: function () {
  59475. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59476. return this.useExponentialShadowMap;
  59477. },
  59478. /**
  59479. * Sets the current filter is to VSM.
  59480. * DEPRECATED. Should use useExponentialShadowMap instead.
  59481. */
  59482. set: function (value) {
  59483. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59484. this.useExponentialShadowMap = value;
  59485. },
  59486. enumerable: true,
  59487. configurable: true
  59488. });
  59489. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59490. /**
  59491. * Gets if the current filter is set to blurred VSM.
  59492. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59493. */
  59494. get: function () {
  59495. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59496. return this.useBlurExponentialShadowMap;
  59497. },
  59498. /**
  59499. * Sets the current filter is to blurred VSM.
  59500. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59501. */
  59502. set: function (value) {
  59503. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59504. this.useBlurExponentialShadowMap = value;
  59505. },
  59506. enumerable: true,
  59507. configurable: true
  59508. });
  59509. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59510. /**
  59511. * Gets if the current filter is set to ESM.
  59512. */
  59513. get: function () {
  59514. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59515. },
  59516. /**
  59517. * Sets the current filter is to ESM.
  59518. */
  59519. set: function (value) {
  59520. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59521. return;
  59522. }
  59523. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59524. },
  59525. enumerable: true,
  59526. configurable: true
  59527. });
  59528. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59529. /**
  59530. * Gets if the current filter is set to filtered ESM.
  59531. */
  59532. get: function () {
  59533. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59534. },
  59535. /**
  59536. * Gets if the current filter is set to filtered ESM.
  59537. */
  59538. set: function (value) {
  59539. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59540. return;
  59541. }
  59542. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59543. },
  59544. enumerable: true,
  59545. configurable: true
  59546. });
  59547. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59548. /**
  59549. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59550. * exponential to prevent steep falloff artifacts).
  59551. */
  59552. get: function () {
  59553. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59554. },
  59555. /**
  59556. * Sets the current filter to "close ESM" (using the inverse of the
  59557. * exponential to prevent steep falloff artifacts).
  59558. */
  59559. set: function (value) {
  59560. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59561. return;
  59562. }
  59563. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59564. },
  59565. enumerable: true,
  59566. configurable: true
  59567. });
  59568. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59569. /**
  59570. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59571. * exponential to prevent steep falloff artifacts).
  59572. */
  59573. get: function () {
  59574. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59575. },
  59576. /**
  59577. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59578. * exponential to prevent steep falloff artifacts).
  59579. */
  59580. set: function (value) {
  59581. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59582. return;
  59583. }
  59584. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59585. },
  59586. enumerable: true,
  59587. configurable: true
  59588. });
  59589. /**
  59590. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59591. * 0 means strongest and 1 would means no shadow.
  59592. * @returns the darkness.
  59593. */
  59594. ShadowGenerator.prototype.getDarkness = function () {
  59595. return this._darkness;
  59596. };
  59597. /**
  59598. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59599. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59600. * @returns the shadow generator allowing fluent coding.
  59601. */
  59602. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59603. if (darkness >= 1.0)
  59604. this._darkness = 1.0;
  59605. else if (darkness <= 0.0)
  59606. this._darkness = 0.0;
  59607. else
  59608. this._darkness = darkness;
  59609. return this;
  59610. };
  59611. /**
  59612. * Sets the ability to have transparent shadow (boolean).
  59613. * @param transparent True if transparent else False
  59614. * @returns the shadow generator allowing fluent coding
  59615. */
  59616. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59617. this._transparencyShadow = transparent;
  59618. return this;
  59619. };
  59620. /**
  59621. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59622. * @returns The render target texture if present otherwise, null
  59623. */
  59624. ShadowGenerator.prototype.getShadowMap = function () {
  59625. return this._shadowMap;
  59626. };
  59627. /**
  59628. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59629. * @returns The render target texture if the shadow map is present otherwise, null
  59630. */
  59631. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59632. if (this._shadowMap2) {
  59633. return this._shadowMap2;
  59634. }
  59635. return this._shadowMap;
  59636. };
  59637. /**
  59638. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59639. * @param mesh Mesh to add
  59640. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59641. * @returns the Shadow Generator itself
  59642. */
  59643. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59644. if (includeDescendants === void 0) { includeDescendants = true; }
  59645. if (!this._shadowMap) {
  59646. return this;
  59647. }
  59648. if (!this._shadowMap.renderList) {
  59649. this._shadowMap.renderList = [];
  59650. }
  59651. this._shadowMap.renderList.push(mesh);
  59652. if (includeDescendants) {
  59653. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59654. }
  59655. return this;
  59656. var _a;
  59657. };
  59658. /**
  59659. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59660. * @param mesh Mesh to remove
  59661. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59662. * @returns the Shadow Generator itself
  59663. */
  59664. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59665. if (includeDescendants === void 0) { includeDescendants = true; }
  59666. if (!this._shadowMap || !this._shadowMap.renderList) {
  59667. return this;
  59668. }
  59669. var index = this._shadowMap.renderList.indexOf(mesh);
  59670. if (index !== -1) {
  59671. this._shadowMap.renderList.splice(index, 1);
  59672. }
  59673. if (includeDescendants) {
  59674. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59675. var child = _a[_i];
  59676. this.removeShadowCaster(child);
  59677. }
  59678. }
  59679. return this;
  59680. };
  59681. /**
  59682. * Returns the associated light object.
  59683. * @returns the light generating the shadow
  59684. */
  59685. ShadowGenerator.prototype.getLight = function () {
  59686. return this._light;
  59687. };
  59688. ShadowGenerator.prototype._initializeGenerator = function () {
  59689. this._light._markMeshesAsLightDirty();
  59690. this._initializeShadowMap();
  59691. };
  59692. ShadowGenerator.prototype._initializeShadowMap = function () {
  59693. var _this = this;
  59694. // Render target
  59695. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59696. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59697. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59698. this._shadowMap.anisotropicFilteringLevel = 1;
  59699. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59700. this._shadowMap.renderParticles = false;
  59701. this._shadowMap.ignoreCameraViewport = true;
  59702. // Record Face Index before render.
  59703. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59704. _this._currentFaceIndex = faceIndex;
  59705. });
  59706. // Custom render function.
  59707. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59708. // Blur if required afer render.
  59709. this._shadowMap.onAfterUnbindObservable.add(function () {
  59710. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59711. return;
  59712. }
  59713. var shadowMap = _this.getShadowMapForRendering();
  59714. if (shadowMap) {
  59715. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59716. }
  59717. });
  59718. // Clear according to the chosen filter.
  59719. this._shadowMap.onClearObservable.add(function (engine) {
  59720. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59721. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59722. }
  59723. else {
  59724. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59725. }
  59726. });
  59727. };
  59728. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59729. var _this = this;
  59730. var engine = this._scene.getEngine();
  59731. var targetSize = this._mapSize / this.blurScale;
  59732. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59733. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59734. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59735. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59736. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59737. }
  59738. if (this.useKernelBlur) {
  59739. 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);
  59740. this._kernelBlurXPostprocess.width = targetSize;
  59741. this._kernelBlurXPostprocess.height = targetSize;
  59742. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59743. effect.setTexture("textureSampler", _this._shadowMap);
  59744. });
  59745. 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);
  59746. this._kernelBlurXPostprocess.autoClear = false;
  59747. this._kernelBlurYPostprocess.autoClear = false;
  59748. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59749. this._kernelBlurXPostprocess.packedFloat = true;
  59750. this._kernelBlurYPostprocess.packedFloat = true;
  59751. }
  59752. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59753. }
  59754. else {
  59755. 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);
  59756. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59757. effect.setFloat2("screenSize", targetSize, targetSize);
  59758. effect.setTexture("textureSampler", _this._shadowMap);
  59759. });
  59760. this._boxBlurPostprocess.autoClear = false;
  59761. this._blurPostProcesses = [this._boxBlurPostprocess];
  59762. }
  59763. };
  59764. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59765. var index;
  59766. var engine = this._scene.getEngine();
  59767. if (depthOnlySubMeshes.length) {
  59768. engine.setColorWrite(false);
  59769. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59770. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59771. }
  59772. engine.setColorWrite(true);
  59773. }
  59774. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59775. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59776. }
  59777. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59778. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59779. }
  59780. if (this._transparencyShadow) {
  59781. for (index = 0; index < transparentSubMeshes.length; index++) {
  59782. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59783. }
  59784. }
  59785. };
  59786. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59787. var _this = this;
  59788. var mesh = subMesh.getRenderingMesh();
  59789. var scene = this._scene;
  59790. var engine = scene.getEngine();
  59791. var material = subMesh.getMaterial();
  59792. if (!material) {
  59793. return;
  59794. }
  59795. // Culling
  59796. engine.setState(material.backFaceCulling);
  59797. // Managing instances
  59798. var batch = mesh._getInstancesRenderList(subMesh._id);
  59799. if (batch.mustReturn) {
  59800. return;
  59801. }
  59802. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59803. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59804. engine.enableEffect(this._effect);
  59805. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59806. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59807. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59808. this._effect.setVector3("lightPosition", this.getLight().position);
  59809. if (scene.activeCamera) {
  59810. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59811. }
  59812. // Alpha test
  59813. if (material && material.needAlphaTesting()) {
  59814. var alphaTexture = material.getAlphaTestTexture();
  59815. if (alphaTexture) {
  59816. this._effect.setTexture("diffuseSampler", alphaTexture);
  59817. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59818. }
  59819. }
  59820. // Bones
  59821. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59822. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59823. }
  59824. if (this.forceBackFacesOnly) {
  59825. engine.setState(true, 0, false, true);
  59826. }
  59827. // Draw
  59828. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59829. if (this.forceBackFacesOnly) {
  59830. engine.setState(true, 0, false, false);
  59831. }
  59832. }
  59833. else {
  59834. // Need to reset refresh rate of the shadowMap
  59835. if (this._shadowMap) {
  59836. this._shadowMap.resetRefreshCounter();
  59837. }
  59838. }
  59839. };
  59840. ShadowGenerator.prototype._applyFilterValues = function () {
  59841. if (!this._shadowMap) {
  59842. return;
  59843. }
  59844. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59845. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59846. }
  59847. else {
  59848. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59849. }
  59850. };
  59851. /**
  59852. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59853. * @param onCompiled Callback triggered at the and of the effects compilation
  59854. * @param options Sets of optional options forcing the compilation with different modes
  59855. */
  59856. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59857. var _this = this;
  59858. var localOptions = __assign({ useInstances: false }, options);
  59859. var shadowMap = this.getShadowMap();
  59860. if (!shadowMap) {
  59861. if (onCompiled) {
  59862. onCompiled(this);
  59863. }
  59864. return;
  59865. }
  59866. var renderList = shadowMap.renderList;
  59867. if (!renderList) {
  59868. if (onCompiled) {
  59869. onCompiled(this);
  59870. }
  59871. return;
  59872. }
  59873. var subMeshes = new Array();
  59874. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59875. var mesh = renderList_1[_i];
  59876. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59877. }
  59878. if (subMeshes.length === 0) {
  59879. if (onCompiled) {
  59880. onCompiled(this);
  59881. }
  59882. return;
  59883. }
  59884. var currentIndex = 0;
  59885. var checkReady = function () {
  59886. if (!_this._scene || !_this._scene.getEngine()) {
  59887. return;
  59888. }
  59889. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59890. currentIndex++;
  59891. if (currentIndex >= subMeshes.length) {
  59892. if (onCompiled) {
  59893. onCompiled(_this);
  59894. }
  59895. return;
  59896. }
  59897. }
  59898. setTimeout(checkReady, 16);
  59899. };
  59900. checkReady();
  59901. };
  59902. /**
  59903. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59904. * @param options Sets of optional options forcing the compilation with different modes
  59905. * @returns A promise that resolves when the compilation completes
  59906. */
  59907. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59908. var _this = this;
  59909. return new Promise(function (resolve) {
  59910. _this.forceCompilation(function () {
  59911. resolve();
  59912. }, options);
  59913. });
  59914. };
  59915. /**
  59916. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59917. * @param subMesh The submesh we want to render in the shadow map
  59918. * @param useInstances Defines wether will draw in the map using instances
  59919. * @returns true if ready otherwise, false
  59920. */
  59921. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59922. var defines = [];
  59923. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59924. defines.push("#define FLOAT");
  59925. }
  59926. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59927. defines.push("#define ESM");
  59928. }
  59929. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59930. var mesh = subMesh.getMesh();
  59931. var material = subMesh.getMaterial();
  59932. // Alpha test
  59933. if (material && material.needAlphaTesting()) {
  59934. var alphaTexture = material.getAlphaTestTexture();
  59935. if (alphaTexture) {
  59936. defines.push("#define ALPHATEST");
  59937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59938. attribs.push(BABYLON.VertexBuffer.UVKind);
  59939. defines.push("#define UV1");
  59940. }
  59941. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59942. if (alphaTexture.coordinatesIndex === 1) {
  59943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59944. defines.push("#define UV2");
  59945. }
  59946. }
  59947. }
  59948. }
  59949. // Bones
  59950. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59951. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59952. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59953. if (mesh.numBoneInfluencers > 4) {
  59954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59956. }
  59957. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59958. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59959. }
  59960. else {
  59961. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59962. }
  59963. // Instances
  59964. if (useInstances) {
  59965. defines.push("#define INSTANCES");
  59966. attribs.push("world0");
  59967. attribs.push("world1");
  59968. attribs.push("world2");
  59969. attribs.push("world3");
  59970. }
  59971. // Get correct effect
  59972. var join = defines.join("\n");
  59973. if (this._cachedDefines !== join) {
  59974. this._cachedDefines = join;
  59975. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59976. }
  59977. if (!this._effect.isReady()) {
  59978. return false;
  59979. }
  59980. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59981. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59982. this._initializeBlurRTTAndPostProcesses();
  59983. }
  59984. }
  59985. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59986. return false;
  59987. }
  59988. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59989. return false;
  59990. }
  59991. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59992. return false;
  59993. }
  59994. return true;
  59995. };
  59996. /**
  59997. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59998. * @param defines Defines of the material we want to update
  59999. * @param lightIndex Index of the light in the enabled light list of the material
  60000. */
  60001. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60002. var scene = this._scene;
  60003. var light = this._light;
  60004. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60005. return;
  60006. }
  60007. defines["SHADOW" + lightIndex] = true;
  60008. if (this.usePoissonSampling) {
  60009. defines["SHADOWPCF" + lightIndex] = true;
  60010. }
  60011. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60012. defines["SHADOWESM" + lightIndex] = true;
  60013. }
  60014. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60015. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60016. }
  60017. if (light.needCube()) {
  60018. defines["SHADOWCUBE" + lightIndex] = true;
  60019. }
  60020. };
  60021. /**
  60022. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60023. * defined in the generator but impacting the effect).
  60024. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60025. * @param effect The effect we are binfing the information for
  60026. */
  60027. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60028. var light = this._light;
  60029. var scene = this._scene;
  60030. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60031. return;
  60032. }
  60033. var camera = scene.activeCamera;
  60034. if (!camera) {
  60035. return;
  60036. }
  60037. var shadowMap = this.getShadowMap();
  60038. if (!shadowMap) {
  60039. return;
  60040. }
  60041. if (!light.needCube()) {
  60042. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60043. }
  60044. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60045. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60046. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60047. };
  60048. /**
  60049. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60050. * (eq to shadow prjection matrix * light transform matrix)
  60051. * @returns The transform matrix used to create the shadow map
  60052. */
  60053. ShadowGenerator.prototype.getTransformMatrix = function () {
  60054. var scene = this._scene;
  60055. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60056. return this._transformMatrix;
  60057. }
  60058. this._currentRenderID = scene.getRenderId();
  60059. this._currentFaceIndexCache = this._currentFaceIndex;
  60060. var lightPosition = this._light.position;
  60061. if (this._light.computeTransformedInformation()) {
  60062. lightPosition = this._light.transformedPosition;
  60063. }
  60064. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60065. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60066. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60067. }
  60068. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60069. this._cachedPosition = lightPosition.clone();
  60070. this._cachedDirection = this._lightDirection.clone();
  60071. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60072. var shadowMap = this.getShadowMap();
  60073. if (shadowMap) {
  60074. var renderList = shadowMap.renderList;
  60075. if (renderList) {
  60076. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60077. }
  60078. }
  60079. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60080. }
  60081. return this._transformMatrix;
  60082. };
  60083. /**
  60084. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60085. * Cube and 2D textures for instance.
  60086. */
  60087. ShadowGenerator.prototype.recreateShadowMap = function () {
  60088. var shadowMap = this._shadowMap;
  60089. if (!shadowMap) {
  60090. return;
  60091. }
  60092. // Track render list.
  60093. var renderList = shadowMap.renderList;
  60094. // Clean up existing data.
  60095. this._disposeRTTandPostProcesses();
  60096. // Reinitializes.
  60097. this._initializeGenerator();
  60098. // Reaffect the filter to ensure a correct fallback if necessary.
  60099. this.filter = this.filter;
  60100. // Reaffect the filter.
  60101. this._applyFilterValues();
  60102. // Reaffect Render List.
  60103. this._shadowMap.renderList = renderList;
  60104. };
  60105. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60106. if (this._shadowMap2) {
  60107. this._shadowMap2.dispose();
  60108. this._shadowMap2 = null;
  60109. }
  60110. if (this._boxBlurPostprocess) {
  60111. this._boxBlurPostprocess.dispose();
  60112. this._boxBlurPostprocess = null;
  60113. }
  60114. if (this._kernelBlurXPostprocess) {
  60115. this._kernelBlurXPostprocess.dispose();
  60116. this._kernelBlurXPostprocess = null;
  60117. }
  60118. if (this._kernelBlurYPostprocess) {
  60119. this._kernelBlurYPostprocess.dispose();
  60120. this._kernelBlurYPostprocess = null;
  60121. }
  60122. this._blurPostProcesses = [];
  60123. };
  60124. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60125. if (this._shadowMap) {
  60126. this._shadowMap.dispose();
  60127. this._shadowMap = null;
  60128. }
  60129. this._disposeBlurPostProcesses();
  60130. };
  60131. /**
  60132. * Disposes the ShadowGenerator.
  60133. * Returns nothing.
  60134. */
  60135. ShadowGenerator.prototype.dispose = function () {
  60136. this._disposeRTTandPostProcesses();
  60137. if (this._light) {
  60138. this._light._shadowGenerator = null;
  60139. this._light._markMeshesAsLightDirty();
  60140. }
  60141. };
  60142. /**
  60143. * Serializes the shadow generator setup to a json object.
  60144. * @returns The serialized JSON object
  60145. */
  60146. ShadowGenerator.prototype.serialize = function () {
  60147. var serializationObject = {};
  60148. var shadowMap = this.getShadowMap();
  60149. if (!shadowMap) {
  60150. return serializationObject;
  60151. }
  60152. serializationObject.lightId = this._light.id;
  60153. serializationObject.mapSize = shadowMap.getRenderSize();
  60154. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60155. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60156. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60157. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60158. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60159. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60160. serializationObject.depthScale = this.depthScale;
  60161. serializationObject.darkness = this.getDarkness();
  60162. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60163. serializationObject.blurKernel = this.blurKernel;
  60164. serializationObject.blurScale = this.blurScale;
  60165. serializationObject.useKernelBlur = this.useKernelBlur;
  60166. serializationObject.transparencyShadow = this._transparencyShadow;
  60167. serializationObject.renderList = [];
  60168. if (shadowMap.renderList) {
  60169. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60170. var mesh = shadowMap.renderList[meshIndex];
  60171. serializationObject.renderList.push(mesh.id);
  60172. }
  60173. }
  60174. return serializationObject;
  60175. };
  60176. /**
  60177. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60178. * @param parsedShadowGenerator The JSON object to parse
  60179. * @param scene The scene to create the shadow map for
  60180. * @returns The parsed shadow generator
  60181. */
  60182. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60183. //casting to point light, as light is missing the position attr and typescript complains.
  60184. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60185. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60186. var shadowMap = shadowGenerator.getShadowMap();
  60187. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60188. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60189. meshes.forEach(function (mesh) {
  60190. if (!shadowMap) {
  60191. return;
  60192. }
  60193. if (!shadowMap.renderList) {
  60194. shadowMap.renderList = [];
  60195. }
  60196. shadowMap.renderList.push(mesh);
  60197. });
  60198. }
  60199. if (parsedShadowGenerator.usePoissonSampling) {
  60200. shadowGenerator.usePoissonSampling = true;
  60201. }
  60202. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60203. shadowGenerator.useExponentialShadowMap = true;
  60204. }
  60205. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60206. shadowGenerator.useBlurExponentialShadowMap = true;
  60207. }
  60208. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60209. shadowGenerator.useCloseExponentialShadowMap = true;
  60210. }
  60211. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60212. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60213. }
  60214. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60215. shadowGenerator.useExponentialShadowMap = true;
  60216. }
  60217. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60218. shadowGenerator.useBlurExponentialShadowMap = true;
  60219. }
  60220. if (parsedShadowGenerator.depthScale) {
  60221. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60222. }
  60223. if (parsedShadowGenerator.blurScale) {
  60224. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60225. }
  60226. if (parsedShadowGenerator.blurBoxOffset) {
  60227. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60228. }
  60229. if (parsedShadowGenerator.useKernelBlur) {
  60230. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60231. }
  60232. if (parsedShadowGenerator.blurKernel) {
  60233. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60234. }
  60235. if (parsedShadowGenerator.bias !== undefined) {
  60236. shadowGenerator.bias = parsedShadowGenerator.bias;
  60237. }
  60238. if (parsedShadowGenerator.darkness) {
  60239. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60240. }
  60241. if (parsedShadowGenerator.transparencyShadow) {
  60242. shadowGenerator.setTransparencyShadow(true);
  60243. }
  60244. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60245. return shadowGenerator;
  60246. };
  60247. ShadowGenerator._FILTER_NONE = 0;
  60248. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60249. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60250. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60251. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60252. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60253. return ShadowGenerator;
  60254. }());
  60255. BABYLON.ShadowGenerator = ShadowGenerator;
  60256. })(BABYLON || (BABYLON = {}));
  60257. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60258. var BABYLON;
  60259. (function (BABYLON) {
  60260. var DefaultLoadingScreen = /** @class */ (function () {
  60261. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60262. if (_loadingText === void 0) { _loadingText = ""; }
  60263. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60264. var _this = this;
  60265. this._renderingCanvas = _renderingCanvas;
  60266. this._loadingText = _loadingText;
  60267. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60268. // Resize
  60269. this._resizeLoadingUI = function () {
  60270. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60271. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60272. if (!_this._loadingDiv) {
  60273. return;
  60274. }
  60275. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60276. _this._loadingDiv.style.left = canvasRect.left + "px";
  60277. _this._loadingDiv.style.top = canvasRect.top + "px";
  60278. _this._loadingDiv.style.width = canvasRect.width + "px";
  60279. _this._loadingDiv.style.height = canvasRect.height + "px";
  60280. };
  60281. }
  60282. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60283. if (this._loadingDiv) {
  60284. // Do not add a loading screen if there is already one
  60285. return;
  60286. }
  60287. this._loadingDiv = document.createElement("div");
  60288. this._loadingDiv.id = "babylonjsLoadingDiv";
  60289. this._loadingDiv.style.opacity = "0";
  60290. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60291. this._loadingDiv.style.pointerEvents = "none";
  60292. // Loading text
  60293. this._loadingTextDiv = document.createElement("div");
  60294. this._loadingTextDiv.style.position = "absolute";
  60295. this._loadingTextDiv.style.left = "0";
  60296. this._loadingTextDiv.style.top = "50%";
  60297. this._loadingTextDiv.style.marginTop = "80px";
  60298. this._loadingTextDiv.style.width = "100%";
  60299. this._loadingTextDiv.style.height = "20px";
  60300. this._loadingTextDiv.style.fontFamily = "Arial";
  60301. this._loadingTextDiv.style.fontSize = "14px";
  60302. this._loadingTextDiv.style.color = "white";
  60303. this._loadingTextDiv.style.textAlign = "center";
  60304. this._loadingTextDiv.innerHTML = "Loading";
  60305. this._loadingDiv.appendChild(this._loadingTextDiv);
  60306. //set the predefined text
  60307. this._loadingTextDiv.innerHTML = this._loadingText;
  60308. // Generating keyframes
  60309. var style = document.createElement('style');
  60310. style.type = 'text/css';
  60311. 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 }";
  60312. style.innerHTML = keyFrames;
  60313. document.getElementsByTagName('head')[0].appendChild(style);
  60314. // Loading img
  60315. var imgBack = new Image();
  60316. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  60317. imgBack.style.position = "absolute";
  60318. imgBack.style.left = "50%";
  60319. imgBack.style.top = "50%";
  60320. imgBack.style.marginLeft = "-60px";
  60321. imgBack.style.marginTop = "-60px";
  60322. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60323. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60324. imgBack.style.transformOrigin = "50% 50%";
  60325. imgBack.style.webkitTransformOrigin = "50% 50%";
  60326. this._loadingDiv.appendChild(imgBack);
  60327. this._resizeLoadingUI();
  60328. window.addEventListener("resize", this._resizeLoadingUI);
  60329. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60330. document.body.appendChild(this._loadingDiv);
  60331. this._loadingDiv.style.opacity = "1";
  60332. };
  60333. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60334. var _this = this;
  60335. if (!this._loadingDiv) {
  60336. return;
  60337. }
  60338. var onTransitionEnd = function () {
  60339. if (!_this._loadingDiv) {
  60340. return;
  60341. }
  60342. document.body.removeChild(_this._loadingDiv);
  60343. window.removeEventListener("resize", _this._resizeLoadingUI);
  60344. _this._loadingDiv = null;
  60345. };
  60346. this._loadingDiv.style.opacity = "0";
  60347. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60348. };
  60349. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60350. set: function (text) {
  60351. this._loadingText = text;
  60352. if (this._loadingTextDiv) {
  60353. this._loadingTextDiv.innerHTML = this._loadingText;
  60354. }
  60355. },
  60356. enumerable: true,
  60357. configurable: true
  60358. });
  60359. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60360. get: function () {
  60361. return this._loadingDivBackgroundColor;
  60362. },
  60363. set: function (color) {
  60364. this._loadingDivBackgroundColor = color;
  60365. if (!this._loadingDiv) {
  60366. return;
  60367. }
  60368. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60369. },
  60370. enumerable: true,
  60371. configurable: true
  60372. });
  60373. return DefaultLoadingScreen;
  60374. }());
  60375. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60376. })(BABYLON || (BABYLON = {}));
  60377. //# sourceMappingURL=babylon.loadingScreen.js.map
  60378. var BABYLON;
  60379. (function (BABYLON) {
  60380. var SceneLoaderProgressEvent = /** @class */ (function () {
  60381. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60382. this.lengthComputable = lengthComputable;
  60383. this.loaded = loaded;
  60384. this.total = total;
  60385. }
  60386. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60387. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60388. };
  60389. return SceneLoaderProgressEvent;
  60390. }());
  60391. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60392. var SceneLoader = /** @class */ (function () {
  60393. function SceneLoader() {
  60394. }
  60395. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60396. get: function () {
  60397. return 0;
  60398. },
  60399. enumerable: true,
  60400. configurable: true
  60401. });
  60402. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60403. get: function () {
  60404. return 1;
  60405. },
  60406. enumerable: true,
  60407. configurable: true
  60408. });
  60409. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60410. get: function () {
  60411. return 2;
  60412. },
  60413. enumerable: true,
  60414. configurable: true
  60415. });
  60416. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60417. get: function () {
  60418. return 3;
  60419. },
  60420. enumerable: true,
  60421. configurable: true
  60422. });
  60423. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60424. get: function () {
  60425. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60426. },
  60427. set: function (value) {
  60428. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60429. },
  60430. enumerable: true,
  60431. configurable: true
  60432. });
  60433. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60434. get: function () {
  60435. return SceneLoader._ShowLoadingScreen;
  60436. },
  60437. set: function (value) {
  60438. SceneLoader._ShowLoadingScreen = value;
  60439. },
  60440. enumerable: true,
  60441. configurable: true
  60442. });
  60443. Object.defineProperty(SceneLoader, "loggingLevel", {
  60444. get: function () {
  60445. return SceneLoader._loggingLevel;
  60446. },
  60447. set: function (value) {
  60448. SceneLoader._loggingLevel = value;
  60449. },
  60450. enumerable: true,
  60451. configurable: true
  60452. });
  60453. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60454. get: function () {
  60455. return SceneLoader._CleanBoneMatrixWeights;
  60456. },
  60457. set: function (value) {
  60458. SceneLoader._CleanBoneMatrixWeights = value;
  60459. },
  60460. enumerable: true,
  60461. configurable: true
  60462. });
  60463. SceneLoader._getDefaultPlugin = function () {
  60464. return SceneLoader._registeredPlugins[".babylon"];
  60465. };
  60466. SceneLoader._getPluginForExtension = function (extension) {
  60467. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60468. if (registeredPlugin) {
  60469. return registeredPlugin;
  60470. }
  60471. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60472. return SceneLoader._getDefaultPlugin();
  60473. };
  60474. SceneLoader._getPluginForDirectLoad = function (data) {
  60475. for (var extension in SceneLoader._registeredPlugins) {
  60476. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60477. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60478. return SceneLoader._registeredPlugins[extension];
  60479. }
  60480. }
  60481. return SceneLoader._getDefaultPlugin();
  60482. };
  60483. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60484. if (sceneFilename.name) {
  60485. sceneFilename = sceneFilename.name;
  60486. }
  60487. var queryStringPosition = sceneFilename.indexOf("?");
  60488. if (queryStringPosition !== -1) {
  60489. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60490. }
  60491. var dotPosition = sceneFilename.lastIndexOf(".");
  60492. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60493. return SceneLoader._getPluginForExtension(extension);
  60494. };
  60495. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60496. SceneLoader._getDirectLoad = function (sceneFilename) {
  60497. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60498. return sceneFilename.substr(5);
  60499. }
  60500. return null;
  60501. };
  60502. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60503. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60504. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60505. var plugin;
  60506. if (registeredPlugin.plugin.createPlugin) {
  60507. plugin = registeredPlugin.plugin.createPlugin();
  60508. }
  60509. else {
  60510. plugin = registeredPlugin.plugin;
  60511. }
  60512. var useArrayBuffer = registeredPlugin.isBinary;
  60513. var database;
  60514. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60515. var dataCallback = function (data, responseURL) {
  60516. if (scene.isDisposed) {
  60517. onError("Scene has been disposed");
  60518. return;
  60519. }
  60520. scene.database = database;
  60521. onSuccess(plugin, data, responseURL);
  60522. };
  60523. var request = null;
  60524. var pluginDisposed = false;
  60525. var onDisposeObservable = plugin.onDisposeObservable;
  60526. if (onDisposeObservable) {
  60527. onDisposeObservable.add(function () {
  60528. pluginDisposed = true;
  60529. if (request) {
  60530. request.abort();
  60531. request = null;
  60532. }
  60533. onDispose();
  60534. });
  60535. }
  60536. var manifestChecked = function () {
  60537. if (pluginDisposed) {
  60538. return;
  60539. }
  60540. var url = rootUrl + sceneFilename;
  60541. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60542. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60543. } : undefined, database, useArrayBuffer, function (request, exception) {
  60544. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60545. });
  60546. };
  60547. if (directLoad) {
  60548. dataCallback(directLoad);
  60549. return plugin;
  60550. }
  60551. if (rootUrl.indexOf("file:") === -1) {
  60552. if (scene.getEngine().enableOfflineSupport) {
  60553. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60554. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60555. }
  60556. else {
  60557. manifestChecked();
  60558. }
  60559. }
  60560. else {
  60561. var fileOrString = sceneFilename;
  60562. if (fileOrString.name) {
  60563. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60564. }
  60565. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60566. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60567. }
  60568. else {
  60569. onError("Unable to find file named " + sceneFilename);
  60570. }
  60571. }
  60572. return plugin;
  60573. };
  60574. // Public functions
  60575. SceneLoader.GetPluginForExtension = function (extension) {
  60576. return SceneLoader._getPluginForExtension(extension).plugin;
  60577. };
  60578. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60579. return !!SceneLoader._registeredPlugins[extension];
  60580. };
  60581. SceneLoader.RegisterPlugin = function (plugin) {
  60582. if (typeof plugin.extensions === "string") {
  60583. var extension = plugin.extensions;
  60584. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60585. plugin: plugin,
  60586. isBinary: false
  60587. };
  60588. }
  60589. else {
  60590. var extensions = plugin.extensions;
  60591. Object.keys(extensions).forEach(function (extension) {
  60592. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60593. plugin: plugin,
  60594. isBinary: extensions[extension].isBinary
  60595. };
  60596. });
  60597. }
  60598. };
  60599. /**
  60600. * Import meshes into a scene
  60601. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60602. * @param rootUrl a string that defines the root url for scene and resources
  60603. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60604. * @param scene the instance of BABYLON.Scene to append to
  60605. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60606. * @param onProgress a callback with a progress event for each file being loaded
  60607. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60608. * @param pluginExtension the extension used to determine the plugin
  60609. * @returns The loaded plugin
  60610. */
  60611. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60612. if (onSuccess === void 0) { onSuccess = null; }
  60613. if (onProgress === void 0) { onProgress = null; }
  60614. if (onError === void 0) { onError = null; }
  60615. if (pluginExtension === void 0) { pluginExtension = null; }
  60616. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60617. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60618. return null;
  60619. }
  60620. var loadingToken = {};
  60621. scene._addPendingData(loadingToken);
  60622. var disposeHandler = function () {
  60623. scene._removePendingData(loadingToken);
  60624. };
  60625. var errorHandler = function (message, exception) {
  60626. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60627. if (onError) {
  60628. onError(scene, errorMessage, exception);
  60629. }
  60630. else {
  60631. BABYLON.Tools.Error(errorMessage);
  60632. // should the exception be thrown?
  60633. }
  60634. disposeHandler();
  60635. };
  60636. var progressHandler = onProgress ? function (event) {
  60637. try {
  60638. onProgress(event);
  60639. }
  60640. catch (e) {
  60641. errorHandler("Error in onProgress callback", e);
  60642. }
  60643. } : undefined;
  60644. var successHandler = function (meshes, particleSystems, skeletons) {
  60645. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60646. if (onSuccess) {
  60647. try {
  60648. onSuccess(meshes, particleSystems, skeletons);
  60649. }
  60650. catch (e) {
  60651. errorHandler("Error in onSuccess callback", e);
  60652. }
  60653. }
  60654. scene._removePendingData(loadingToken);
  60655. };
  60656. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60657. if (plugin.rewriteRootURL) {
  60658. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60659. }
  60660. if (sceneFilename === "") {
  60661. if (sceneFilename === "") {
  60662. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60663. }
  60664. }
  60665. if (plugin.importMesh) {
  60666. var syncedPlugin = plugin;
  60667. var meshes = new Array();
  60668. var particleSystems = new Array();
  60669. var skeletons = new Array();
  60670. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60671. return;
  60672. }
  60673. scene.loadingPluginName = plugin.name;
  60674. successHandler(meshes, particleSystems, skeletons);
  60675. }
  60676. else {
  60677. var asyncedPlugin = plugin;
  60678. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60679. scene.loadingPluginName = plugin.name;
  60680. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60681. }).catch(function (error) {
  60682. errorHandler(error.message, error);
  60683. });
  60684. }
  60685. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60686. };
  60687. /**
  60688. * Import meshes into a scene
  60689. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60690. * @param rootUrl a string that defines the root url for scene and resources
  60691. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60692. * @param scene the instance of BABYLON.Scene to append to
  60693. * @param onProgress a callback with a progress event for each file being loaded
  60694. * @param pluginExtension the extension used to determine the plugin
  60695. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60696. */
  60697. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60698. if (onProgress === void 0) { onProgress = null; }
  60699. if (pluginExtension === void 0) { pluginExtension = null; }
  60700. return new Promise(function (resolve, reject) {
  60701. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60702. resolve({
  60703. meshes: meshes,
  60704. particleSystems: particleSystems,
  60705. skeletons: skeletons
  60706. });
  60707. }, onProgress, function (scene, message, exception) {
  60708. reject(exception || new Error(message));
  60709. });
  60710. });
  60711. };
  60712. /**
  60713. * Load a scene
  60714. * @param rootUrl a string that defines the root url for scene and resources
  60715. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60716. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60717. * @param onSuccess a callback with the scene when import succeeds
  60718. * @param onProgress a callback with a progress event for each file being loaded
  60719. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60720. * @param pluginExtension the extension used to determine the plugin
  60721. * @returns The loaded plugin
  60722. */
  60723. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60724. if (onSuccess === void 0) { onSuccess = null; }
  60725. if (onProgress === void 0) { onProgress = null; }
  60726. if (onError === void 0) { onError = null; }
  60727. if (pluginExtension === void 0) { pluginExtension = null; }
  60728. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60729. };
  60730. /**
  60731. * Load a scene
  60732. * @param rootUrl a string that defines the root url for scene and resources
  60733. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60734. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60735. * @param onProgress a callback with a progress event for each file being loaded
  60736. * @param pluginExtension the extension used to determine the plugin
  60737. * @returns The loaded scene
  60738. */
  60739. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60740. if (onProgress === void 0) { onProgress = null; }
  60741. if (pluginExtension === void 0) { pluginExtension = null; }
  60742. return new Promise(function (resolve, reject) {
  60743. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60744. resolve(scene);
  60745. }, onProgress, function (scene, message, exception) {
  60746. reject(exception || new Error(message));
  60747. }, pluginExtension);
  60748. });
  60749. };
  60750. /**
  60751. * Append a scene
  60752. * @param rootUrl a string that defines the root url for scene and resources
  60753. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60754. * @param scene is the instance of BABYLON.Scene to append to
  60755. * @param onSuccess a callback with the scene when import succeeds
  60756. * @param onProgress a callback with a progress event for each file being loaded
  60757. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60758. * @param pluginExtension the extension used to determine the plugin
  60759. * @returns The loaded plugin
  60760. */
  60761. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60762. if (onSuccess === void 0) { onSuccess = null; }
  60763. if (onProgress === void 0) { onProgress = null; }
  60764. if (onError === void 0) { onError = null; }
  60765. if (pluginExtension === void 0) { pluginExtension = null; }
  60766. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60767. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60768. return null;
  60769. }
  60770. if (SceneLoader.ShowLoadingScreen) {
  60771. scene.getEngine().displayLoadingUI();
  60772. }
  60773. var loadingToken = {};
  60774. scene._addPendingData(loadingToken);
  60775. var disposeHandler = function () {
  60776. scene._removePendingData(loadingToken);
  60777. scene.getEngine().hideLoadingUI();
  60778. };
  60779. var errorHandler = function (message, exception) {
  60780. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60781. if (onError) {
  60782. onError(scene, errorMessage, exception);
  60783. }
  60784. else {
  60785. BABYLON.Tools.Error(errorMessage);
  60786. // should the exception be thrown?
  60787. }
  60788. disposeHandler();
  60789. };
  60790. var progressHandler = onProgress ? function (event) {
  60791. try {
  60792. onProgress(event);
  60793. }
  60794. catch (e) {
  60795. errorHandler("Error in onProgress callback", e);
  60796. }
  60797. } : undefined;
  60798. var successHandler = function () {
  60799. if (onSuccess) {
  60800. try {
  60801. onSuccess(scene);
  60802. }
  60803. catch (e) {
  60804. errorHandler("Error in onSuccess callback", e);
  60805. }
  60806. }
  60807. scene._removePendingData(loadingToken);
  60808. };
  60809. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60810. if (sceneFilename === "") {
  60811. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60812. }
  60813. if (plugin.load) {
  60814. var syncedPlugin = plugin;
  60815. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60816. return;
  60817. }
  60818. scene.loadingPluginName = plugin.name;
  60819. successHandler();
  60820. }
  60821. else {
  60822. var asyncedPlugin = plugin;
  60823. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60824. scene.loadingPluginName = plugin.name;
  60825. successHandler();
  60826. }).catch(function (error) {
  60827. errorHandler(error.message, error);
  60828. });
  60829. }
  60830. if (SceneLoader.ShowLoadingScreen) {
  60831. scene.executeWhenReady(function () {
  60832. scene.getEngine().hideLoadingUI();
  60833. });
  60834. }
  60835. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60836. };
  60837. /**
  60838. * Append a scene
  60839. * @param rootUrl a string that defines the root url for scene and resources
  60840. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60841. * @param scene is the instance of BABYLON.Scene to append to
  60842. * @param onProgress a callback with a progress event for each file being loaded
  60843. * @param pluginExtension the extension used to determine the plugin
  60844. * @returns The given scene
  60845. */
  60846. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60847. if (onProgress === void 0) { onProgress = null; }
  60848. if (pluginExtension === void 0) { pluginExtension = null; }
  60849. return new Promise(function (resolve, reject) {
  60850. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60851. resolve(scene);
  60852. }, onProgress, function (scene, message, exception) {
  60853. reject(exception || new Error(message));
  60854. }, pluginExtension);
  60855. });
  60856. };
  60857. /**
  60858. * Load a scene into an asset container
  60859. * @param rootUrl a string that defines the root url for scene and resources
  60860. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60861. * @param scene is the instance of BABYLON.Scene to append to
  60862. * @param onSuccess a callback with the scene when import succeeds
  60863. * @param onProgress a callback with a progress event for each file being loaded
  60864. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60865. * @param pluginExtension the extension used to determine the plugin
  60866. * @returns The loaded plugin
  60867. */
  60868. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60869. if (onSuccess === void 0) { onSuccess = null; }
  60870. if (onProgress === void 0) { onProgress = null; }
  60871. if (onError === void 0) { onError = null; }
  60872. if (pluginExtension === void 0) { pluginExtension = null; }
  60873. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60874. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60875. return null;
  60876. }
  60877. var loadingToken = {};
  60878. scene._addPendingData(loadingToken);
  60879. var disposeHandler = function () {
  60880. scene._removePendingData(loadingToken);
  60881. };
  60882. var errorHandler = function (message, exception) {
  60883. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60884. if (onError) {
  60885. onError(scene, errorMessage, exception);
  60886. }
  60887. else {
  60888. BABYLON.Tools.Error(errorMessage);
  60889. // should the exception be thrown?
  60890. }
  60891. disposeHandler();
  60892. };
  60893. var progressHandler = onProgress ? function (event) {
  60894. try {
  60895. onProgress(event);
  60896. }
  60897. catch (e) {
  60898. errorHandler("Error in onProgress callback", e);
  60899. }
  60900. } : undefined;
  60901. var successHandler = function (assets) {
  60902. if (onSuccess) {
  60903. try {
  60904. onSuccess(assets);
  60905. }
  60906. catch (e) {
  60907. errorHandler("Error in onSuccess callback", e);
  60908. }
  60909. }
  60910. scene._removePendingData(loadingToken);
  60911. };
  60912. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60913. if (plugin.loadAssetContainer) {
  60914. var syncedPlugin = plugin;
  60915. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60916. if (!assetContainer) {
  60917. return;
  60918. }
  60919. scene.loadingPluginName = plugin.name;
  60920. successHandler(assetContainer);
  60921. }
  60922. else if (plugin.loadAssetContainerAsync) {
  60923. var asyncedPlugin = plugin;
  60924. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60925. scene.loadingPluginName = plugin.name;
  60926. successHandler(assetContainer);
  60927. }).catch(function (error) {
  60928. errorHandler(error.message, error);
  60929. });
  60930. }
  60931. else {
  60932. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60933. }
  60934. if (SceneLoader.ShowLoadingScreen) {
  60935. scene.executeWhenReady(function () {
  60936. scene.getEngine().hideLoadingUI();
  60937. });
  60938. }
  60939. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60940. };
  60941. /**
  60942. * Load a scene into an asset container
  60943. * @param rootUrl a string that defines the root url for scene and resources
  60944. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60945. * @param scene is the instance of BABYLON.Scene to append to
  60946. * @param onProgress a callback with a progress event for each file being loaded
  60947. * @param pluginExtension the extension used to determine the plugin
  60948. * @returns The loaded asset container
  60949. */
  60950. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60951. if (onProgress === void 0) { onProgress = null; }
  60952. if (pluginExtension === void 0) { pluginExtension = null; }
  60953. return new Promise(function (resolve, reject) {
  60954. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60955. resolve(assetContainer);
  60956. }, onProgress, function (scene, message, exception) {
  60957. reject(exception || new Error(message));
  60958. }, pluginExtension);
  60959. });
  60960. };
  60961. // Flags
  60962. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60963. SceneLoader._ShowLoadingScreen = true;
  60964. SceneLoader._CleanBoneMatrixWeights = false;
  60965. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60966. // Members
  60967. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60968. SceneLoader._registeredPlugins = {};
  60969. return SceneLoader;
  60970. }());
  60971. BABYLON.SceneLoader = SceneLoader;
  60972. ;
  60973. })(BABYLON || (BABYLON = {}));
  60974. //# sourceMappingURL=babylon.sceneLoader.js.map
  60975. var BABYLON;
  60976. (function (BABYLON) {
  60977. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60978. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60979. var parsedMaterial = parsedData.materials[index];
  60980. if (parsedMaterial.id === id) {
  60981. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60982. }
  60983. }
  60984. return null;
  60985. };
  60986. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60987. for (var i in names) {
  60988. if (mesh.name === names[i]) {
  60989. hierarchyIds.push(mesh.id);
  60990. return true;
  60991. }
  60992. }
  60993. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60994. hierarchyIds.push(mesh.id);
  60995. return true;
  60996. }
  60997. return false;
  60998. };
  60999. var logOperation = function (operation, producer) {
  61000. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61001. };
  61002. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61003. if (addToScene === void 0) { addToScene = false; }
  61004. var container = new BABYLON.AssetContainer(scene);
  61005. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61006. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61007. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61008. // and avoid problems with multiple concurrent .babylon loads.
  61009. var log = "importScene has failed JSON parse";
  61010. try {
  61011. var parsedData = JSON.parse(data);
  61012. log = "";
  61013. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61014. var index;
  61015. var cache;
  61016. // Lights
  61017. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61018. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61019. var parsedLight = parsedData.lights[index];
  61020. var light = BABYLON.Light.Parse(parsedLight, scene);
  61021. if (light) {
  61022. container.lights.push(light);
  61023. log += (index === 0 ? "\n\tLights:" : "");
  61024. log += "\n\t\t" + light.toString(fullDetails);
  61025. }
  61026. }
  61027. }
  61028. // Animations
  61029. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61030. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61031. var parsedAnimation = parsedData.animations[index];
  61032. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61033. scene.animations.push(animation);
  61034. container.animations.push(animation);
  61035. log += (index === 0 ? "\n\tAnimations:" : "");
  61036. log += "\n\t\t" + animation.toString(fullDetails);
  61037. }
  61038. }
  61039. // Materials
  61040. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61041. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61042. var parsedMaterial = parsedData.materials[index];
  61043. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61044. container.materials.push(mat);
  61045. log += (index === 0 ? "\n\tMaterials:" : "");
  61046. log += "\n\t\t" + mat.toString(fullDetails);
  61047. }
  61048. }
  61049. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61050. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61051. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61052. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61053. container.multiMaterials.push(mmat);
  61054. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61055. log += "\n\t\t" + mmat.toString(fullDetails);
  61056. }
  61057. }
  61058. // Morph targets
  61059. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61060. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61061. var managerData = _a[_i];
  61062. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61063. }
  61064. }
  61065. // Skeletons
  61066. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61067. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61068. var parsedSkeleton = parsedData.skeletons[index];
  61069. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61070. container.skeletons.push(skeleton);
  61071. log += (index === 0 ? "\n\tSkeletons:" : "");
  61072. log += "\n\t\t" + skeleton.toString(fullDetails);
  61073. }
  61074. }
  61075. // Geometries
  61076. var geometries = parsedData.geometries;
  61077. if (geometries !== undefined && geometries !== null) {
  61078. var addedGeometry = new Array();
  61079. // Boxes
  61080. var boxes = geometries.boxes;
  61081. if (boxes !== undefined && boxes !== null) {
  61082. for (index = 0, cache = boxes.length; index < cache; index++) {
  61083. var parsedBox = boxes[index];
  61084. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61085. }
  61086. }
  61087. // Spheres
  61088. var spheres = geometries.spheres;
  61089. if (spheres !== undefined && spheres !== null) {
  61090. for (index = 0, cache = spheres.length; index < cache; index++) {
  61091. var parsedSphere = spheres[index];
  61092. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61093. }
  61094. }
  61095. // Cylinders
  61096. var cylinders = geometries.cylinders;
  61097. if (cylinders !== undefined && cylinders !== null) {
  61098. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61099. var parsedCylinder = cylinders[index];
  61100. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61101. }
  61102. }
  61103. // Toruses
  61104. var toruses = geometries.toruses;
  61105. if (toruses !== undefined && toruses !== null) {
  61106. for (index = 0, cache = toruses.length; index < cache; index++) {
  61107. var parsedTorus = toruses[index];
  61108. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61109. }
  61110. }
  61111. // Grounds
  61112. var grounds = geometries.grounds;
  61113. if (grounds !== undefined && grounds !== null) {
  61114. for (index = 0, cache = grounds.length; index < cache; index++) {
  61115. var parsedGround = grounds[index];
  61116. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61117. }
  61118. }
  61119. // Planes
  61120. var planes = geometries.planes;
  61121. if (planes !== undefined && planes !== null) {
  61122. for (index = 0, cache = planes.length; index < cache; index++) {
  61123. var parsedPlane = planes[index];
  61124. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61125. }
  61126. }
  61127. // TorusKnots
  61128. var torusKnots = geometries.torusKnots;
  61129. if (torusKnots !== undefined && torusKnots !== null) {
  61130. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61131. var parsedTorusKnot = torusKnots[index];
  61132. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61133. }
  61134. }
  61135. // VertexData
  61136. var vertexData = geometries.vertexData;
  61137. if (vertexData !== undefined && vertexData !== null) {
  61138. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61139. var parsedVertexData = vertexData[index];
  61140. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61141. }
  61142. }
  61143. addedGeometry.forEach(function (g) {
  61144. if (g) {
  61145. container.geometries.push(g);
  61146. }
  61147. });
  61148. }
  61149. // Transform nodes
  61150. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61151. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61152. var parsedTransformNode = parsedData.transformNodes[index];
  61153. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61154. container.transformNodes.push(node);
  61155. }
  61156. }
  61157. // Meshes
  61158. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61159. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61160. var parsedMesh = parsedData.meshes[index];
  61161. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61162. container.meshes.push(mesh);
  61163. log += (index === 0 ? "\n\tMeshes:" : "");
  61164. log += "\n\t\t" + mesh.toString(fullDetails);
  61165. }
  61166. }
  61167. // Cameras
  61168. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61169. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61170. var parsedCamera = parsedData.cameras[index];
  61171. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61172. container.cameras.push(camera);
  61173. log += (index === 0 ? "\n\tCameras:" : "");
  61174. log += "\n\t\t" + camera.toString(fullDetails);
  61175. }
  61176. }
  61177. // Browsing all the graph to connect the dots
  61178. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61179. var camera = scene.cameras[index];
  61180. if (camera._waitingParentId) {
  61181. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61182. camera._waitingParentId = null;
  61183. }
  61184. }
  61185. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61186. var light_1 = scene.lights[index];
  61187. if (light_1 && light_1._waitingParentId) {
  61188. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61189. light_1._waitingParentId = null;
  61190. }
  61191. }
  61192. // Sounds
  61193. // TODO: add sound
  61194. var loadedSounds = [];
  61195. var loadedSound;
  61196. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61197. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61198. var parsedSound = parsedData.sounds[index];
  61199. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61200. if (!parsedSound.url)
  61201. parsedSound.url = parsedSound.name;
  61202. if (!loadedSounds[parsedSound.url]) {
  61203. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61204. loadedSounds[parsedSound.url] = loadedSound;
  61205. container.sounds.push(loadedSound);
  61206. }
  61207. else {
  61208. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61209. }
  61210. }
  61211. else {
  61212. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61213. }
  61214. }
  61215. }
  61216. loadedSounds = [];
  61217. // Connect parents & children and parse actions
  61218. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61219. var transformNode = scene.transformNodes[index];
  61220. if (transformNode._waitingParentId) {
  61221. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61222. transformNode._waitingParentId = null;
  61223. }
  61224. }
  61225. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61226. var mesh = scene.meshes[index];
  61227. if (mesh._waitingParentId) {
  61228. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61229. mesh._waitingParentId = null;
  61230. }
  61231. if (mesh._waitingActions) {
  61232. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61233. mesh._waitingActions = null;
  61234. }
  61235. }
  61236. // freeze world matrix application
  61237. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61238. var currentMesh = scene.meshes[index];
  61239. if (currentMesh._waitingFreezeWorldMatrix) {
  61240. currentMesh.freezeWorldMatrix();
  61241. currentMesh._waitingFreezeWorldMatrix = null;
  61242. }
  61243. else {
  61244. currentMesh.computeWorldMatrix(true);
  61245. }
  61246. }
  61247. // Particles Systems
  61248. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61249. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61250. var parsedParticleSystem = parsedData.particleSystems[index];
  61251. if (parsedParticleSystem.activeParticleCount) {
  61252. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61253. container.particleSystems.push(ps);
  61254. }
  61255. else {
  61256. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61257. container.particleSystems.push(ps);
  61258. }
  61259. }
  61260. }
  61261. // Lens flares
  61262. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61263. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61264. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61265. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61266. container.lensFlareSystems.push(lf);
  61267. }
  61268. }
  61269. // Shadows
  61270. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61271. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61272. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61273. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61274. container.shadowGenerators.push(sg);
  61275. }
  61276. }
  61277. // Lights exclusions / inclusions
  61278. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61279. var light_2 = scene.lights[index];
  61280. // Excluded check
  61281. if (light_2._excludedMeshesIds.length > 0) {
  61282. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61283. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61284. if (excludedMesh) {
  61285. light_2.excludedMeshes.push(excludedMesh);
  61286. }
  61287. }
  61288. light_2._excludedMeshesIds = [];
  61289. }
  61290. // Included check
  61291. if (light_2._includedOnlyMeshesIds.length > 0) {
  61292. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61293. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61294. if (includedOnlyMesh) {
  61295. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61296. }
  61297. }
  61298. light_2._includedOnlyMeshesIds = [];
  61299. }
  61300. }
  61301. // Actions (scene)
  61302. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61303. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61304. }
  61305. if (!addToScene) {
  61306. container.removeAllFromScene();
  61307. }
  61308. }
  61309. catch (err) {
  61310. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61311. if (onError) {
  61312. onError(msg, err);
  61313. }
  61314. else {
  61315. BABYLON.Tools.Log(msg);
  61316. throw err;
  61317. }
  61318. }
  61319. finally {
  61320. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61321. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61322. }
  61323. }
  61324. return container;
  61325. };
  61326. BABYLON.SceneLoader.RegisterPlugin({
  61327. name: "babylon.js",
  61328. extensions: ".babylon",
  61329. canDirectLoad: function (data) {
  61330. if (data.indexOf("babylon") !== -1) {
  61331. return true;
  61332. }
  61333. return false;
  61334. },
  61335. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61336. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61337. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61338. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61339. // and avoid problems with multiple concurrent .babylon loads.
  61340. var log = "importMesh has failed JSON parse";
  61341. try {
  61342. var parsedData = JSON.parse(data);
  61343. log = "";
  61344. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61345. if (!meshesNames) {
  61346. meshesNames = null;
  61347. }
  61348. else if (!Array.isArray(meshesNames)) {
  61349. meshesNames = [meshesNames];
  61350. }
  61351. var hierarchyIds = new Array();
  61352. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61353. var loadedSkeletonsIds = [];
  61354. var loadedMaterialsIds = [];
  61355. var index;
  61356. var cache;
  61357. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61358. var parsedMesh = parsedData.meshes[index];
  61359. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61360. if (meshesNames !== null) {
  61361. // Remove found mesh name from list.
  61362. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61363. }
  61364. //Geometry?
  61365. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61366. //does the file contain geometries?
  61367. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61368. //find the correct geometry and add it to the scene
  61369. var found = false;
  61370. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61371. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61372. return;
  61373. }
  61374. else {
  61375. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61376. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61377. switch (geometryType) {
  61378. case "boxes":
  61379. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61380. break;
  61381. case "spheres":
  61382. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61383. break;
  61384. case "cylinders":
  61385. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61386. break;
  61387. case "toruses":
  61388. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61389. break;
  61390. case "grounds":
  61391. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61392. break;
  61393. case "planes":
  61394. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61395. break;
  61396. case "torusKnots":
  61397. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61398. break;
  61399. case "vertexData":
  61400. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61401. break;
  61402. }
  61403. found = true;
  61404. }
  61405. });
  61406. }
  61407. });
  61408. if (found === false) {
  61409. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61410. }
  61411. }
  61412. }
  61413. // Material ?
  61414. if (parsedMesh.materialId) {
  61415. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61416. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61417. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61418. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61419. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61420. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61421. var subMatId = parsedMultiMaterial.materials[matIndex];
  61422. loadedMaterialsIds.push(subMatId);
  61423. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61424. if (mat) {
  61425. log += "\n\tMaterial " + mat.toString(fullDetails);
  61426. }
  61427. }
  61428. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61429. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61430. if (mmat) {
  61431. materialFound = true;
  61432. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61433. }
  61434. break;
  61435. }
  61436. }
  61437. }
  61438. if (materialFound === false) {
  61439. loadedMaterialsIds.push(parsedMesh.materialId);
  61440. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61441. if (!mat) {
  61442. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61443. }
  61444. else {
  61445. log += "\n\tMaterial " + mat.toString(fullDetails);
  61446. }
  61447. }
  61448. }
  61449. // Skeleton ?
  61450. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61451. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61452. if (skeletonAlreadyLoaded === false) {
  61453. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61454. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61455. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61456. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61457. skeletons.push(skeleton);
  61458. loadedSkeletonsIds.push(parsedSkeleton.id);
  61459. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61460. }
  61461. }
  61462. }
  61463. }
  61464. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61465. meshes.push(mesh);
  61466. log += "\n\tMesh " + mesh.toString(fullDetails);
  61467. }
  61468. }
  61469. // Connecting parents
  61470. var currentMesh;
  61471. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61472. currentMesh = scene.meshes[index];
  61473. if (currentMesh._waitingParentId) {
  61474. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61475. currentMesh._waitingParentId = null;
  61476. }
  61477. }
  61478. // freeze and compute world matrix application
  61479. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61480. currentMesh = scene.meshes[index];
  61481. if (currentMesh._waitingFreezeWorldMatrix) {
  61482. currentMesh.freezeWorldMatrix();
  61483. currentMesh._waitingFreezeWorldMatrix = null;
  61484. }
  61485. else {
  61486. currentMesh.computeWorldMatrix(true);
  61487. }
  61488. }
  61489. }
  61490. // Particles
  61491. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61492. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61493. var parsedParticleSystem = parsedData.particleSystems[index];
  61494. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61495. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61496. }
  61497. }
  61498. }
  61499. return true;
  61500. }
  61501. catch (err) {
  61502. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61503. if (onError) {
  61504. onError(msg, err);
  61505. }
  61506. else {
  61507. BABYLON.Tools.Log(msg);
  61508. throw err;
  61509. }
  61510. }
  61511. finally {
  61512. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61513. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61514. }
  61515. }
  61516. return false;
  61517. },
  61518. load: function (scene, data, rootUrl, onError) {
  61519. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61520. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61521. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61522. // and avoid problems with multiple concurrent .babylon loads.
  61523. var log = "importScene has failed JSON parse";
  61524. try {
  61525. var parsedData = JSON.parse(data);
  61526. log = "";
  61527. // Scene
  61528. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61529. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61530. }
  61531. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61532. scene.autoClear = parsedData.autoClear;
  61533. }
  61534. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61535. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61536. }
  61537. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61538. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61539. }
  61540. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61541. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61542. }
  61543. // Fog
  61544. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61545. scene.fogMode = parsedData.fogMode;
  61546. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61547. scene.fogStart = parsedData.fogStart;
  61548. scene.fogEnd = parsedData.fogEnd;
  61549. scene.fogDensity = parsedData.fogDensity;
  61550. log += "\tFog mode for scene: ";
  61551. switch (scene.fogMode) {
  61552. // getters not compiling, so using hardcoded
  61553. case 1:
  61554. log += "exp\n";
  61555. break;
  61556. case 2:
  61557. log += "exp2\n";
  61558. break;
  61559. case 3:
  61560. log += "linear\n";
  61561. break;
  61562. }
  61563. }
  61564. //Physics
  61565. if (parsedData.physicsEnabled) {
  61566. var physicsPlugin;
  61567. if (parsedData.physicsEngine === "cannon") {
  61568. physicsPlugin = new BABYLON.CannonJSPlugin();
  61569. }
  61570. else if (parsedData.physicsEngine === "oimo") {
  61571. physicsPlugin = new BABYLON.OimoJSPlugin();
  61572. }
  61573. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61574. //else - default engine, which is currently oimo
  61575. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61576. scene.enablePhysics(physicsGravity, physicsPlugin);
  61577. }
  61578. // Metadata
  61579. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61580. scene.metadata = parsedData.metadata;
  61581. }
  61582. //collisions, if defined. otherwise, default is true
  61583. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61584. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61585. }
  61586. scene.workerCollisions = !!parsedData.workerCollisions;
  61587. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61588. if (!container) {
  61589. return false;
  61590. }
  61591. if (parsedData.autoAnimate) {
  61592. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61593. }
  61594. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61595. scene.setActiveCameraByID(parsedData.activeCameraID);
  61596. }
  61597. // Environment texture
  61598. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61599. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61600. if (parsedData.createDefaultSkybox === true) {
  61601. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61602. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61603. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61604. }
  61605. }
  61606. // Finish
  61607. return true;
  61608. }
  61609. catch (err) {
  61610. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61611. if (onError) {
  61612. onError(msg, err);
  61613. }
  61614. else {
  61615. BABYLON.Tools.Log(msg);
  61616. throw err;
  61617. }
  61618. }
  61619. finally {
  61620. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61621. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61622. }
  61623. }
  61624. return false;
  61625. },
  61626. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61627. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61628. return container;
  61629. }
  61630. });
  61631. })(BABYLON || (BABYLON = {}));
  61632. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61633. var BABYLON;
  61634. (function (BABYLON) {
  61635. var FilesInput = /** @class */ (function () {
  61636. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61637. this.onProcessFileCallback = function () { return true; };
  61638. this._engine = engine;
  61639. this._currentScene = scene;
  61640. this._sceneLoadedCallback = sceneLoadedCallback;
  61641. this._progressCallback = progressCallback;
  61642. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61643. this._textureLoadingCallback = textureLoadingCallback;
  61644. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61645. this._onReloadCallback = onReloadCallback;
  61646. this._errorCallback = errorCallback;
  61647. }
  61648. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61649. var _this = this;
  61650. if (elementToMonitor) {
  61651. this._elementToMonitor = elementToMonitor;
  61652. this._dragEnterHandler = function (e) { _this.drag(e); };
  61653. this._dragOverHandler = function (e) { _this.drag(e); };
  61654. this._dropHandler = function (e) { _this.drop(e); };
  61655. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61656. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61657. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61658. }
  61659. };
  61660. FilesInput.prototype.dispose = function () {
  61661. if (!this._elementToMonitor) {
  61662. return;
  61663. }
  61664. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61665. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61666. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61667. };
  61668. FilesInput.prototype.renderFunction = function () {
  61669. if (this._additionalRenderLoopLogicCallback) {
  61670. this._additionalRenderLoopLogicCallback();
  61671. }
  61672. if (this._currentScene) {
  61673. if (this._textureLoadingCallback) {
  61674. var remaining = this._currentScene.getWaitingItemsCount();
  61675. if (remaining > 0) {
  61676. this._textureLoadingCallback(remaining);
  61677. }
  61678. }
  61679. this._currentScene.render();
  61680. }
  61681. };
  61682. FilesInput.prototype.drag = function (e) {
  61683. e.stopPropagation();
  61684. e.preventDefault();
  61685. };
  61686. FilesInput.prototype.drop = function (eventDrop) {
  61687. eventDrop.stopPropagation();
  61688. eventDrop.preventDefault();
  61689. this.loadFiles(eventDrop);
  61690. };
  61691. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61692. var _this = this;
  61693. var reader = folder.createReader();
  61694. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61695. reader.readEntries(function (entries) {
  61696. remaining.count += entries.length;
  61697. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61698. var entry = entries_1[_i];
  61699. if (entry.isFile) {
  61700. entry.file(function (file) {
  61701. file.correctName = relativePath + file.name;
  61702. files.push(file);
  61703. if (--remaining.count === 0) {
  61704. callback();
  61705. }
  61706. });
  61707. }
  61708. else if (entry.isDirectory) {
  61709. _this._traverseFolder(entry, files, remaining, callback);
  61710. }
  61711. }
  61712. if (--remaining.count) {
  61713. callback();
  61714. }
  61715. });
  61716. };
  61717. FilesInput.prototype._processFiles = function (files) {
  61718. for (var i = 0; i < files.length; i++) {
  61719. var name = files[i].correctName.toLowerCase();
  61720. var extension = name.split('.').pop();
  61721. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61722. continue;
  61723. }
  61724. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61725. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61726. this._sceneFileToLoad = files[i];
  61727. }
  61728. else {
  61729. FilesInput.FilesToLoad[name] = files[i];
  61730. }
  61731. }
  61732. };
  61733. FilesInput.prototype.loadFiles = function (event) {
  61734. var _this = this;
  61735. if (this._startingProcessingFilesCallback)
  61736. this._startingProcessingFilesCallback();
  61737. // Handling data transfer via drag'n'drop
  61738. if (event && event.dataTransfer && event.dataTransfer.files) {
  61739. this._filesToLoad = event.dataTransfer.files;
  61740. }
  61741. // Handling files from input files
  61742. if (event && event.target && event.target.files) {
  61743. this._filesToLoad = event.target.files;
  61744. }
  61745. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61746. var files_1 = new Array();
  61747. var folders = [];
  61748. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61749. for (var i = 0; i < this._filesToLoad.length; i++) {
  61750. var fileToLoad = this._filesToLoad[i];
  61751. var name_1 = fileToLoad.name.toLowerCase();
  61752. var entry = void 0;
  61753. fileToLoad.correctName = name_1;
  61754. if (items) {
  61755. var item = items[i];
  61756. if (item.getAsEntry) {
  61757. entry = item.getAsEntry();
  61758. }
  61759. else if (item.webkitGetAsEntry) {
  61760. entry = item.webkitGetAsEntry();
  61761. }
  61762. }
  61763. if (!entry) {
  61764. files_1.push(fileToLoad);
  61765. }
  61766. else {
  61767. if (entry.isDirectory) {
  61768. folders.push(entry);
  61769. }
  61770. else {
  61771. files_1.push(fileToLoad);
  61772. }
  61773. }
  61774. }
  61775. if (folders.length === 0) {
  61776. this._processFiles(files_1);
  61777. this._processReload();
  61778. }
  61779. else {
  61780. var remaining = { count: folders.length };
  61781. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61782. var folder = folders_1[_i];
  61783. this._traverseFolder(folder, files_1, remaining, function () {
  61784. _this._processFiles(files_1);
  61785. if (remaining.count === 0) {
  61786. _this._processReload();
  61787. }
  61788. });
  61789. }
  61790. }
  61791. }
  61792. };
  61793. FilesInput.prototype._processReload = function () {
  61794. if (this._onReloadCallback) {
  61795. this._onReloadCallback(this._sceneFileToLoad);
  61796. }
  61797. else {
  61798. this.reload();
  61799. }
  61800. };
  61801. FilesInput.prototype.reload = function () {
  61802. var _this = this;
  61803. // If a scene file has been provided
  61804. if (this._sceneFileToLoad) {
  61805. if (this._currentScene) {
  61806. if (BABYLON.Tools.errorsCount > 0) {
  61807. BABYLON.Tools.ClearLogCache();
  61808. }
  61809. this._engine.stopRenderLoop();
  61810. this._currentScene.dispose();
  61811. }
  61812. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61813. if (_this._progressCallback) {
  61814. _this._progressCallback(progress);
  61815. }
  61816. }).then(function (scene) {
  61817. _this._currentScene = scene;
  61818. if (_this._sceneLoadedCallback) {
  61819. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61820. }
  61821. // Wait for textures and shaders to be ready
  61822. _this._currentScene.executeWhenReady(function () {
  61823. _this._engine.runRenderLoop(function () {
  61824. _this.renderFunction();
  61825. });
  61826. });
  61827. }).catch(function (error) {
  61828. if (_this._errorCallback) {
  61829. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61830. }
  61831. });
  61832. }
  61833. else {
  61834. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61835. }
  61836. };
  61837. FilesInput.FilesToLoad = {};
  61838. return FilesInput;
  61839. }());
  61840. BABYLON.FilesInput = FilesInput;
  61841. })(BABYLON || (BABYLON = {}));
  61842. //# sourceMappingURL=babylon.filesInput.js.map
  61843. var BABYLON;
  61844. (function (BABYLON) {
  61845. /**
  61846. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61847. * The underlying implementation relies on an associative array to ensure the best performances.
  61848. * The value can be anything including 'null' but except 'undefined'
  61849. */
  61850. var StringDictionary = /** @class */ (function () {
  61851. function StringDictionary() {
  61852. this._count = 0;
  61853. this._data = {};
  61854. }
  61855. /**
  61856. * This will clear this dictionary and copy the content from the 'source' one.
  61857. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61858. * @param source the dictionary to take the content from and copy to this dictionary
  61859. */
  61860. StringDictionary.prototype.copyFrom = function (source) {
  61861. var _this = this;
  61862. this.clear();
  61863. source.forEach(function (t, v) { return _this.add(t, v); });
  61864. };
  61865. /**
  61866. * Get a value based from its key
  61867. * @param key the given key to get the matching value from
  61868. * @return the value if found, otherwise undefined is returned
  61869. */
  61870. StringDictionary.prototype.get = function (key) {
  61871. var val = this._data[key];
  61872. if (val !== undefined) {
  61873. return val;
  61874. }
  61875. return undefined;
  61876. };
  61877. /**
  61878. * Get a value from its key or add it if it doesn't exist.
  61879. * This method will ensure you that a given key/data will be present in the dictionary.
  61880. * @param key the given key to get the matching value from
  61881. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61882. * The factory will only be invoked if there's no data for the given key.
  61883. * @return the value corresponding to the key.
  61884. */
  61885. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61886. var val = this.get(key);
  61887. if (val !== undefined) {
  61888. return val;
  61889. }
  61890. val = factory(key);
  61891. if (val) {
  61892. this.add(key, val);
  61893. }
  61894. return val;
  61895. };
  61896. /**
  61897. * Get a value from its key if present in the dictionary otherwise add it
  61898. * @param key the key to get the value from
  61899. * @param val if there's no such key/value pair in the dictionary add it with this value
  61900. * @return the value corresponding to the key
  61901. */
  61902. StringDictionary.prototype.getOrAdd = function (key, val) {
  61903. var curVal = this.get(key);
  61904. if (curVal !== undefined) {
  61905. return curVal;
  61906. }
  61907. this.add(key, val);
  61908. return val;
  61909. };
  61910. /**
  61911. * Check if there's a given key in the dictionary
  61912. * @param key the key to check for
  61913. * @return true if the key is present, false otherwise
  61914. */
  61915. StringDictionary.prototype.contains = function (key) {
  61916. return this._data[key] !== undefined;
  61917. };
  61918. /**
  61919. * Add a new key and its corresponding value
  61920. * @param key the key to add
  61921. * @param value the value corresponding to the key
  61922. * @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
  61923. */
  61924. StringDictionary.prototype.add = function (key, value) {
  61925. if (this._data[key] !== undefined) {
  61926. return false;
  61927. }
  61928. this._data[key] = value;
  61929. ++this._count;
  61930. return true;
  61931. };
  61932. StringDictionary.prototype.set = function (key, value) {
  61933. if (this._data[key] === undefined) {
  61934. return false;
  61935. }
  61936. this._data[key] = value;
  61937. return true;
  61938. };
  61939. /**
  61940. * Get the element of the given key and remove it from the dictionary
  61941. * @param key
  61942. */
  61943. StringDictionary.prototype.getAndRemove = function (key) {
  61944. var val = this.get(key);
  61945. if (val !== undefined) {
  61946. delete this._data[key];
  61947. --this._count;
  61948. return val;
  61949. }
  61950. return null;
  61951. };
  61952. /**
  61953. * Remove a key/value from the dictionary.
  61954. * @param key the key to remove
  61955. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61956. */
  61957. StringDictionary.prototype.remove = function (key) {
  61958. if (this.contains(key)) {
  61959. delete this._data[key];
  61960. --this._count;
  61961. return true;
  61962. }
  61963. return false;
  61964. };
  61965. /**
  61966. * Clear the whole content of the dictionary
  61967. */
  61968. StringDictionary.prototype.clear = function () {
  61969. this._data = {};
  61970. this._count = 0;
  61971. };
  61972. Object.defineProperty(StringDictionary.prototype, "count", {
  61973. get: function () {
  61974. return this._count;
  61975. },
  61976. enumerable: true,
  61977. configurable: true
  61978. });
  61979. /**
  61980. * Execute a callback on each key/val of the dictionary.
  61981. * Note that you can remove any element in this dictionary in the callback implementation
  61982. * @param callback the callback to execute on a given key/value pair
  61983. */
  61984. StringDictionary.prototype.forEach = function (callback) {
  61985. for (var cur in this._data) {
  61986. var val = this._data[cur];
  61987. callback(cur, val);
  61988. }
  61989. };
  61990. /**
  61991. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61992. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61993. * Note that you can remove any element in this dictionary in the callback implementation
  61994. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61995. */
  61996. StringDictionary.prototype.first = function (callback) {
  61997. for (var cur in this._data) {
  61998. var val = this._data[cur];
  61999. var res = callback(cur, val);
  62000. if (res) {
  62001. return res;
  62002. }
  62003. }
  62004. return null;
  62005. };
  62006. return StringDictionary;
  62007. }());
  62008. BABYLON.StringDictionary = StringDictionary;
  62009. })(BABYLON || (BABYLON = {}));
  62010. //# sourceMappingURL=babylon.stringDictionary.js.map
  62011. var BABYLON;
  62012. (function (BABYLON) {
  62013. var Tags = /** @class */ (function () {
  62014. function Tags() {
  62015. }
  62016. Tags.EnableFor = function (obj) {
  62017. obj._tags = obj._tags || {};
  62018. obj.hasTags = function () {
  62019. return Tags.HasTags(obj);
  62020. };
  62021. obj.addTags = function (tagsString) {
  62022. return Tags.AddTagsTo(obj, tagsString);
  62023. };
  62024. obj.removeTags = function (tagsString) {
  62025. return Tags.RemoveTagsFrom(obj, tagsString);
  62026. };
  62027. obj.matchesTagsQuery = function (tagsQuery) {
  62028. return Tags.MatchesQuery(obj, tagsQuery);
  62029. };
  62030. };
  62031. Tags.DisableFor = function (obj) {
  62032. delete obj._tags;
  62033. delete obj.hasTags;
  62034. delete obj.addTags;
  62035. delete obj.removeTags;
  62036. delete obj.matchesTagsQuery;
  62037. };
  62038. Tags.HasTags = function (obj) {
  62039. if (!obj._tags) {
  62040. return false;
  62041. }
  62042. return !BABYLON.Tools.IsEmpty(obj._tags);
  62043. };
  62044. Tags.GetTags = function (obj, asString) {
  62045. if (asString === void 0) { asString = true; }
  62046. if (!obj._tags) {
  62047. return null;
  62048. }
  62049. if (asString) {
  62050. var tagsArray = [];
  62051. for (var tag in obj._tags) {
  62052. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62053. tagsArray.push(tag);
  62054. }
  62055. }
  62056. return tagsArray.join(" ");
  62057. }
  62058. else {
  62059. return obj._tags;
  62060. }
  62061. };
  62062. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62063. // a tag cannot start with '||', '&&', and '!'
  62064. // it cannot contain whitespaces
  62065. Tags.AddTagsTo = function (obj, tagsString) {
  62066. if (!tagsString) {
  62067. return;
  62068. }
  62069. if (typeof tagsString !== "string") {
  62070. return;
  62071. }
  62072. var tags = tagsString.split(" ");
  62073. tags.forEach(function (tag, index, array) {
  62074. Tags._AddTagTo(obj, tag);
  62075. });
  62076. };
  62077. Tags._AddTagTo = function (obj, tag) {
  62078. tag = tag.trim();
  62079. if (tag === "" || tag === "true" || tag === "false") {
  62080. return;
  62081. }
  62082. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62083. return;
  62084. }
  62085. Tags.EnableFor(obj);
  62086. obj._tags[tag] = true;
  62087. };
  62088. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62089. if (!Tags.HasTags(obj)) {
  62090. return;
  62091. }
  62092. var tags = tagsString.split(" ");
  62093. for (var t in tags) {
  62094. Tags._RemoveTagFrom(obj, tags[t]);
  62095. }
  62096. };
  62097. Tags._RemoveTagFrom = function (obj, tag) {
  62098. delete obj._tags[tag];
  62099. };
  62100. Tags.MatchesQuery = function (obj, tagsQuery) {
  62101. if (tagsQuery === undefined) {
  62102. return true;
  62103. }
  62104. if (tagsQuery === "") {
  62105. return Tags.HasTags(obj);
  62106. }
  62107. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62108. };
  62109. return Tags;
  62110. }());
  62111. BABYLON.Tags = Tags;
  62112. })(BABYLON || (BABYLON = {}));
  62113. //# sourceMappingURL=babylon.tags.js.map
  62114. var BABYLON;
  62115. (function (BABYLON) {
  62116. var AndOrNotEvaluator = /** @class */ (function () {
  62117. function AndOrNotEvaluator() {
  62118. }
  62119. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62120. if (!query.match(/\([^\(\)]*\)/g)) {
  62121. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62122. }
  62123. else {
  62124. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62125. // remove parenthesis
  62126. r = r.slice(1, r.length - 1);
  62127. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62128. });
  62129. }
  62130. if (query === "true") {
  62131. return true;
  62132. }
  62133. if (query === "false") {
  62134. return false;
  62135. }
  62136. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62137. };
  62138. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62139. evaluateCallback = evaluateCallback || (function (r) {
  62140. return r === "true" ? true : false;
  62141. });
  62142. var result;
  62143. var or = parenthesisContent.split("||");
  62144. for (var i in or) {
  62145. if (or.hasOwnProperty(i)) {
  62146. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62147. var and = ori.split("&&");
  62148. if (and.length > 1) {
  62149. for (var j = 0; j < and.length; ++j) {
  62150. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62151. if (andj !== "true" && andj !== "false") {
  62152. if (andj[0] === "!") {
  62153. result = !evaluateCallback(andj.substring(1));
  62154. }
  62155. else {
  62156. result = evaluateCallback(andj);
  62157. }
  62158. }
  62159. else {
  62160. result = andj === "true" ? true : false;
  62161. }
  62162. if (!result) {
  62163. ori = "false";
  62164. break;
  62165. }
  62166. }
  62167. }
  62168. if (result || ori === "true") {
  62169. result = true;
  62170. break;
  62171. }
  62172. // result equals false (or undefined)
  62173. if (ori !== "true" && ori !== "false") {
  62174. if (ori[0] === "!") {
  62175. result = !evaluateCallback(ori.substring(1));
  62176. }
  62177. else {
  62178. result = evaluateCallback(ori);
  62179. }
  62180. }
  62181. else {
  62182. result = ori === "true" ? true : false;
  62183. }
  62184. }
  62185. }
  62186. // the whole parenthesis scope is replaced by 'true' or 'false'
  62187. return result ? "true" : "false";
  62188. };
  62189. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62190. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62191. // remove whitespaces
  62192. r = r.replace(/[\s]/g, function () { return ""; });
  62193. return r.length % 2 ? "!" : "";
  62194. });
  62195. booleanString = booleanString.trim();
  62196. if (booleanString === "!true") {
  62197. booleanString = "false";
  62198. }
  62199. else if (booleanString === "!false") {
  62200. booleanString = "true";
  62201. }
  62202. return booleanString;
  62203. };
  62204. return AndOrNotEvaluator;
  62205. }());
  62206. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62207. })(BABYLON || (BABYLON = {}));
  62208. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62209. var BABYLON;
  62210. (function (BABYLON) {
  62211. var Database = /** @class */ (function () {
  62212. function Database(urlToScene, callbackManifestChecked) {
  62213. // Handling various flavors of prefixed version of IndexedDB
  62214. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62215. this.callbackManifestChecked = callbackManifestChecked;
  62216. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62217. this.db = null;
  62218. this._enableSceneOffline = false;
  62219. this._enableTexturesOffline = false;
  62220. this.manifestVersionFound = 0;
  62221. this.mustUpdateRessources = false;
  62222. this.hasReachedQuota = false;
  62223. if (!Database.IDBStorageEnabled) {
  62224. this.callbackManifestChecked(true);
  62225. }
  62226. else {
  62227. this.checkManifestFile();
  62228. }
  62229. }
  62230. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62231. get: function () {
  62232. return this._enableSceneOffline;
  62233. },
  62234. enumerable: true,
  62235. configurable: true
  62236. });
  62237. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62238. get: function () {
  62239. return this._enableTexturesOffline;
  62240. },
  62241. enumerable: true,
  62242. configurable: true
  62243. });
  62244. Database.prototype.checkManifestFile = function () {
  62245. var _this = this;
  62246. var noManifestFile = function () {
  62247. _this._enableSceneOffline = false;
  62248. _this._enableTexturesOffline = false;
  62249. _this.callbackManifestChecked(false);
  62250. };
  62251. var timeStampUsed = false;
  62252. var manifestURL = this.currentSceneUrl + ".manifest";
  62253. var xhr = new XMLHttpRequest();
  62254. if (navigator.onLine) {
  62255. // Adding a timestamp to by-pass browsers' cache
  62256. timeStampUsed = true;
  62257. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62258. }
  62259. xhr.open("GET", manifestURL, true);
  62260. xhr.addEventListener("load", function () {
  62261. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62262. try {
  62263. var manifestFile = JSON.parse(xhr.response);
  62264. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62265. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62266. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62267. _this.manifestVersionFound = manifestFile.version;
  62268. }
  62269. if (_this.callbackManifestChecked) {
  62270. _this.callbackManifestChecked(true);
  62271. }
  62272. }
  62273. catch (ex) {
  62274. noManifestFile();
  62275. }
  62276. }
  62277. else {
  62278. noManifestFile();
  62279. }
  62280. }, false);
  62281. xhr.addEventListener("error", function (event) {
  62282. if (timeStampUsed) {
  62283. timeStampUsed = false;
  62284. // Let's retry without the timeStamp
  62285. // It could fail when coupled with HTML5 Offline API
  62286. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62287. xhr.open("GET", retryManifestURL, true);
  62288. xhr.send();
  62289. }
  62290. else {
  62291. noManifestFile();
  62292. }
  62293. }, false);
  62294. try {
  62295. xhr.send();
  62296. }
  62297. catch (ex) {
  62298. BABYLON.Tools.Error("Error on XHR send request.");
  62299. this.callbackManifestChecked(false);
  62300. }
  62301. };
  62302. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62303. var _this = this;
  62304. var handleError = function () {
  62305. _this.isSupported = false;
  62306. if (errorCallback)
  62307. errorCallback();
  62308. };
  62309. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62310. // Your browser doesn't support IndexedDB
  62311. this.isSupported = false;
  62312. if (errorCallback)
  62313. errorCallback();
  62314. }
  62315. else {
  62316. // If the DB hasn't been opened or created yet
  62317. if (!this.db) {
  62318. this.hasReachedQuota = false;
  62319. this.isSupported = true;
  62320. var request = this.idbFactory.open("babylonjs", 1);
  62321. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62322. request.onerror = function (event) {
  62323. handleError();
  62324. };
  62325. // executes when a version change transaction cannot complete due to other active transactions
  62326. request.onblocked = function (event) {
  62327. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62328. handleError();
  62329. };
  62330. // DB has been opened successfully
  62331. request.onsuccess = function (event) {
  62332. _this.db = request.result;
  62333. successCallback();
  62334. };
  62335. // Initialization of the DB. Creating Scenes & Textures stores
  62336. request.onupgradeneeded = function (event) {
  62337. _this.db = (event.target).result;
  62338. if (_this.db) {
  62339. try {
  62340. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62341. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62342. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62343. }
  62344. catch (ex) {
  62345. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62346. handleError();
  62347. }
  62348. }
  62349. };
  62350. }
  62351. else {
  62352. if (successCallback)
  62353. successCallback();
  62354. }
  62355. }
  62356. };
  62357. Database.prototype.loadImageFromDB = function (url, image) {
  62358. var _this = this;
  62359. var completeURL = Database.ReturnFullUrlLocation(url);
  62360. var saveAndLoadImage = function () {
  62361. if (!_this.hasReachedQuota && _this.db !== null) {
  62362. // the texture is not yet in the DB, let's try to save it
  62363. _this._saveImageIntoDBAsync(completeURL, image);
  62364. }
  62365. else {
  62366. image.src = url;
  62367. }
  62368. };
  62369. if (!this.mustUpdateRessources) {
  62370. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62371. }
  62372. else {
  62373. saveAndLoadImage();
  62374. }
  62375. };
  62376. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62377. if (this.isSupported && this.db !== null) {
  62378. var texture;
  62379. var transaction = this.db.transaction(["textures"]);
  62380. transaction.onabort = function (event) {
  62381. image.src = url;
  62382. };
  62383. transaction.oncomplete = function (event) {
  62384. var blobTextureURL;
  62385. if (texture) {
  62386. var URL = window.URL || window.webkitURL;
  62387. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62388. image.onerror = function () {
  62389. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62390. image.src = url;
  62391. };
  62392. image.src = blobTextureURL;
  62393. }
  62394. else {
  62395. notInDBCallback();
  62396. }
  62397. };
  62398. var getRequest = transaction.objectStore("textures").get(url);
  62399. getRequest.onsuccess = function (event) {
  62400. texture = (event.target).result;
  62401. };
  62402. getRequest.onerror = function (event) {
  62403. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62404. image.src = url;
  62405. };
  62406. }
  62407. else {
  62408. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62409. image.src = url;
  62410. }
  62411. };
  62412. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62413. var _this = this;
  62414. if (this.isSupported) {
  62415. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62416. var generateBlobUrl = function () {
  62417. var blobTextureURL;
  62418. if (blob) {
  62419. var URL = window.URL || window.webkitURL;
  62420. try {
  62421. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62422. }
  62423. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62424. catch (ex) {
  62425. blobTextureURL = URL.createObjectURL(blob);
  62426. }
  62427. }
  62428. if (blobTextureURL) {
  62429. image.src = blobTextureURL;
  62430. }
  62431. };
  62432. if (Database.IsUASupportingBlobStorage) {
  62433. var xhr = new XMLHttpRequest(), blob;
  62434. xhr.open("GET", url, true);
  62435. xhr.responseType = "blob";
  62436. xhr.addEventListener("load", function () {
  62437. if (xhr.status === 200 && _this.db) {
  62438. // Blob as response (XHR2)
  62439. blob = xhr.response;
  62440. var transaction = _this.db.transaction(["textures"], "readwrite");
  62441. // the transaction could abort because of a QuotaExceededError error
  62442. transaction.onabort = function (event) {
  62443. try {
  62444. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62445. var srcElement = (event.srcElement || event.target);
  62446. var error = srcElement.error;
  62447. if (error && error.name === "QuotaExceededError") {
  62448. _this.hasReachedQuota = true;
  62449. }
  62450. }
  62451. catch (ex) { }
  62452. generateBlobUrl();
  62453. };
  62454. transaction.oncomplete = function (event) {
  62455. generateBlobUrl();
  62456. };
  62457. var newTexture = { textureUrl: url, data: blob };
  62458. try {
  62459. // Put the blob into the dabase
  62460. var addRequest = transaction.objectStore("textures").put(newTexture);
  62461. addRequest.onsuccess = function (event) {
  62462. };
  62463. addRequest.onerror = function (event) {
  62464. generateBlobUrl();
  62465. };
  62466. }
  62467. catch (ex) {
  62468. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62469. if (ex.code === 25) {
  62470. Database.IsUASupportingBlobStorage = false;
  62471. }
  62472. image.src = url;
  62473. }
  62474. }
  62475. else {
  62476. image.src = url;
  62477. }
  62478. }, false);
  62479. xhr.addEventListener("error", function (event) {
  62480. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62481. image.src = url;
  62482. }, false);
  62483. xhr.send();
  62484. }
  62485. else {
  62486. image.src = url;
  62487. }
  62488. }
  62489. else {
  62490. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62491. image.src = url;
  62492. }
  62493. };
  62494. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62495. var _this = this;
  62496. var updateVersion = function () {
  62497. // the version is not yet in the DB or we need to update it
  62498. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62499. };
  62500. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62501. };
  62502. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62503. var _this = this;
  62504. if (this.isSupported && this.db) {
  62505. var version;
  62506. try {
  62507. var transaction = this.db.transaction(["versions"]);
  62508. transaction.oncomplete = function (event) {
  62509. if (version) {
  62510. // If the version in the JSON file is > than the version in DB
  62511. if (_this.manifestVersionFound > version.data) {
  62512. _this.mustUpdateRessources = true;
  62513. updateInDBCallback();
  62514. }
  62515. else {
  62516. callback(version.data);
  62517. }
  62518. }
  62519. else {
  62520. _this.mustUpdateRessources = true;
  62521. updateInDBCallback();
  62522. }
  62523. };
  62524. transaction.onabort = function (event) {
  62525. callback(-1);
  62526. };
  62527. var getRequest = transaction.objectStore("versions").get(url);
  62528. getRequest.onsuccess = function (event) {
  62529. version = (event.target).result;
  62530. };
  62531. getRequest.onerror = function (event) {
  62532. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62533. callback(-1);
  62534. };
  62535. }
  62536. catch (ex) {
  62537. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62538. callback(-1);
  62539. }
  62540. }
  62541. else {
  62542. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62543. callback(-1);
  62544. }
  62545. };
  62546. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62547. var _this = this;
  62548. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62549. try {
  62550. // Open a transaction to the database
  62551. var transaction = this.db.transaction(["versions"], "readwrite");
  62552. // the transaction could abort because of a QuotaExceededError error
  62553. transaction.onabort = function (event) {
  62554. try {
  62555. var error = event.srcElement['error'];
  62556. if (error && error.name === "QuotaExceededError") {
  62557. _this.hasReachedQuota = true;
  62558. }
  62559. }
  62560. catch (ex) { }
  62561. callback(-1);
  62562. };
  62563. transaction.oncomplete = function (event) {
  62564. callback(_this.manifestVersionFound);
  62565. };
  62566. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62567. // Put the scene into the database
  62568. var addRequest = transaction.objectStore("versions").put(newVersion);
  62569. addRequest.onsuccess = function (event) {
  62570. };
  62571. addRequest.onerror = function (event) {
  62572. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62573. };
  62574. }
  62575. catch (ex) {
  62576. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62577. callback(-1);
  62578. }
  62579. }
  62580. else {
  62581. callback(-1);
  62582. }
  62583. };
  62584. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62585. var _this = this;
  62586. var completeUrl = Database.ReturnFullUrlLocation(url);
  62587. var saveAndLoadFile = function () {
  62588. // the scene is not yet in the DB, let's try to save it
  62589. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62590. };
  62591. this._checkVersionFromDB(completeUrl, function (version) {
  62592. if (version !== -1) {
  62593. if (!_this.mustUpdateRessources) {
  62594. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62595. }
  62596. else {
  62597. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62598. }
  62599. }
  62600. else {
  62601. if (errorCallback) {
  62602. errorCallback();
  62603. }
  62604. }
  62605. });
  62606. };
  62607. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62608. if (this.isSupported && this.db) {
  62609. var targetStore;
  62610. if (url.indexOf(".babylon") !== -1) {
  62611. targetStore = "scenes";
  62612. }
  62613. else {
  62614. targetStore = "textures";
  62615. }
  62616. var file;
  62617. var transaction = this.db.transaction([targetStore]);
  62618. transaction.oncomplete = function (event) {
  62619. if (file) {
  62620. callback(file.data);
  62621. }
  62622. else {
  62623. notInDBCallback();
  62624. }
  62625. };
  62626. transaction.onabort = function (event) {
  62627. notInDBCallback();
  62628. };
  62629. var getRequest = transaction.objectStore(targetStore).get(url);
  62630. getRequest.onsuccess = function (event) {
  62631. file = (event.target).result;
  62632. };
  62633. getRequest.onerror = function (event) {
  62634. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62635. notInDBCallback();
  62636. };
  62637. }
  62638. else {
  62639. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62640. callback();
  62641. }
  62642. };
  62643. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62644. var _this = this;
  62645. if (this.isSupported) {
  62646. var targetStore;
  62647. if (url.indexOf(".babylon") !== -1) {
  62648. targetStore = "scenes";
  62649. }
  62650. else {
  62651. targetStore = "textures";
  62652. }
  62653. // Create XHR
  62654. var xhr = new XMLHttpRequest();
  62655. var fileData;
  62656. xhr.open("GET", url, true);
  62657. if (useArrayBuffer) {
  62658. xhr.responseType = "arraybuffer";
  62659. }
  62660. if (progressCallback) {
  62661. xhr.onprogress = progressCallback;
  62662. }
  62663. xhr.addEventListener("load", function () {
  62664. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62665. // Blob as response (XHR2)
  62666. //fileData = xhr.responseText;
  62667. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62668. if (!_this.hasReachedQuota && _this.db) {
  62669. // Open a transaction to the database
  62670. var transaction = _this.db.transaction([targetStore], "readwrite");
  62671. // the transaction could abort because of a QuotaExceededError error
  62672. transaction.onabort = function (event) {
  62673. try {
  62674. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62675. var error = event.srcElement['error'];
  62676. if (error && error.name === "QuotaExceededError") {
  62677. _this.hasReachedQuota = true;
  62678. }
  62679. }
  62680. catch (ex) { }
  62681. callback(fileData);
  62682. };
  62683. transaction.oncomplete = function (event) {
  62684. callback(fileData);
  62685. };
  62686. var newFile;
  62687. if (targetStore === "scenes") {
  62688. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62689. }
  62690. else {
  62691. newFile = { textureUrl: url, data: fileData };
  62692. }
  62693. try {
  62694. // Put the scene into the database
  62695. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62696. addRequest.onsuccess = function (event) {
  62697. };
  62698. addRequest.onerror = function (event) {
  62699. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62700. };
  62701. }
  62702. catch (ex) {
  62703. callback(fileData);
  62704. }
  62705. }
  62706. else {
  62707. callback(fileData);
  62708. }
  62709. }
  62710. else {
  62711. callback();
  62712. }
  62713. }, false);
  62714. xhr.addEventListener("error", function (event) {
  62715. BABYLON.Tools.Error("error on XHR request.");
  62716. callback();
  62717. }, false);
  62718. xhr.send();
  62719. }
  62720. else {
  62721. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62722. callback();
  62723. }
  62724. };
  62725. Database.IsUASupportingBlobStorage = true;
  62726. Database.IDBStorageEnabled = true;
  62727. Database.parseURL = function (url) {
  62728. var a = document.createElement('a');
  62729. a.href = url;
  62730. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62731. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62732. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62733. return absLocation;
  62734. };
  62735. Database.ReturnFullUrlLocation = function (url) {
  62736. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62737. return (Database.parseURL(window.location.href) + url);
  62738. }
  62739. else {
  62740. return url;
  62741. }
  62742. };
  62743. return Database;
  62744. }());
  62745. BABYLON.Database = Database;
  62746. })(BABYLON || (BABYLON = {}));
  62747. //# sourceMappingURL=babylon.database.js.map
  62748. var BABYLON;
  62749. (function (BABYLON) {
  62750. var FresnelParameters = /** @class */ (function () {
  62751. function FresnelParameters() {
  62752. this._isEnabled = true;
  62753. this.leftColor = BABYLON.Color3.White();
  62754. this.rightColor = BABYLON.Color3.Black();
  62755. this.bias = 0;
  62756. this.power = 1;
  62757. }
  62758. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62759. get: function () {
  62760. return this._isEnabled;
  62761. },
  62762. set: function (value) {
  62763. if (this._isEnabled === value) {
  62764. return;
  62765. }
  62766. this._isEnabled = value;
  62767. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62768. },
  62769. enumerable: true,
  62770. configurable: true
  62771. });
  62772. FresnelParameters.prototype.clone = function () {
  62773. var newFresnelParameters = new FresnelParameters();
  62774. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62775. return newFresnelParameters;
  62776. };
  62777. FresnelParameters.prototype.serialize = function () {
  62778. var serializationObject = {};
  62779. serializationObject.isEnabled = this.isEnabled;
  62780. serializationObject.leftColor = this.leftColor;
  62781. serializationObject.rightColor = this.rightColor;
  62782. serializationObject.bias = this.bias;
  62783. serializationObject.power = this.power;
  62784. return serializationObject;
  62785. };
  62786. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62787. var fresnelParameters = new FresnelParameters();
  62788. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62789. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62790. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62791. fresnelParameters.bias = parsedFresnelParameters.bias;
  62792. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62793. return fresnelParameters;
  62794. };
  62795. return FresnelParameters;
  62796. }());
  62797. BABYLON.FresnelParameters = FresnelParameters;
  62798. })(BABYLON || (BABYLON = {}));
  62799. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62800. var BABYLON;
  62801. (function (BABYLON) {
  62802. var MultiMaterial = /** @class */ (function (_super) {
  62803. __extends(MultiMaterial, _super);
  62804. function MultiMaterial(name, scene) {
  62805. var _this = _super.call(this, name, scene, true) || this;
  62806. scene.multiMaterials.push(_this);
  62807. _this.subMaterials = new Array();
  62808. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62809. return _this;
  62810. }
  62811. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62812. get: function () {
  62813. return this._subMaterials;
  62814. },
  62815. set: function (value) {
  62816. this._subMaterials = value;
  62817. this._hookArray(value);
  62818. },
  62819. enumerable: true,
  62820. configurable: true
  62821. });
  62822. MultiMaterial.prototype._hookArray = function (array) {
  62823. var _this = this;
  62824. var oldPush = array.push;
  62825. array.push = function () {
  62826. var items = [];
  62827. for (var _i = 0; _i < arguments.length; _i++) {
  62828. items[_i] = arguments[_i];
  62829. }
  62830. var result = oldPush.apply(array, items);
  62831. _this._markAllSubMeshesAsTexturesDirty();
  62832. return result;
  62833. };
  62834. var oldSplice = array.splice;
  62835. array.splice = function (index, deleteCount) {
  62836. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62837. _this._markAllSubMeshesAsTexturesDirty();
  62838. return deleted;
  62839. };
  62840. };
  62841. // Properties
  62842. MultiMaterial.prototype.getSubMaterial = function (index) {
  62843. if (index < 0 || index >= this.subMaterials.length) {
  62844. return this.getScene().defaultMaterial;
  62845. }
  62846. return this.subMaterials[index];
  62847. };
  62848. MultiMaterial.prototype.getActiveTextures = function () {
  62849. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62850. if (subMaterial) {
  62851. return subMaterial.getActiveTextures();
  62852. }
  62853. else {
  62854. return [];
  62855. }
  62856. }));
  62857. var _a;
  62858. };
  62859. // Methods
  62860. MultiMaterial.prototype.getClassName = function () {
  62861. return "MultiMaterial";
  62862. };
  62863. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62864. for (var index = 0; index < this.subMaterials.length; index++) {
  62865. var subMaterial = this.subMaterials[index];
  62866. if (subMaterial) {
  62867. if (subMaterial.storeEffectOnSubMeshes) {
  62868. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62869. return false;
  62870. }
  62871. continue;
  62872. }
  62873. if (!subMaterial.isReady(mesh)) {
  62874. return false;
  62875. }
  62876. }
  62877. }
  62878. return true;
  62879. };
  62880. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62881. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62882. for (var index = 0; index < this.subMaterials.length; index++) {
  62883. var subMaterial = null;
  62884. var current = this.subMaterials[index];
  62885. if (cloneChildren && current) {
  62886. subMaterial = current.clone(name + "-" + current.name);
  62887. }
  62888. else {
  62889. subMaterial = this.subMaterials[index];
  62890. }
  62891. newMultiMaterial.subMaterials.push(subMaterial);
  62892. }
  62893. return newMultiMaterial;
  62894. };
  62895. MultiMaterial.prototype.serialize = function () {
  62896. var serializationObject = {};
  62897. serializationObject.name = this.name;
  62898. serializationObject.id = this.id;
  62899. if (BABYLON.Tags) {
  62900. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62901. }
  62902. serializationObject.materials = [];
  62903. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62904. var subMat = this.subMaterials[matIndex];
  62905. if (subMat) {
  62906. serializationObject.materials.push(subMat.id);
  62907. }
  62908. else {
  62909. serializationObject.materials.push(null);
  62910. }
  62911. }
  62912. return serializationObject;
  62913. };
  62914. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62915. var scene = this.getScene();
  62916. if (!scene) {
  62917. return;
  62918. }
  62919. var index = scene.multiMaterials.indexOf(this);
  62920. if (index >= 0) {
  62921. scene.multiMaterials.splice(index, 1);
  62922. }
  62923. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62924. };
  62925. return MultiMaterial;
  62926. }(BABYLON.Material));
  62927. BABYLON.MultiMaterial = MultiMaterial;
  62928. })(BABYLON || (BABYLON = {}));
  62929. //# sourceMappingURL=babylon.multiMaterial.js.map
  62930. var BABYLON;
  62931. (function (BABYLON) {
  62932. var FreeCameraTouchInput = /** @class */ (function () {
  62933. function FreeCameraTouchInput() {
  62934. this._offsetX = null;
  62935. this._offsetY = null;
  62936. this._pointerPressed = new Array();
  62937. this.touchAngularSensibility = 200000.0;
  62938. this.touchMoveSensibility = 250.0;
  62939. }
  62940. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62941. var _this = this;
  62942. var previousPosition = null;
  62943. if (this._pointerInput === undefined) {
  62944. this._onLostFocus = function (evt) {
  62945. _this._offsetX = null;
  62946. _this._offsetY = null;
  62947. };
  62948. this._pointerInput = function (p, s) {
  62949. var evt = p.event;
  62950. if (evt.pointerType === "mouse") {
  62951. return;
  62952. }
  62953. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62954. if (!noPreventDefault) {
  62955. evt.preventDefault();
  62956. }
  62957. _this._pointerPressed.push(evt.pointerId);
  62958. if (_this._pointerPressed.length !== 1) {
  62959. return;
  62960. }
  62961. previousPosition = {
  62962. x: evt.clientX,
  62963. y: evt.clientY
  62964. };
  62965. }
  62966. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62967. if (!noPreventDefault) {
  62968. evt.preventDefault();
  62969. }
  62970. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62971. if (index === -1) {
  62972. return;
  62973. }
  62974. _this._pointerPressed.splice(index, 1);
  62975. if (index != 0) {
  62976. return;
  62977. }
  62978. previousPosition = null;
  62979. _this._offsetX = null;
  62980. _this._offsetY = null;
  62981. }
  62982. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62983. if (!noPreventDefault) {
  62984. evt.preventDefault();
  62985. }
  62986. if (!previousPosition) {
  62987. return;
  62988. }
  62989. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62990. if (index != 0) {
  62991. return;
  62992. }
  62993. _this._offsetX = evt.clientX - previousPosition.x;
  62994. _this._offsetY = -(evt.clientY - previousPosition.y);
  62995. }
  62996. };
  62997. }
  62998. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62999. if (this._onLostFocus) {
  63000. element.addEventListener("blur", this._onLostFocus);
  63001. }
  63002. };
  63003. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63004. if (this._pointerInput && element) {
  63005. if (this._observer) {
  63006. this.camera.getScene().onPointerObservable.remove(this._observer);
  63007. this._observer = null;
  63008. }
  63009. if (this._onLostFocus) {
  63010. element.removeEventListener("blur", this._onLostFocus);
  63011. this._onLostFocus = null;
  63012. }
  63013. this._pointerPressed = [];
  63014. this._offsetX = null;
  63015. this._offsetY = null;
  63016. }
  63017. };
  63018. FreeCameraTouchInput.prototype.checkInputs = function () {
  63019. if (this._offsetX && this._offsetY) {
  63020. var camera = this.camera;
  63021. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63022. if (this._pointerPressed.length > 1) {
  63023. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63024. }
  63025. else {
  63026. var speed = camera._computeLocalCameraSpeed();
  63027. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63028. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63029. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63030. }
  63031. }
  63032. };
  63033. FreeCameraTouchInput.prototype.getClassName = function () {
  63034. return "FreeCameraTouchInput";
  63035. };
  63036. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63037. return "touch";
  63038. };
  63039. __decorate([
  63040. BABYLON.serialize()
  63041. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63042. __decorate([
  63043. BABYLON.serialize()
  63044. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63045. return FreeCameraTouchInput;
  63046. }());
  63047. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63048. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63049. })(BABYLON || (BABYLON = {}));
  63050. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63051. var BABYLON;
  63052. (function (BABYLON) {
  63053. // We're mainly based on the logic defined into the FreeCamera code
  63054. var TouchCamera = /** @class */ (function (_super) {
  63055. __extends(TouchCamera, _super);
  63056. //-- end properties for backward compatibility for inputs
  63057. function TouchCamera(name, position, scene) {
  63058. var _this = _super.call(this, name, position, scene) || this;
  63059. _this.inputs.addTouch();
  63060. _this._setupInputs();
  63061. return _this;
  63062. }
  63063. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63064. //-- Begin properties for backward compatibility for inputs
  63065. get: function () {
  63066. var touch = this.inputs.attached["touch"];
  63067. if (touch)
  63068. return touch.touchAngularSensibility;
  63069. return 0;
  63070. },
  63071. set: function (value) {
  63072. var touch = this.inputs.attached["touch"];
  63073. if (touch)
  63074. touch.touchAngularSensibility = value;
  63075. },
  63076. enumerable: true,
  63077. configurable: true
  63078. });
  63079. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63080. get: function () {
  63081. var touch = this.inputs.attached["touch"];
  63082. if (touch)
  63083. return touch.touchMoveSensibility;
  63084. return 0;
  63085. },
  63086. set: function (value) {
  63087. var touch = this.inputs.attached["touch"];
  63088. if (touch)
  63089. touch.touchMoveSensibility = value;
  63090. },
  63091. enumerable: true,
  63092. configurable: true
  63093. });
  63094. TouchCamera.prototype.getClassName = function () {
  63095. return "TouchCamera";
  63096. };
  63097. TouchCamera.prototype._setupInputs = function () {
  63098. var mouse = this.inputs.attached["mouse"];
  63099. if (mouse) {
  63100. mouse.touchEnabled = false;
  63101. }
  63102. };
  63103. return TouchCamera;
  63104. }(BABYLON.FreeCamera));
  63105. BABYLON.TouchCamera = TouchCamera;
  63106. })(BABYLON || (BABYLON = {}));
  63107. //# sourceMappingURL=babylon.touchCamera.js.map
  63108. var BABYLON;
  63109. (function (BABYLON) {
  63110. var ProceduralTexture = /** @class */ (function (_super) {
  63111. __extends(ProceduralTexture, _super);
  63112. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63113. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63114. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63115. if (isCube === void 0) { isCube = false; }
  63116. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63117. _this.isCube = isCube;
  63118. _this.isEnabled = true;
  63119. _this._currentRefreshId = -1;
  63120. _this._refreshRate = 1;
  63121. _this._vertexBuffers = {};
  63122. _this._uniforms = new Array();
  63123. _this._samplers = new Array();
  63124. _this._textures = {};
  63125. _this._floats = {};
  63126. _this._floatsArrays = {};
  63127. _this._colors3 = {};
  63128. _this._colors4 = {};
  63129. _this._vectors2 = {};
  63130. _this._vectors3 = {};
  63131. _this._matrices = {};
  63132. _this._fallbackTextureUsed = false;
  63133. scene._proceduralTextures.push(_this);
  63134. _this._engine = scene.getEngine();
  63135. _this.name = name;
  63136. _this.isRenderTarget = true;
  63137. _this._size = size;
  63138. _this._generateMipMaps = generateMipMaps;
  63139. _this.setFragment(fragment);
  63140. _this._fallbackTexture = fallbackTexture;
  63141. if (isCube) {
  63142. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63143. _this.setFloat("face", 0);
  63144. }
  63145. else {
  63146. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63147. }
  63148. // VBO
  63149. var vertices = [];
  63150. vertices.push(1, 1);
  63151. vertices.push(-1, 1);
  63152. vertices.push(-1, -1);
  63153. vertices.push(1, -1);
  63154. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63155. _this._createIndexBuffer();
  63156. return _this;
  63157. }
  63158. ProceduralTexture.prototype._createIndexBuffer = function () {
  63159. var engine = this._engine;
  63160. // Indices
  63161. var indices = [];
  63162. indices.push(0);
  63163. indices.push(1);
  63164. indices.push(2);
  63165. indices.push(0);
  63166. indices.push(2);
  63167. indices.push(3);
  63168. this._indexBuffer = engine.createIndexBuffer(indices);
  63169. };
  63170. ProceduralTexture.prototype._rebuild = function () {
  63171. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63172. if (vb) {
  63173. vb._rebuild();
  63174. }
  63175. this._createIndexBuffer();
  63176. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63177. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63178. }
  63179. };
  63180. ProceduralTexture.prototype.reset = function () {
  63181. if (this._effect === undefined) {
  63182. return;
  63183. }
  63184. var engine = this._engine;
  63185. engine._releaseEffect(this._effect);
  63186. };
  63187. ProceduralTexture.prototype.isReady = function () {
  63188. var _this = this;
  63189. var engine = this._engine;
  63190. var shaders;
  63191. if (!this._fragment) {
  63192. return false;
  63193. }
  63194. if (this._fallbackTextureUsed) {
  63195. return true;
  63196. }
  63197. if (this._fragment.fragmentElement !== undefined) {
  63198. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63199. }
  63200. else {
  63201. shaders = { vertex: "procedural", fragment: this._fragment };
  63202. }
  63203. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63204. _this.releaseInternalTexture();
  63205. if (_this._fallbackTexture) {
  63206. _this._texture = _this._fallbackTexture._texture;
  63207. if (_this._texture) {
  63208. _this._texture.incrementReferences();
  63209. }
  63210. }
  63211. _this._fallbackTextureUsed = true;
  63212. });
  63213. return this._effect.isReady();
  63214. };
  63215. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63216. this._currentRefreshId = -1;
  63217. };
  63218. ProceduralTexture.prototype.setFragment = function (fragment) {
  63219. this._fragment = fragment;
  63220. };
  63221. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63222. get: function () {
  63223. return this._refreshRate;
  63224. },
  63225. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63226. set: function (value) {
  63227. this._refreshRate = value;
  63228. this.resetRefreshCounter();
  63229. },
  63230. enumerable: true,
  63231. configurable: true
  63232. });
  63233. ProceduralTexture.prototype._shouldRender = function () {
  63234. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63235. return false;
  63236. }
  63237. if (this._fallbackTextureUsed) {
  63238. return false;
  63239. }
  63240. if (this._currentRefreshId === -1) {
  63241. this._currentRefreshId = 1;
  63242. return true;
  63243. }
  63244. if (this.refreshRate === this._currentRefreshId) {
  63245. this._currentRefreshId = 1;
  63246. return true;
  63247. }
  63248. this._currentRefreshId++;
  63249. return false;
  63250. };
  63251. ProceduralTexture.prototype.getRenderSize = function () {
  63252. return this._size;
  63253. };
  63254. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63255. if (this._fallbackTextureUsed) {
  63256. return;
  63257. }
  63258. this.releaseInternalTexture();
  63259. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63260. };
  63261. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63262. if (this._uniforms.indexOf(uniformName) === -1) {
  63263. this._uniforms.push(uniformName);
  63264. }
  63265. };
  63266. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63267. if (this._samplers.indexOf(name) === -1) {
  63268. this._samplers.push(name);
  63269. }
  63270. this._textures[name] = texture;
  63271. return this;
  63272. };
  63273. ProceduralTexture.prototype.setFloat = function (name, value) {
  63274. this._checkUniform(name);
  63275. this._floats[name] = value;
  63276. return this;
  63277. };
  63278. ProceduralTexture.prototype.setFloats = function (name, value) {
  63279. this._checkUniform(name);
  63280. this._floatsArrays[name] = value;
  63281. return this;
  63282. };
  63283. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63284. this._checkUniform(name);
  63285. this._colors3[name] = value;
  63286. return this;
  63287. };
  63288. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63289. this._checkUniform(name);
  63290. this._colors4[name] = value;
  63291. return this;
  63292. };
  63293. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63294. this._checkUniform(name);
  63295. this._vectors2[name] = value;
  63296. return this;
  63297. };
  63298. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63299. this._checkUniform(name);
  63300. this._vectors3[name] = value;
  63301. return this;
  63302. };
  63303. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63304. this._checkUniform(name);
  63305. this._matrices[name] = value;
  63306. return this;
  63307. };
  63308. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63309. var scene = this.getScene();
  63310. if (!scene) {
  63311. return;
  63312. }
  63313. var engine = this._engine;
  63314. // Render
  63315. engine.enableEffect(this._effect);
  63316. engine.setState(false);
  63317. // Texture
  63318. for (var name in this._textures) {
  63319. this._effect.setTexture(name, this._textures[name]);
  63320. }
  63321. // Float
  63322. for (name in this._floats) {
  63323. this._effect.setFloat(name, this._floats[name]);
  63324. }
  63325. // Floats
  63326. for (name in this._floatsArrays) {
  63327. this._effect.setArray(name, this._floatsArrays[name]);
  63328. }
  63329. // Color3
  63330. for (name in this._colors3) {
  63331. this._effect.setColor3(name, this._colors3[name]);
  63332. }
  63333. // Color4
  63334. for (name in this._colors4) {
  63335. var color = this._colors4[name];
  63336. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63337. }
  63338. // Vector2
  63339. for (name in this._vectors2) {
  63340. this._effect.setVector2(name, this._vectors2[name]);
  63341. }
  63342. // Vector3
  63343. for (name in this._vectors3) {
  63344. this._effect.setVector3(name, this._vectors3[name]);
  63345. }
  63346. // Matrix
  63347. for (name in this._matrices) {
  63348. this._effect.setMatrix(name, this._matrices[name]);
  63349. }
  63350. if (!this._texture) {
  63351. return;
  63352. }
  63353. if (this.isCube) {
  63354. for (var face = 0; face < 6; face++) {
  63355. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63356. // VBOs
  63357. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63358. this._effect.setFloat("face", face);
  63359. // Clear
  63360. engine.clear(scene.clearColor, true, true, true);
  63361. // Draw order
  63362. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63363. // Mipmaps
  63364. if (face === 5) {
  63365. engine.generateMipMapsForCubemap(this._texture);
  63366. }
  63367. }
  63368. }
  63369. else {
  63370. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63371. // VBOs
  63372. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63373. // Clear
  63374. engine.clear(scene.clearColor, true, true, true);
  63375. // Draw order
  63376. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63377. }
  63378. // Unbind
  63379. engine.unBindFramebuffer(this._texture, this.isCube);
  63380. if (this.onGenerated) {
  63381. this.onGenerated();
  63382. }
  63383. };
  63384. ProceduralTexture.prototype.clone = function () {
  63385. var textureSize = this.getSize();
  63386. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63387. // Base texture
  63388. newTexture.hasAlpha = this.hasAlpha;
  63389. newTexture.level = this.level;
  63390. // RenderTarget Texture
  63391. newTexture.coordinatesMode = this.coordinatesMode;
  63392. return newTexture;
  63393. };
  63394. ProceduralTexture.prototype.dispose = function () {
  63395. var scene = this.getScene();
  63396. if (!scene) {
  63397. return;
  63398. }
  63399. var index = scene._proceduralTextures.indexOf(this);
  63400. if (index >= 0) {
  63401. scene._proceduralTextures.splice(index, 1);
  63402. }
  63403. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63404. if (vertexBuffer) {
  63405. vertexBuffer.dispose();
  63406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63407. }
  63408. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63409. this._indexBuffer = null;
  63410. }
  63411. _super.prototype.dispose.call(this);
  63412. };
  63413. return ProceduralTexture;
  63414. }(BABYLON.Texture));
  63415. BABYLON.ProceduralTexture = ProceduralTexture;
  63416. })(BABYLON || (BABYLON = {}));
  63417. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63418. var BABYLON;
  63419. (function (BABYLON) {
  63420. var CustomProceduralTexture = /** @class */ (function (_super) {
  63421. __extends(CustomProceduralTexture, _super);
  63422. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63423. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63424. _this._animate = true;
  63425. _this._time = 0;
  63426. _this._texturePath = texturePath;
  63427. //Try to load json
  63428. _this.loadJson(texturePath);
  63429. _this.refreshRate = 1;
  63430. return _this;
  63431. }
  63432. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63433. var _this = this;
  63434. var noConfigFile = function () {
  63435. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63436. try {
  63437. _this.setFragment(_this._texturePath);
  63438. }
  63439. catch (ex) {
  63440. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63441. }
  63442. };
  63443. var configFileUrl = jsonUrl + "/config.json";
  63444. var xhr = new XMLHttpRequest();
  63445. xhr.open("GET", configFileUrl, true);
  63446. xhr.addEventListener("load", function () {
  63447. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63448. try {
  63449. _this._config = JSON.parse(xhr.response);
  63450. _this.updateShaderUniforms();
  63451. _this.updateTextures();
  63452. _this.setFragment(_this._texturePath + "/custom");
  63453. _this._animate = _this._config.animate;
  63454. _this.refreshRate = _this._config.refreshrate;
  63455. }
  63456. catch (ex) {
  63457. noConfigFile();
  63458. }
  63459. }
  63460. else {
  63461. noConfigFile();
  63462. }
  63463. }, false);
  63464. xhr.addEventListener("error", function () {
  63465. noConfigFile();
  63466. }, false);
  63467. try {
  63468. xhr.send();
  63469. }
  63470. catch (ex) {
  63471. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63472. }
  63473. };
  63474. CustomProceduralTexture.prototype.isReady = function () {
  63475. if (!_super.prototype.isReady.call(this)) {
  63476. return false;
  63477. }
  63478. for (var name in this._textures) {
  63479. var texture = this._textures[name];
  63480. if (!texture.isReady()) {
  63481. return false;
  63482. }
  63483. }
  63484. return true;
  63485. };
  63486. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63487. var scene = this.getScene();
  63488. if (this._animate && scene) {
  63489. this._time += scene.getAnimationRatio() * 0.03;
  63490. this.updateShaderUniforms();
  63491. }
  63492. _super.prototype.render.call(this, useCameraPostProcess);
  63493. };
  63494. CustomProceduralTexture.prototype.updateTextures = function () {
  63495. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63496. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63497. }
  63498. };
  63499. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63500. if (this._config) {
  63501. for (var j = 0; j < this._config.uniforms.length; j++) {
  63502. var uniform = this._config.uniforms[j];
  63503. switch (uniform.type) {
  63504. case "float":
  63505. this.setFloat(uniform.name, uniform.value);
  63506. break;
  63507. case "color3":
  63508. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63509. break;
  63510. case "color4":
  63511. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63512. break;
  63513. case "vector2":
  63514. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63515. break;
  63516. case "vector3":
  63517. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63518. break;
  63519. }
  63520. }
  63521. }
  63522. this.setFloat("time", this._time);
  63523. };
  63524. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63525. get: function () {
  63526. return this._animate;
  63527. },
  63528. set: function (value) {
  63529. this._animate = value;
  63530. },
  63531. enumerable: true,
  63532. configurable: true
  63533. });
  63534. return CustomProceduralTexture;
  63535. }(BABYLON.ProceduralTexture));
  63536. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63537. })(BABYLON || (BABYLON = {}));
  63538. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63539. var BABYLON;
  63540. (function (BABYLON) {
  63541. var FreeCameraGamepadInput = /** @class */ (function () {
  63542. function FreeCameraGamepadInput() {
  63543. this.gamepadAngularSensibility = 200;
  63544. this.gamepadMoveSensibility = 40;
  63545. // private members
  63546. this._cameraTransform = BABYLON.Matrix.Identity();
  63547. this._deltaTransform = BABYLON.Vector3.Zero();
  63548. this._vector3 = BABYLON.Vector3.Zero();
  63549. this._vector2 = BABYLON.Vector2.Zero();
  63550. }
  63551. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63552. var _this = this;
  63553. var manager = this.camera.getScene().gamepadManager;
  63554. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63555. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63556. // prioritize XBOX gamepads.
  63557. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63558. _this.gamepad = gamepad;
  63559. }
  63560. }
  63561. });
  63562. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63563. if (_this.gamepad === gamepad) {
  63564. _this.gamepad = null;
  63565. }
  63566. });
  63567. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63568. };
  63569. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63570. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63571. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63572. this.gamepad = null;
  63573. };
  63574. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63575. if (this.gamepad && this.gamepad.leftStick) {
  63576. var camera = this.camera;
  63577. var LSValues = this.gamepad.leftStick;
  63578. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63579. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63580. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63581. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63582. var RSValues = this.gamepad.rightStick;
  63583. if (RSValues) {
  63584. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63585. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63586. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63587. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63588. }
  63589. else {
  63590. RSValues = { x: 0, y: 0 };
  63591. }
  63592. if (!camera.rotationQuaternion) {
  63593. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63594. }
  63595. else {
  63596. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63597. }
  63598. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63599. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63600. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63601. camera.cameraDirection.addInPlace(this._deltaTransform);
  63602. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63603. camera.cameraRotation.addInPlace(this._vector2);
  63604. }
  63605. };
  63606. FreeCameraGamepadInput.prototype.getClassName = function () {
  63607. return "FreeCameraGamepadInput";
  63608. };
  63609. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63610. return "gamepad";
  63611. };
  63612. __decorate([
  63613. BABYLON.serialize()
  63614. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63615. __decorate([
  63616. BABYLON.serialize()
  63617. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63618. return FreeCameraGamepadInput;
  63619. }());
  63620. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63621. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63622. })(BABYLON || (BABYLON = {}));
  63623. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63624. var BABYLON;
  63625. (function (BABYLON) {
  63626. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63627. function ArcRotateCameraGamepadInput() {
  63628. this.gamepadRotationSensibility = 80;
  63629. this.gamepadMoveSensibility = 40;
  63630. }
  63631. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63632. var _this = this;
  63633. var manager = this.camera.getScene().gamepadManager;
  63634. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63635. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63636. // prioritize XBOX gamepads.
  63637. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63638. _this.gamepad = gamepad;
  63639. }
  63640. }
  63641. });
  63642. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63643. if (_this.gamepad === gamepad) {
  63644. _this.gamepad = null;
  63645. }
  63646. });
  63647. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63648. };
  63649. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63650. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63651. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63652. this.gamepad = null;
  63653. };
  63654. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63655. if (this.gamepad) {
  63656. var camera = this.camera;
  63657. var RSValues = this.gamepad.rightStick;
  63658. if (RSValues) {
  63659. if (RSValues.x != 0) {
  63660. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63661. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63662. camera.inertialAlphaOffset += normalizedRX;
  63663. }
  63664. }
  63665. if (RSValues.y != 0) {
  63666. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63667. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63668. camera.inertialBetaOffset += normalizedRY;
  63669. }
  63670. }
  63671. }
  63672. var LSValues = this.gamepad.leftStick;
  63673. if (LSValues && LSValues.y != 0) {
  63674. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63675. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63676. this.camera.inertialRadiusOffset -= normalizedLY;
  63677. }
  63678. }
  63679. }
  63680. };
  63681. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63682. return "ArcRotateCameraGamepadInput";
  63683. };
  63684. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63685. return "gamepad";
  63686. };
  63687. __decorate([
  63688. BABYLON.serialize()
  63689. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63690. __decorate([
  63691. BABYLON.serialize()
  63692. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63693. return ArcRotateCameraGamepadInput;
  63694. }());
  63695. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63696. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63697. })(BABYLON || (BABYLON = {}));
  63698. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63699. var BABYLON;
  63700. (function (BABYLON) {
  63701. var GamepadManager = /** @class */ (function () {
  63702. function GamepadManager(_scene) {
  63703. var _this = this;
  63704. this._scene = _scene;
  63705. this._babylonGamepads = [];
  63706. this._oneGamepadConnected = false;
  63707. this._isMonitoring = false;
  63708. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63709. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63710. this._gamepadEventSupported = false;
  63711. }
  63712. else {
  63713. this._gamepadEventSupported = 'GamepadEvent' in window;
  63714. this._gamepadSupport = (navigator.getGamepads ||
  63715. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63716. }
  63717. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63718. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63719. for (var i in _this._babylonGamepads) {
  63720. var gamepad = _this._babylonGamepads[i];
  63721. if (gamepad && gamepad._isConnected) {
  63722. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63723. }
  63724. }
  63725. });
  63726. this._onGamepadConnectedEvent = function (evt) {
  63727. var gamepad = evt.gamepad;
  63728. if (gamepad.index in _this._babylonGamepads) {
  63729. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63730. return;
  63731. }
  63732. }
  63733. var newGamepad;
  63734. if (_this._babylonGamepads[gamepad.index]) {
  63735. newGamepad = _this._babylonGamepads[gamepad.index];
  63736. newGamepad.browserGamepad = gamepad;
  63737. newGamepad._isConnected = true;
  63738. }
  63739. else {
  63740. newGamepad = _this._addNewGamepad(gamepad);
  63741. }
  63742. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63743. _this._startMonitoringGamepads();
  63744. };
  63745. this._onGamepadDisconnectedEvent = function (evt) {
  63746. var gamepad = evt.gamepad;
  63747. // Remove the gamepad from the list of gamepads to monitor.
  63748. for (var i in _this._babylonGamepads) {
  63749. if (_this._babylonGamepads[i].index === gamepad.index) {
  63750. var disconnectedGamepad = _this._babylonGamepads[i];
  63751. disconnectedGamepad._isConnected = false;
  63752. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63753. break;
  63754. }
  63755. }
  63756. };
  63757. if (this._gamepadSupport) {
  63758. //first add already-connected gamepads
  63759. this._updateGamepadObjects();
  63760. if (this._babylonGamepads.length) {
  63761. this._startMonitoringGamepads();
  63762. }
  63763. // Checking if the gamepad connected event is supported (like in Firefox)
  63764. if (this._gamepadEventSupported) {
  63765. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63766. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63767. }
  63768. else {
  63769. this._startMonitoringGamepads();
  63770. }
  63771. }
  63772. }
  63773. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63774. get: function () {
  63775. return this._babylonGamepads;
  63776. },
  63777. enumerable: true,
  63778. configurable: true
  63779. });
  63780. GamepadManager.prototype.getGamepadByType = function (type) {
  63781. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63782. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63783. var gamepad = _a[_i];
  63784. if (gamepad && gamepad.type === type) {
  63785. return gamepad;
  63786. }
  63787. }
  63788. return null;
  63789. };
  63790. GamepadManager.prototype.dispose = function () {
  63791. if (this._gamepadEventSupported) {
  63792. if (this._onGamepadConnectedEvent) {
  63793. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63794. }
  63795. if (this._onGamepadDisconnectedEvent) {
  63796. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63797. }
  63798. this._onGamepadConnectedEvent = null;
  63799. this._onGamepadDisconnectedEvent = null;
  63800. }
  63801. this._babylonGamepads.forEach(function (gamepad) {
  63802. gamepad.dispose();
  63803. });
  63804. this.onGamepadConnectedObservable.clear();
  63805. this.onGamepadDisconnectedObservable.clear();
  63806. this._oneGamepadConnected = false;
  63807. this._stopMonitoringGamepads();
  63808. this._babylonGamepads = [];
  63809. };
  63810. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63811. if (!this._oneGamepadConnected) {
  63812. this._oneGamepadConnected = true;
  63813. }
  63814. var newGamepad;
  63815. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63816. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63817. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63818. }
  63819. else if (gamepad.pose) {
  63820. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63821. }
  63822. else {
  63823. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63824. }
  63825. this._babylonGamepads[newGamepad.index] = newGamepad;
  63826. return newGamepad;
  63827. };
  63828. GamepadManager.prototype._startMonitoringGamepads = function () {
  63829. if (!this._isMonitoring) {
  63830. this._isMonitoring = true;
  63831. //back-comp
  63832. if (!this._scene) {
  63833. this._checkGamepadsStatus();
  63834. }
  63835. }
  63836. };
  63837. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63838. this._isMonitoring = false;
  63839. };
  63840. GamepadManager.prototype._checkGamepadsStatus = function () {
  63841. var _this = this;
  63842. // Hack to be compatible Chrome
  63843. this._updateGamepadObjects();
  63844. for (var i in this._babylonGamepads) {
  63845. var gamepad = this._babylonGamepads[i];
  63846. if (!gamepad || !gamepad.isConnected) {
  63847. continue;
  63848. }
  63849. gamepad.update();
  63850. }
  63851. if (this._isMonitoring && !this._scene) {
  63852. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63853. }
  63854. };
  63855. // This function is called only on Chrome, which does not properly support
  63856. // connection/disconnection events and forces you to recopy again the gamepad object
  63857. GamepadManager.prototype._updateGamepadObjects = function () {
  63858. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63859. for (var i = 0; i < gamepads.length; i++) {
  63860. if (gamepads[i]) {
  63861. if (!this._babylonGamepads[gamepads[i].index]) {
  63862. var newGamepad = this._addNewGamepad(gamepads[i]);
  63863. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63864. }
  63865. else {
  63866. // Forced to copy again this object for Chrome for unknown reason
  63867. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63868. if (!this._babylonGamepads[i].isConnected) {
  63869. this._babylonGamepads[i]._isConnected = true;
  63870. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63871. }
  63872. }
  63873. }
  63874. }
  63875. };
  63876. return GamepadManager;
  63877. }());
  63878. BABYLON.GamepadManager = GamepadManager;
  63879. })(BABYLON || (BABYLON = {}));
  63880. //# sourceMappingURL=babylon.gamepadManager.js.map
  63881. var BABYLON;
  63882. (function (BABYLON) {
  63883. var StickValues = /** @class */ (function () {
  63884. function StickValues(x, y) {
  63885. this.x = x;
  63886. this.y = y;
  63887. }
  63888. return StickValues;
  63889. }());
  63890. BABYLON.StickValues = StickValues;
  63891. var Gamepad = /** @class */ (function () {
  63892. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63893. if (leftStickX === void 0) { leftStickX = 0; }
  63894. if (leftStickY === void 0) { leftStickY = 1; }
  63895. if (rightStickX === void 0) { rightStickX = 2; }
  63896. if (rightStickY === void 0) { rightStickY = 3; }
  63897. this.id = id;
  63898. this.index = index;
  63899. this.browserGamepad = browserGamepad;
  63900. this._isConnected = true;
  63901. this._invertLeftStickY = false;
  63902. this.type = Gamepad.GAMEPAD;
  63903. this._leftStickAxisX = leftStickX;
  63904. this._leftStickAxisY = leftStickY;
  63905. this._rightStickAxisX = rightStickX;
  63906. this._rightStickAxisY = rightStickY;
  63907. if (this.browserGamepad.axes.length >= 2) {
  63908. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63909. }
  63910. if (this.browserGamepad.axes.length >= 4) {
  63911. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63912. }
  63913. }
  63914. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63915. get: function () {
  63916. return this._isConnected;
  63917. },
  63918. enumerable: true,
  63919. configurable: true
  63920. });
  63921. Gamepad.prototype.onleftstickchanged = function (callback) {
  63922. this._onleftstickchanged = callback;
  63923. };
  63924. Gamepad.prototype.onrightstickchanged = function (callback) {
  63925. this._onrightstickchanged = callback;
  63926. };
  63927. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63928. get: function () {
  63929. return this._leftStick;
  63930. },
  63931. set: function (newValues) {
  63932. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63933. this._onleftstickchanged(newValues);
  63934. }
  63935. this._leftStick = newValues;
  63936. },
  63937. enumerable: true,
  63938. configurable: true
  63939. });
  63940. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63941. get: function () {
  63942. return this._rightStick;
  63943. },
  63944. set: function (newValues) {
  63945. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63946. this._onrightstickchanged(newValues);
  63947. }
  63948. this._rightStick = newValues;
  63949. },
  63950. enumerable: true,
  63951. configurable: true
  63952. });
  63953. Gamepad.prototype.update = function () {
  63954. if (this._leftStick) {
  63955. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63956. if (this._invertLeftStickY) {
  63957. this.leftStick.y *= -1;
  63958. }
  63959. }
  63960. if (this._rightStick) {
  63961. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63962. }
  63963. };
  63964. Gamepad.prototype.dispose = function () {
  63965. };
  63966. Gamepad.GAMEPAD = 0;
  63967. Gamepad.GENERIC = 1;
  63968. Gamepad.XBOX = 2;
  63969. Gamepad.POSE_ENABLED = 3;
  63970. return Gamepad;
  63971. }());
  63972. BABYLON.Gamepad = Gamepad;
  63973. var GenericPad = /** @class */ (function (_super) {
  63974. __extends(GenericPad, _super);
  63975. function GenericPad(id, index, browserGamepad) {
  63976. var _this = _super.call(this, id, index, browserGamepad) || this;
  63977. _this.onButtonDownObservable = new BABYLON.Observable();
  63978. _this.onButtonUpObservable = new BABYLON.Observable();
  63979. _this.type = Gamepad.GENERIC;
  63980. _this._buttons = new Array(browserGamepad.buttons.length);
  63981. return _this;
  63982. }
  63983. GenericPad.prototype.onbuttondown = function (callback) {
  63984. this._onbuttondown = callback;
  63985. };
  63986. GenericPad.prototype.onbuttonup = function (callback) {
  63987. this._onbuttonup = callback;
  63988. };
  63989. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63990. if (newValue !== currentValue) {
  63991. if (newValue === 1) {
  63992. if (this._onbuttondown) {
  63993. this._onbuttondown(buttonIndex);
  63994. }
  63995. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63996. }
  63997. if (newValue === 0) {
  63998. if (this._onbuttonup) {
  63999. this._onbuttonup(buttonIndex);
  64000. }
  64001. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64002. }
  64003. }
  64004. return newValue;
  64005. };
  64006. GenericPad.prototype.update = function () {
  64007. _super.prototype.update.call(this);
  64008. for (var index = 0; index < this._buttons.length; index++) {
  64009. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64010. }
  64011. };
  64012. GenericPad.prototype.dispose = function () {
  64013. _super.prototype.dispose.call(this);
  64014. this.onButtonDownObservable.clear();
  64015. this.onButtonUpObservable.clear();
  64016. };
  64017. return GenericPad;
  64018. }(Gamepad));
  64019. BABYLON.GenericPad = GenericPad;
  64020. })(BABYLON || (BABYLON = {}));
  64021. //# sourceMappingURL=babylon.gamepad.js.map
  64022. var BABYLON;
  64023. (function (BABYLON) {
  64024. var Xbox360Button;
  64025. (function (Xbox360Button) {
  64026. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64027. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64028. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64029. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64030. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64031. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64032. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64033. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64034. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64035. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64036. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64037. var Xbox360Dpad;
  64038. (function (Xbox360Dpad) {
  64039. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64040. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64041. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64042. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64043. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64044. var Xbox360Pad = /** @class */ (function (_super) {
  64045. __extends(Xbox360Pad, _super);
  64046. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64047. if (xboxOne === void 0) { xboxOne = false; }
  64048. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64049. _this._leftTrigger = 0;
  64050. _this._rightTrigger = 0;
  64051. _this.onButtonDownObservable = new BABYLON.Observable();
  64052. _this.onButtonUpObservable = new BABYLON.Observable();
  64053. _this.onPadDownObservable = new BABYLON.Observable();
  64054. _this.onPadUpObservable = new BABYLON.Observable();
  64055. _this._buttonA = 0;
  64056. _this._buttonB = 0;
  64057. _this._buttonX = 0;
  64058. _this._buttonY = 0;
  64059. _this._buttonBack = 0;
  64060. _this._buttonStart = 0;
  64061. _this._buttonLB = 0;
  64062. _this._buttonRB = 0;
  64063. _this._buttonLeftStick = 0;
  64064. _this._buttonRightStick = 0;
  64065. _this._dPadUp = 0;
  64066. _this._dPadDown = 0;
  64067. _this._dPadLeft = 0;
  64068. _this._dPadRight = 0;
  64069. _this._isXboxOnePad = false;
  64070. _this.type = BABYLON.Gamepad.XBOX;
  64071. _this._isXboxOnePad = xboxOne;
  64072. return _this;
  64073. }
  64074. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64075. this._onlefttriggerchanged = callback;
  64076. };
  64077. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64078. this._onrighttriggerchanged = callback;
  64079. };
  64080. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64081. get: function () {
  64082. return this._leftTrigger;
  64083. },
  64084. set: function (newValue) {
  64085. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64086. this._onlefttriggerchanged(newValue);
  64087. }
  64088. this._leftTrigger = newValue;
  64089. },
  64090. enumerable: true,
  64091. configurable: true
  64092. });
  64093. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64094. get: function () {
  64095. return this._rightTrigger;
  64096. },
  64097. set: function (newValue) {
  64098. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64099. this._onrighttriggerchanged(newValue);
  64100. }
  64101. this._rightTrigger = newValue;
  64102. },
  64103. enumerable: true,
  64104. configurable: true
  64105. });
  64106. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64107. this._onbuttondown = callback;
  64108. };
  64109. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64110. this._onbuttonup = callback;
  64111. };
  64112. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64113. this._ondpaddown = callback;
  64114. };
  64115. Xbox360Pad.prototype.ondpadup = function (callback) {
  64116. this._ondpadup = callback;
  64117. };
  64118. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64119. if (newValue !== currentValue) {
  64120. if (newValue === 1) {
  64121. if (this._onbuttondown) {
  64122. this._onbuttondown(buttonType);
  64123. }
  64124. this.onButtonDownObservable.notifyObservers(buttonType);
  64125. }
  64126. if (newValue === 0) {
  64127. if (this._onbuttonup) {
  64128. this._onbuttonup(buttonType);
  64129. }
  64130. this.onButtonUpObservable.notifyObservers(buttonType);
  64131. }
  64132. }
  64133. return newValue;
  64134. };
  64135. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64136. if (newValue !== currentValue) {
  64137. if (newValue === 1) {
  64138. if (this._ondpaddown) {
  64139. this._ondpaddown(buttonType);
  64140. }
  64141. this.onPadDownObservable.notifyObservers(buttonType);
  64142. }
  64143. if (newValue === 0) {
  64144. if (this._ondpadup) {
  64145. this._ondpadup(buttonType);
  64146. }
  64147. this.onPadUpObservable.notifyObservers(buttonType);
  64148. }
  64149. }
  64150. return newValue;
  64151. };
  64152. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64153. get: function () {
  64154. return this._buttonA;
  64155. },
  64156. set: function (value) {
  64157. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64158. },
  64159. enumerable: true,
  64160. configurable: true
  64161. });
  64162. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64163. get: function () {
  64164. return this._buttonB;
  64165. },
  64166. set: function (value) {
  64167. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64168. },
  64169. enumerable: true,
  64170. configurable: true
  64171. });
  64172. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64173. get: function () {
  64174. return this._buttonX;
  64175. },
  64176. set: function (value) {
  64177. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64178. },
  64179. enumerable: true,
  64180. configurable: true
  64181. });
  64182. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64183. get: function () {
  64184. return this._buttonY;
  64185. },
  64186. set: function (value) {
  64187. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64188. },
  64189. enumerable: true,
  64190. configurable: true
  64191. });
  64192. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64193. get: function () {
  64194. return this._buttonStart;
  64195. },
  64196. set: function (value) {
  64197. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64198. },
  64199. enumerable: true,
  64200. configurable: true
  64201. });
  64202. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64203. get: function () {
  64204. return this._buttonBack;
  64205. },
  64206. set: function (value) {
  64207. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64208. },
  64209. enumerable: true,
  64210. configurable: true
  64211. });
  64212. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64213. get: function () {
  64214. return this._buttonLB;
  64215. },
  64216. set: function (value) {
  64217. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64218. },
  64219. enumerable: true,
  64220. configurable: true
  64221. });
  64222. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64223. get: function () {
  64224. return this._buttonRB;
  64225. },
  64226. set: function (value) {
  64227. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64228. },
  64229. enumerable: true,
  64230. configurable: true
  64231. });
  64232. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64233. get: function () {
  64234. return this._buttonLeftStick;
  64235. },
  64236. set: function (value) {
  64237. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64238. },
  64239. enumerable: true,
  64240. configurable: true
  64241. });
  64242. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64243. get: function () {
  64244. return this._buttonRightStick;
  64245. },
  64246. set: function (value) {
  64247. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64248. },
  64249. enumerable: true,
  64250. configurable: true
  64251. });
  64252. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64253. get: function () {
  64254. return this._dPadUp;
  64255. },
  64256. set: function (value) {
  64257. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64258. },
  64259. enumerable: true,
  64260. configurable: true
  64261. });
  64262. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64263. get: function () {
  64264. return this._dPadDown;
  64265. },
  64266. set: function (value) {
  64267. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64268. },
  64269. enumerable: true,
  64270. configurable: true
  64271. });
  64272. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64273. get: function () {
  64274. return this._dPadLeft;
  64275. },
  64276. set: function (value) {
  64277. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64278. },
  64279. enumerable: true,
  64280. configurable: true
  64281. });
  64282. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64283. get: function () {
  64284. return this._dPadRight;
  64285. },
  64286. set: function (value) {
  64287. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64288. },
  64289. enumerable: true,
  64290. configurable: true
  64291. });
  64292. Xbox360Pad.prototype.update = function () {
  64293. _super.prototype.update.call(this);
  64294. if (this._isXboxOnePad) {
  64295. this.buttonA = this.browserGamepad.buttons[0].value;
  64296. this.buttonB = this.browserGamepad.buttons[1].value;
  64297. this.buttonX = this.browserGamepad.buttons[2].value;
  64298. this.buttonY = this.browserGamepad.buttons[3].value;
  64299. this.buttonLB = this.browserGamepad.buttons[4].value;
  64300. this.buttonRB = this.browserGamepad.buttons[5].value;
  64301. this.leftTrigger = this.browserGamepad.axes[2];
  64302. this.rightTrigger = this.browserGamepad.axes[5];
  64303. this.buttonBack = this.browserGamepad.buttons[9].value;
  64304. this.buttonStart = this.browserGamepad.buttons[8].value;
  64305. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64306. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64307. this.dPadUp = this.browserGamepad.buttons[11].value;
  64308. this.dPadDown = this.browserGamepad.buttons[12].value;
  64309. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64310. this.dPadRight = this.browserGamepad.buttons[14].value;
  64311. }
  64312. else {
  64313. this.buttonA = this.browserGamepad.buttons[0].value;
  64314. this.buttonB = this.browserGamepad.buttons[1].value;
  64315. this.buttonX = this.browserGamepad.buttons[2].value;
  64316. this.buttonY = this.browserGamepad.buttons[3].value;
  64317. this.buttonLB = this.browserGamepad.buttons[4].value;
  64318. this.buttonRB = this.browserGamepad.buttons[5].value;
  64319. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64320. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64321. this.buttonBack = this.browserGamepad.buttons[8].value;
  64322. this.buttonStart = this.browserGamepad.buttons[9].value;
  64323. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64324. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64325. this.dPadUp = this.browserGamepad.buttons[12].value;
  64326. this.dPadDown = this.browserGamepad.buttons[13].value;
  64327. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64328. this.dPadRight = this.browserGamepad.buttons[15].value;
  64329. }
  64330. };
  64331. Xbox360Pad.prototype.dispose = function () {
  64332. _super.prototype.dispose.call(this);
  64333. this.onButtonDownObservable.clear();
  64334. this.onButtonUpObservable.clear();
  64335. this.onPadDownObservable.clear();
  64336. this.onPadUpObservable.clear();
  64337. };
  64338. return Xbox360Pad;
  64339. }(BABYLON.Gamepad));
  64340. BABYLON.Xbox360Pad = Xbox360Pad;
  64341. })(BABYLON || (BABYLON = {}));
  64342. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64343. var BABYLON;
  64344. (function (BABYLON) {
  64345. var PoseEnabledControllerType;
  64346. (function (PoseEnabledControllerType) {
  64347. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64348. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64349. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64350. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64351. /**
  64352. * Google Daydream
  64353. */
  64354. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64355. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64356. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64357. var PoseEnabledControllerHelper = /** @class */ (function () {
  64358. function PoseEnabledControllerHelper() {
  64359. }
  64360. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64361. // Oculus Touch
  64362. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64363. return new BABYLON.OculusTouchController(vrGamepad);
  64364. }
  64365. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64366. return new BABYLON.WindowsMotionController(vrGamepad);
  64367. }
  64368. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64369. return new BABYLON.ViveController(vrGamepad);
  64370. }
  64371. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64372. return new BABYLON.GearVRController(vrGamepad);
  64373. }
  64374. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64375. return new BABYLON.DaydreamController(vrGamepad);
  64376. }
  64377. else {
  64378. return new BABYLON.GenericController(vrGamepad);
  64379. }
  64380. };
  64381. return PoseEnabledControllerHelper;
  64382. }());
  64383. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64384. var PoseEnabledController = /** @class */ (function (_super) {
  64385. __extends(PoseEnabledController, _super);
  64386. function PoseEnabledController(browserGamepad) {
  64387. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64388. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64389. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64390. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64391. // Represents device position and rotation in babylon space
  64392. _this.devicePosition = BABYLON.Vector3.Zero();
  64393. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64394. _this.deviceScaleFactor = 1;
  64395. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64396. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64397. /**
  64398. * Node to be used when casting a ray from the controller
  64399. */
  64400. _this._pointingPoseNode = null;
  64401. _this._workingMatrix = BABYLON.Matrix.Identity();
  64402. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64403. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64404. _this.position = BABYLON.Vector3.Zero();
  64405. _this.rotationQuaternion = new BABYLON.Quaternion();
  64406. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64407. _this._calculatedRotation = new BABYLON.Quaternion();
  64408. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64409. return _this;
  64410. }
  64411. PoseEnabledController.prototype.update = function () {
  64412. _super.prototype.update.call(this);
  64413. var pose = this.browserGamepad.pose;
  64414. this.updateFromDevice(pose);
  64415. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64416. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64417. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64418. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64419. if (this._mesh) {
  64420. this._mesh.position.copyFrom(this.devicePosition);
  64421. if (this._mesh.rotationQuaternion) {
  64422. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64423. }
  64424. }
  64425. };
  64426. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64427. if (poseData) {
  64428. this.rawPose = poseData;
  64429. if (poseData.position) {
  64430. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64431. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64432. this._deviceRoomPosition.z *= -1;
  64433. }
  64434. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64435. this._calculatedPosition.addInPlace(this.position);
  64436. }
  64437. var pose = this.rawPose;
  64438. if (poseData.orientation && pose.orientation) {
  64439. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64440. if (this._mesh) {
  64441. if (this._mesh.getScene().useRightHandedSystem) {
  64442. this._deviceRoomRotationQuaternion.z *= -1;
  64443. this._deviceRoomRotationQuaternion.w *= -1;
  64444. }
  64445. else {
  64446. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64447. }
  64448. }
  64449. // if the camera is set, rotate to the camera's rotation
  64450. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64451. }
  64452. }
  64453. };
  64454. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64455. if (this._mesh) {
  64456. this._mesh.parent = null;
  64457. }
  64458. this._mesh = mesh;
  64459. if (this._poseControlledCamera) {
  64460. this._mesh.parent = this._poseControlledCamera;
  64461. }
  64462. if (!this._mesh.rotationQuaternion) {
  64463. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64464. }
  64465. };
  64466. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64467. this._poseControlledCamera = camera;
  64468. if (this._mesh) {
  64469. this._mesh.parent = this._poseControlledCamera;
  64470. }
  64471. };
  64472. PoseEnabledController.prototype.dispose = function () {
  64473. if (this._mesh) {
  64474. this._mesh.dispose();
  64475. }
  64476. this._mesh = null;
  64477. _super.prototype.dispose.call(this);
  64478. };
  64479. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64480. get: function () {
  64481. return this._mesh;
  64482. },
  64483. enumerable: true,
  64484. configurable: true
  64485. });
  64486. PoseEnabledController.prototype.getForwardRay = function (length) {
  64487. if (length === void 0) { length = 100; }
  64488. if (!this.mesh) {
  64489. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64490. }
  64491. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  64492. var origin = m.getTranslation();
  64493. var forward = new BABYLON.Vector3(0, 0, -1);
  64494. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64495. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64496. return new BABYLON.Ray(origin, direction, length);
  64497. };
  64498. /**
  64499. * Name of the child mesh that can be used to cast a ray from the controller
  64500. */
  64501. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  64502. return PoseEnabledController;
  64503. }(BABYLON.Gamepad));
  64504. BABYLON.PoseEnabledController = PoseEnabledController;
  64505. })(BABYLON || (BABYLON = {}));
  64506. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64507. var BABYLON;
  64508. (function (BABYLON) {
  64509. var WebVRController = /** @class */ (function (_super) {
  64510. __extends(WebVRController, _super);
  64511. function WebVRController(vrGamepad) {
  64512. var _this = _super.call(this, vrGamepad) || this;
  64513. // Observables
  64514. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64515. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64516. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64517. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64518. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64519. _this.pad = { x: 0, y: 0 };
  64520. // avoid GC, store state in a tmp object
  64521. _this._changes = {
  64522. pressChanged: false,
  64523. touchChanged: false,
  64524. valueChanged: false,
  64525. changed: false
  64526. };
  64527. _this._buttons = new Array(vrGamepad.buttons.length);
  64528. _this.hand = vrGamepad.hand;
  64529. return _this;
  64530. }
  64531. WebVRController.prototype.onButtonStateChange = function (callback) {
  64532. this._onButtonStateChange = callback;
  64533. };
  64534. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64535. get: function () {
  64536. return this._defaultModel;
  64537. },
  64538. enumerable: true,
  64539. configurable: true
  64540. });
  64541. WebVRController.prototype.update = function () {
  64542. _super.prototype.update.call(this);
  64543. for (var index = 0; index < this._buttons.length; index++) {
  64544. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64545. }
  64546. ;
  64547. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64548. this.pad.x = this.leftStick.x;
  64549. this.pad.y = this.leftStick.y;
  64550. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64551. }
  64552. };
  64553. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64554. if (!newState) {
  64555. newState = {
  64556. pressed: false,
  64557. touched: false,
  64558. value: 0
  64559. };
  64560. }
  64561. if (!currentState) {
  64562. this._buttons[buttonIndex] = {
  64563. pressed: newState.pressed,
  64564. touched: newState.touched,
  64565. value: newState.value
  64566. };
  64567. return;
  64568. }
  64569. this._checkChanges(newState, currentState);
  64570. if (this._changes.changed) {
  64571. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64572. this._handleButtonChange(buttonIndex, newState, this._changes);
  64573. }
  64574. this._buttons[buttonIndex].pressed = newState.pressed;
  64575. this._buttons[buttonIndex].touched = newState.touched;
  64576. // oculus triggers are never 0, thou not touched.
  64577. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64578. };
  64579. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64580. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64581. this._changes.touchChanged = newState.touched !== currentState.touched;
  64582. this._changes.valueChanged = newState.value !== currentState.value;
  64583. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64584. return this._changes;
  64585. };
  64586. WebVRController.prototype.dispose = function () {
  64587. _super.prototype.dispose.call(this);
  64588. this.onTriggerStateChangedObservable.clear();
  64589. this.onMainButtonStateChangedObservable.clear();
  64590. this.onSecondaryButtonStateChangedObservable.clear();
  64591. this.onPadStateChangedObservable.clear();
  64592. this.onPadValuesChangedObservable.clear();
  64593. };
  64594. return WebVRController;
  64595. }(BABYLON.PoseEnabledController));
  64596. BABYLON.WebVRController = WebVRController;
  64597. })(BABYLON || (BABYLON = {}));
  64598. //# sourceMappingURL=babylon.webVRController.js.map
  64599. var BABYLON;
  64600. (function (BABYLON) {
  64601. var OculusTouchController = /** @class */ (function (_super) {
  64602. __extends(OculusTouchController, _super);
  64603. function OculusTouchController(vrGamepad) {
  64604. var _this = _super.call(this, vrGamepad) || this;
  64605. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64606. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64607. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64608. return _this;
  64609. }
  64610. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64611. var _this = this;
  64612. var meshName;
  64613. // Hand
  64614. if (this.hand === 'left') {
  64615. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64616. }
  64617. else {
  64618. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64619. }
  64620. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64621. /*
  64622. Parent Mesh name: oculus_touch_left
  64623. - body
  64624. - trigger
  64625. - thumbstick
  64626. - grip
  64627. - button_y
  64628. - button_x
  64629. - button_enter
  64630. */
  64631. _this._defaultModel = newMeshes[1];
  64632. _this.attachToMesh(_this._defaultModel);
  64633. if (meshLoaded) {
  64634. meshLoaded(_this._defaultModel);
  64635. }
  64636. });
  64637. };
  64638. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64639. // helper getters for left and right hand.
  64640. get: function () {
  64641. if (this.hand === 'right') {
  64642. return this.onMainButtonStateChangedObservable;
  64643. }
  64644. else {
  64645. throw new Error('No A button on left hand');
  64646. }
  64647. },
  64648. enumerable: true,
  64649. configurable: true
  64650. });
  64651. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64652. get: function () {
  64653. if (this.hand === 'right') {
  64654. return this.onSecondaryButtonStateChangedObservable;
  64655. }
  64656. else {
  64657. throw new Error('No B button on left hand');
  64658. }
  64659. },
  64660. enumerable: true,
  64661. configurable: true
  64662. });
  64663. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64664. get: function () {
  64665. if (this.hand === 'left') {
  64666. return this.onMainButtonStateChangedObservable;
  64667. }
  64668. else {
  64669. throw new Error('No X button on right hand');
  64670. }
  64671. },
  64672. enumerable: true,
  64673. configurable: true
  64674. });
  64675. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64676. get: function () {
  64677. if (this.hand === 'left') {
  64678. return this.onSecondaryButtonStateChangedObservable;
  64679. }
  64680. else {
  64681. throw new Error('No Y button on right hand');
  64682. }
  64683. },
  64684. enumerable: true,
  64685. configurable: true
  64686. });
  64687. /*
  64688. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64689. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64690. 2) secondary trigger (same)
  64691. 3) A (right) X (left), touch, pressed = value
  64692. 4) B / Y
  64693. 5) thumb rest
  64694. */
  64695. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64696. var notifyObject = state; //{ state: state, changes: changes };
  64697. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64698. switch (buttonIdx) {
  64699. case 0:
  64700. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64701. return;
  64702. case 1:// index trigger
  64703. if (this._defaultModel) {
  64704. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64705. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64706. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64707. }
  64708. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64709. return;
  64710. case 2:// secondary trigger
  64711. if (this._defaultModel) {
  64712. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64713. }
  64714. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64715. return;
  64716. case 3:
  64717. if (this._defaultModel) {
  64718. if (notifyObject.pressed) {
  64719. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64720. }
  64721. else {
  64722. (this._defaultModel.getChildren()[1]).position.y = 0;
  64723. }
  64724. }
  64725. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64726. return;
  64727. case 4:
  64728. if (this._defaultModel) {
  64729. if (notifyObject.pressed) {
  64730. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64731. }
  64732. else {
  64733. (this._defaultModel.getChildren()[2]).position.y = 0;
  64734. }
  64735. }
  64736. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64737. return;
  64738. case 5:
  64739. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64740. return;
  64741. }
  64742. };
  64743. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64744. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64745. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64746. return OculusTouchController;
  64747. }(BABYLON.WebVRController));
  64748. BABYLON.OculusTouchController = OculusTouchController;
  64749. })(BABYLON || (BABYLON = {}));
  64750. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64751. var BABYLON;
  64752. (function (BABYLON) {
  64753. var ViveController = /** @class */ (function (_super) {
  64754. __extends(ViveController, _super);
  64755. function ViveController(vrGamepad) {
  64756. var _this = _super.call(this, vrGamepad) || this;
  64757. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64758. _this._invertLeftStickY = true;
  64759. return _this;
  64760. }
  64761. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64762. var _this = this;
  64763. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64764. /*
  64765. Parent Mesh name: ViveWand
  64766. - body
  64767. - r_gripper
  64768. - l_gripper
  64769. - menu_button
  64770. - system_button
  64771. - trackpad
  64772. - trigger
  64773. - LED
  64774. */
  64775. _this._defaultModel = newMeshes[1];
  64776. _this.attachToMesh(_this._defaultModel);
  64777. if (meshLoaded) {
  64778. meshLoaded(_this._defaultModel);
  64779. }
  64780. });
  64781. };
  64782. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64783. get: function () {
  64784. return this.onMainButtonStateChangedObservable;
  64785. },
  64786. enumerable: true,
  64787. configurable: true
  64788. });
  64789. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64790. get: function () {
  64791. return this.onMainButtonStateChangedObservable;
  64792. },
  64793. enumerable: true,
  64794. configurable: true
  64795. });
  64796. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64797. get: function () {
  64798. return this.onSecondaryButtonStateChangedObservable;
  64799. },
  64800. enumerable: true,
  64801. configurable: true
  64802. });
  64803. /**
  64804. * Vive mapping:
  64805. * 0: touchpad
  64806. * 1: trigger
  64807. * 2: left AND right buttons
  64808. * 3: menu button
  64809. */
  64810. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64811. var notifyObject = state; //{ state: state, changes: changes };
  64812. switch (buttonIdx) {
  64813. case 0:
  64814. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64815. return;
  64816. case 1:// index trigger
  64817. if (this._defaultModel) {
  64818. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64819. }
  64820. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64821. return;
  64822. case 2:// left AND right button
  64823. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64824. return;
  64825. case 3:
  64826. if (this._defaultModel) {
  64827. if (notifyObject.pressed) {
  64828. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64829. }
  64830. else {
  64831. (this._defaultModel.getChildren()[2]).position.y = 0;
  64832. }
  64833. }
  64834. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64835. return;
  64836. }
  64837. };
  64838. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64839. ViveController.MODEL_FILENAME = 'wand.babylon';
  64840. return ViveController;
  64841. }(BABYLON.WebVRController));
  64842. BABYLON.ViveController = ViveController;
  64843. })(BABYLON || (BABYLON = {}));
  64844. //# sourceMappingURL=babylon.viveController.js.map
  64845. var BABYLON;
  64846. (function (BABYLON) {
  64847. var GenericController = /** @class */ (function (_super) {
  64848. __extends(GenericController, _super);
  64849. function GenericController(vrGamepad) {
  64850. return _super.call(this, vrGamepad) || this;
  64851. }
  64852. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64853. var _this = this;
  64854. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64855. _this._defaultModel = newMeshes[1];
  64856. _this.attachToMesh(_this._defaultModel);
  64857. if (meshLoaded) {
  64858. meshLoaded(_this._defaultModel);
  64859. }
  64860. });
  64861. };
  64862. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64863. console.log("Button id: " + buttonIdx + "state: ");
  64864. console.dir(state);
  64865. };
  64866. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64867. GenericController.MODEL_FILENAME = 'generic.babylon';
  64868. return GenericController;
  64869. }(BABYLON.WebVRController));
  64870. BABYLON.GenericController = GenericController;
  64871. })(BABYLON || (BABYLON = {}));
  64872. //# sourceMappingURL=babylon.genericController.js.map
  64873. var BABYLON;
  64874. (function (BABYLON) {
  64875. var LoadedMeshInfo = /** @class */ (function () {
  64876. function LoadedMeshInfo() {
  64877. this.buttonMeshes = {};
  64878. this.axisMeshes = {};
  64879. }
  64880. return LoadedMeshInfo;
  64881. }());
  64882. var WindowsMotionController = /** @class */ (function (_super) {
  64883. __extends(WindowsMotionController, _super);
  64884. function WindowsMotionController(vrGamepad) {
  64885. var _this = _super.call(this, vrGamepad) || this;
  64886. _this._mapping = {
  64887. // Semantic button names
  64888. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64889. // A mapping of the button name to glTF model node name
  64890. // that should be transformed by button value.
  64891. buttonMeshNames: {
  64892. 'trigger': 'SELECT',
  64893. 'menu': 'MENU',
  64894. 'grip': 'GRASP',
  64895. 'thumbstick': 'THUMBSTICK_PRESS',
  64896. 'trackpad': 'TOUCHPAD_PRESS'
  64897. },
  64898. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64899. buttonObservableNames: {
  64900. 'trigger': 'onTriggerStateChangedObservable',
  64901. 'menu': 'onSecondaryButtonStateChangedObservable',
  64902. 'grip': 'onMainButtonStateChangedObservable',
  64903. 'thumbstick': 'onPadStateChangedObservable',
  64904. 'trackpad': 'onTrackpadChangedObservable'
  64905. },
  64906. // A mapping of the axis name to glTF model node name
  64907. // that should be transformed by axis value.
  64908. // This array mirrors the browserGamepad.axes array, such that
  64909. // the mesh corresponding to axis 0 is in this array index 0.
  64910. axisMeshNames: [
  64911. 'THUMBSTICK_X',
  64912. 'THUMBSTICK_Y',
  64913. 'TOUCHPAD_TOUCH_X',
  64914. 'TOUCHPAD_TOUCH_Y'
  64915. ],
  64916. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  64917. };
  64918. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64919. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64920. _this.trackpad = { x: 0, y: 0 };
  64921. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64922. _this._loadedMeshInfo = null;
  64923. return _this;
  64924. }
  64925. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64926. get: function () {
  64927. return this.onTriggerStateChangedObservable;
  64928. },
  64929. enumerable: true,
  64930. configurable: true
  64931. });
  64932. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64933. get: function () {
  64934. return this.onSecondaryButtonStateChangedObservable;
  64935. },
  64936. enumerable: true,
  64937. configurable: true
  64938. });
  64939. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64940. get: function () {
  64941. return this.onMainButtonStateChangedObservable;
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64947. get: function () {
  64948. return this.onPadStateChangedObservable;
  64949. },
  64950. enumerable: true,
  64951. configurable: true
  64952. });
  64953. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64954. get: function () {
  64955. return this.onTrackpadChangedObservable;
  64956. },
  64957. enumerable: true,
  64958. configurable: true
  64959. });
  64960. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64961. get: function () {
  64962. return this.onTrackpadValuesChangedObservable;
  64963. },
  64964. enumerable: true,
  64965. configurable: true
  64966. });
  64967. /**
  64968. * Called once per frame by the engine.
  64969. */
  64970. WindowsMotionController.prototype.update = function () {
  64971. _super.prototype.update.call(this);
  64972. if (this.browserGamepad.axes) {
  64973. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64974. this.trackpad.x = this.browserGamepad["axes"][2];
  64975. this.trackpad.y = this.browserGamepad["axes"][3];
  64976. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64977. }
  64978. // Only need to animate axes if there is a loaded mesh
  64979. if (this._loadedMeshInfo) {
  64980. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64981. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64982. }
  64983. }
  64984. }
  64985. };
  64986. /**
  64987. * Called once for each button that changed state since the last frame
  64988. * @param buttonIdx Which button index changed
  64989. * @param state New state of the button
  64990. * @param changes Which properties on the state changed since last frame
  64991. */
  64992. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64993. var buttonName = this._mapping.buttons[buttonIdx];
  64994. if (!buttonName) {
  64995. return;
  64996. }
  64997. // Only emit events for buttons that we know how to map from index to name
  64998. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64999. if (observable) {
  65000. observable.notifyObservers(state);
  65001. }
  65002. this.lerpButtonTransform(buttonName, state.value);
  65003. };
  65004. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65005. // If there is no loaded mesh, there is nothing to transform.
  65006. if (!this._loadedMeshInfo) {
  65007. return;
  65008. }
  65009. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65010. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65011. return;
  65012. }
  65013. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65014. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65015. };
  65016. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65017. if (!this._loadedMeshInfo) {
  65018. return;
  65019. }
  65020. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65021. if (!meshInfo) {
  65022. return;
  65023. }
  65024. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65025. return;
  65026. }
  65027. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65028. var lerpValue = axisValue * 0.5 + 0.5;
  65029. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65030. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65031. };
  65032. /**
  65033. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65034. * @param scene scene in which to add meshes
  65035. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65036. */
  65037. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65038. var _this = this;
  65039. if (forceDefault === void 0) { forceDefault = false; }
  65040. var path;
  65041. var filename;
  65042. // Checking if GLB loader is present
  65043. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65044. // Determine the device specific folder based on the ID suffix
  65045. var device = 'default';
  65046. if (this.id && !forceDefault) {
  65047. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65048. device = ((match && match[0]) || device);
  65049. }
  65050. // Hand
  65051. if (this.hand === 'left') {
  65052. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65053. }
  65054. else {
  65055. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65056. }
  65057. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65058. }
  65059. else {
  65060. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65061. path = BABYLON.GenericController.MODEL_BASE_URL;
  65062. filename = BABYLON.GenericController.MODEL_FILENAME;
  65063. }
  65064. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65065. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65066. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65067. if (!_this._loadedMeshInfo) {
  65068. return;
  65069. }
  65070. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65071. _this.attachToMesh(_this._defaultModel);
  65072. if (meshLoaded) {
  65073. meshLoaded(_this._defaultModel);
  65074. }
  65075. }, null, function (scene, message) {
  65076. BABYLON.Tools.Log(message);
  65077. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65078. if (!forceDefault) {
  65079. _this.initControllerMesh(scene, meshLoaded, true);
  65080. }
  65081. });
  65082. };
  65083. /**
  65084. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65085. * can be transformed by button presses and axes values, based on this._mapping.
  65086. *
  65087. * @param scene scene in which the meshes exist
  65088. * @param meshes list of meshes that make up the controller model to process
  65089. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65090. */
  65091. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65092. var loadedMeshInfo = null;
  65093. // Create a new mesh to contain the glTF hierarchy
  65094. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65095. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65096. var childMesh = null;
  65097. for (var i = 0; i < meshes.length; i++) {
  65098. var mesh = meshes[i];
  65099. if (!mesh.parent) {
  65100. // Exclude controller meshes from picking results
  65101. mesh.isPickable = false;
  65102. // Handle root node, attach to the new parentMesh
  65103. childMesh = mesh;
  65104. break;
  65105. }
  65106. }
  65107. if (childMesh) {
  65108. childMesh.setParent(parentMesh);
  65109. // Create our mesh info. Note that this method will always return non-null.
  65110. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65111. }
  65112. else {
  65113. BABYLON.Tools.Warn('Could not find root node in model file.');
  65114. }
  65115. return loadedMeshInfo;
  65116. };
  65117. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65118. var loadedMeshInfo = new LoadedMeshInfo();
  65119. var i;
  65120. loadedMeshInfo.rootNode = rootNode;
  65121. // Reset the caches
  65122. loadedMeshInfo.buttonMeshes = {};
  65123. loadedMeshInfo.axisMeshes = {};
  65124. // Button Meshes
  65125. for (i = 0; i < this._mapping.buttons.length; i++) {
  65126. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65127. if (!buttonMeshName) {
  65128. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65129. continue;
  65130. }
  65131. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65132. if (!buttonMesh) {
  65133. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65134. continue;
  65135. }
  65136. var buttonMeshInfo = {
  65137. index: i,
  65138. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65139. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65140. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65141. };
  65142. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65143. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65144. }
  65145. else {
  65146. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65147. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65148. '(VALUE: ' + !!buttonMeshInfo.value +
  65149. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65150. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65151. ')');
  65152. }
  65153. }
  65154. // Axis Meshes
  65155. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65156. var axisMeshName = this._mapping.axisMeshNames[i];
  65157. if (!axisMeshName) {
  65158. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65159. continue;
  65160. }
  65161. var axisMesh = getChildByName(rootNode, axisMeshName);
  65162. if (!axisMesh) {
  65163. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65164. continue;
  65165. }
  65166. var axisMeshInfo = {
  65167. index: i,
  65168. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65169. min: getImmediateChildByName(axisMesh, 'MIN'),
  65170. max: getImmediateChildByName(axisMesh, 'MAX')
  65171. };
  65172. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65173. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65174. }
  65175. else {
  65176. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65177. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65178. '(VALUE: ' + !!axisMeshInfo.value +
  65179. ', MIN: ' + !!axisMeshInfo.min +
  65180. ', MAX:' + !!axisMeshInfo.max +
  65181. ')');
  65182. }
  65183. }
  65184. // Pointing Ray
  65185. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65186. if (!loadedMeshInfo.pointingPoseNode) {
  65187. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65188. }
  65189. return loadedMeshInfo;
  65190. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65191. function getChildByName(node, name) {
  65192. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65193. }
  65194. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65195. function getImmediateChildByName(node, name) {
  65196. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65197. }
  65198. };
  65199. WindowsMotionController.prototype.getForwardRay = function (length) {
  65200. if (length === void 0) { length = 100; }
  65201. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65202. return _super.prototype.getForwardRay.call(this, length);
  65203. }
  65204. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65205. var origin = m.getTranslation();
  65206. var forward = new BABYLON.Vector3(0, 0, -1);
  65207. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65208. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65209. return new BABYLON.Ray(origin, direction, length);
  65210. };
  65211. WindowsMotionController.prototype.dispose = function () {
  65212. _super.prototype.dispose.call(this);
  65213. this.onTrackpadChangedObservable.clear();
  65214. };
  65215. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65216. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65217. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65218. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65219. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65220. return WindowsMotionController;
  65221. }(BABYLON.WebVRController));
  65222. BABYLON.WindowsMotionController = WindowsMotionController;
  65223. })(BABYLON || (BABYLON = {}));
  65224. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65225. var BABYLON;
  65226. (function (BABYLON) {
  65227. var GearVRController = /** @class */ (function (_super) {
  65228. __extends(GearVRController, _super);
  65229. function GearVRController(vrGamepad) {
  65230. var _this = _super.call(this, vrGamepad) || this;
  65231. _this._buttonIndexToObservableNameMap = [
  65232. 'onTrackpadChangedObservable',
  65233. 'onTriggerStateChangedObservable' // Trigger
  65234. ];
  65235. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65236. return _this;
  65237. }
  65238. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65239. var _this = this;
  65240. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65241. _this._defaultModel = newMeshes[1];
  65242. _this.attachToMesh(_this._defaultModel);
  65243. if (meshLoaded) {
  65244. meshLoaded(_this._defaultModel);
  65245. }
  65246. });
  65247. };
  65248. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65249. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65250. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65251. // Only emit events for buttons that we know how to map from index to observable
  65252. var observable = this[observableName];
  65253. if (observable) {
  65254. observable.notifyObservers(state);
  65255. }
  65256. }
  65257. };
  65258. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65259. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65260. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65261. return GearVRController;
  65262. }(BABYLON.WebVRController));
  65263. BABYLON.GearVRController = GearVRController;
  65264. })(BABYLON || (BABYLON = {}));
  65265. //# sourceMappingURL=babylon.gearVRController.js.map
  65266. var BABYLON;
  65267. (function (BABYLON) {
  65268. /**
  65269. * Google Daydream controller
  65270. */
  65271. var DaydreamController = /** @class */ (function (_super) {
  65272. __extends(DaydreamController, _super);
  65273. function DaydreamController(vrGamepad) {
  65274. var _this = _super.call(this, vrGamepad) || this;
  65275. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65276. return _this;
  65277. }
  65278. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65279. var _this = this;
  65280. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65281. _this._defaultModel = newMeshes[1];
  65282. _this.attachToMesh(_this._defaultModel);
  65283. if (meshLoaded) {
  65284. meshLoaded(_this._defaultModel);
  65285. }
  65286. });
  65287. };
  65288. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65289. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65290. if (buttonIdx === 0) {
  65291. var observable = this.onTriggerStateChangedObservable;
  65292. if (observable) {
  65293. observable.notifyObservers(state);
  65294. }
  65295. }
  65296. else {
  65297. // If the app or home buttons are ever made available
  65298. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65299. }
  65300. };
  65301. /**
  65302. * Base Url for the controller model.
  65303. */
  65304. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65305. /**
  65306. * File name for the controller model.
  65307. */
  65308. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65309. /**
  65310. * Gamepad Id prefix used to identify Daydream Controller.
  65311. */
  65312. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65313. return DaydreamController;
  65314. }(BABYLON.WebVRController));
  65315. BABYLON.DaydreamController = DaydreamController;
  65316. })(BABYLON || (BABYLON = {}));
  65317. //# sourceMappingURL=babylon.daydreamController.js.map
  65318. var BABYLON;
  65319. (function (BABYLON) {
  65320. var FollowCamera = /** @class */ (function (_super) {
  65321. __extends(FollowCamera, _super);
  65322. function FollowCamera(name, position, scene, lockedTarget) {
  65323. if (lockedTarget === void 0) { lockedTarget = null; }
  65324. var _this = _super.call(this, name, position, scene) || this;
  65325. _this.radius = 12;
  65326. _this.rotationOffset = 0;
  65327. _this.heightOffset = 4;
  65328. _this.cameraAcceleration = 0.05;
  65329. _this.maxCameraSpeed = 20;
  65330. _this.lockedTarget = lockedTarget;
  65331. return _this;
  65332. }
  65333. FollowCamera.prototype.getRadians = function (degrees) {
  65334. return degrees * Math.PI / 180;
  65335. };
  65336. FollowCamera.prototype.follow = function (cameraTarget) {
  65337. if (!cameraTarget)
  65338. return;
  65339. var yRotation;
  65340. if (cameraTarget.rotationQuaternion) {
  65341. var rotMatrix = new BABYLON.Matrix();
  65342. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65343. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65344. }
  65345. else {
  65346. yRotation = cameraTarget.rotation.y;
  65347. }
  65348. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65349. var targetPosition = cameraTarget.getAbsolutePosition();
  65350. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65351. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65352. var dx = targetX - this.position.x;
  65353. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65354. var dz = (targetZ) - this.position.z;
  65355. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65356. var vy = dy * this.cameraAcceleration;
  65357. var vz = dz * this.cameraAcceleration * 2;
  65358. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65359. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65360. }
  65361. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65362. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65363. }
  65364. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65365. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65366. }
  65367. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65368. this.setTarget(targetPosition);
  65369. };
  65370. FollowCamera.prototype._checkInputs = function () {
  65371. _super.prototype._checkInputs.call(this);
  65372. if (this.lockedTarget) {
  65373. this.follow(this.lockedTarget);
  65374. }
  65375. };
  65376. FollowCamera.prototype.getClassName = function () {
  65377. return "FollowCamera";
  65378. };
  65379. __decorate([
  65380. BABYLON.serialize()
  65381. ], FollowCamera.prototype, "radius", void 0);
  65382. __decorate([
  65383. BABYLON.serialize()
  65384. ], FollowCamera.prototype, "rotationOffset", void 0);
  65385. __decorate([
  65386. BABYLON.serialize()
  65387. ], FollowCamera.prototype, "heightOffset", void 0);
  65388. __decorate([
  65389. BABYLON.serialize()
  65390. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65391. __decorate([
  65392. BABYLON.serialize()
  65393. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65394. __decorate([
  65395. BABYLON.serializeAsMeshReference("lockedTargetId")
  65396. ], FollowCamera.prototype, "lockedTarget", void 0);
  65397. return FollowCamera;
  65398. }(BABYLON.TargetCamera));
  65399. BABYLON.FollowCamera = FollowCamera;
  65400. var ArcFollowCamera = /** @class */ (function (_super) {
  65401. __extends(ArcFollowCamera, _super);
  65402. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65403. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65404. _this.alpha = alpha;
  65405. _this.beta = beta;
  65406. _this.radius = radius;
  65407. _this.target = target;
  65408. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65409. _this.follow();
  65410. return _this;
  65411. }
  65412. ArcFollowCamera.prototype.follow = function () {
  65413. if (!this.target) {
  65414. return;
  65415. }
  65416. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65417. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65418. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65419. var targetPosition = this.target.getAbsolutePosition();
  65420. this.position = targetPosition.add(this._cartesianCoordinates);
  65421. this.setTarget(targetPosition);
  65422. };
  65423. ArcFollowCamera.prototype._checkInputs = function () {
  65424. _super.prototype._checkInputs.call(this);
  65425. this.follow();
  65426. };
  65427. ArcFollowCamera.prototype.getClassName = function () {
  65428. return "ArcFollowCamera";
  65429. };
  65430. return ArcFollowCamera;
  65431. }(BABYLON.TargetCamera));
  65432. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65433. })(BABYLON || (BABYLON = {}));
  65434. //# sourceMappingURL=babylon.followCamera.js.map
  65435. var BABYLON;
  65436. (function (BABYLON) {
  65437. // We're mainly based on the logic defined into the FreeCamera code
  65438. var UniversalCamera = /** @class */ (function (_super) {
  65439. __extends(UniversalCamera, _super);
  65440. //-- end properties for backward compatibility for inputs
  65441. function UniversalCamera(name, position, scene) {
  65442. var _this = _super.call(this, name, position, scene) || this;
  65443. _this.inputs.addGamepad();
  65444. return _this;
  65445. }
  65446. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65447. //-- Begin properties for backward compatibility for inputs
  65448. get: function () {
  65449. var gamepad = this.inputs.attached["gamepad"];
  65450. if (gamepad)
  65451. return gamepad.gamepadAngularSensibility;
  65452. return 0;
  65453. },
  65454. set: function (value) {
  65455. var gamepad = this.inputs.attached["gamepad"];
  65456. if (gamepad)
  65457. gamepad.gamepadAngularSensibility = value;
  65458. },
  65459. enumerable: true,
  65460. configurable: true
  65461. });
  65462. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65463. get: function () {
  65464. var gamepad = this.inputs.attached["gamepad"];
  65465. if (gamepad)
  65466. return gamepad.gamepadMoveSensibility;
  65467. return 0;
  65468. },
  65469. set: function (value) {
  65470. var gamepad = this.inputs.attached["gamepad"];
  65471. if (gamepad)
  65472. gamepad.gamepadMoveSensibility = value;
  65473. },
  65474. enumerable: true,
  65475. configurable: true
  65476. });
  65477. UniversalCamera.prototype.getClassName = function () {
  65478. return "UniversalCamera";
  65479. };
  65480. return UniversalCamera;
  65481. }(BABYLON.TouchCamera));
  65482. BABYLON.UniversalCamera = UniversalCamera;
  65483. })(BABYLON || (BABYLON = {}));
  65484. //# sourceMappingURL=babylon.universalCamera.js.map
  65485. var BABYLON;
  65486. (function (BABYLON) {
  65487. // We're mainly based on the logic defined into the FreeCamera code
  65488. var GamepadCamera = /** @class */ (function (_super) {
  65489. __extends(GamepadCamera, _super);
  65490. //-- end properties for backward compatibility for inputs
  65491. function GamepadCamera(name, position, scene) {
  65492. return _super.call(this, name, position, scene) || this;
  65493. }
  65494. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65495. //-- Begin properties for backward compatibility for inputs
  65496. get: function () {
  65497. var gamepad = this.inputs.attached["gamepad"];
  65498. if (gamepad)
  65499. return gamepad.gamepadAngularSensibility;
  65500. return 0;
  65501. },
  65502. set: function (value) {
  65503. var gamepad = this.inputs.attached["gamepad"];
  65504. if (gamepad)
  65505. gamepad.gamepadAngularSensibility = value;
  65506. },
  65507. enumerable: true,
  65508. configurable: true
  65509. });
  65510. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65511. get: function () {
  65512. var gamepad = this.inputs.attached["gamepad"];
  65513. if (gamepad)
  65514. return gamepad.gamepadMoveSensibility;
  65515. return 0;
  65516. },
  65517. set: function (value) {
  65518. var gamepad = this.inputs.attached["gamepad"];
  65519. if (gamepad)
  65520. gamepad.gamepadMoveSensibility = value;
  65521. },
  65522. enumerable: true,
  65523. configurable: true
  65524. });
  65525. GamepadCamera.prototype.getClassName = function () {
  65526. return "GamepadCamera";
  65527. };
  65528. return GamepadCamera;
  65529. }(BABYLON.UniversalCamera));
  65530. BABYLON.GamepadCamera = GamepadCamera;
  65531. })(BABYLON || (BABYLON = {}));
  65532. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65533. var BABYLON;
  65534. (function (BABYLON) {
  65535. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65536. function PostProcessRenderPipelineManager() {
  65537. this._renderPipelines = {};
  65538. }
  65539. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65540. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65541. };
  65542. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65543. if (unique === void 0) { unique = false; }
  65544. var renderPipeline = this._renderPipelines[renderPipelineName];
  65545. if (!renderPipeline) {
  65546. return;
  65547. }
  65548. renderPipeline._attachCameras(cameras, unique);
  65549. };
  65550. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65551. var renderPipeline = this._renderPipelines[renderPipelineName];
  65552. if (!renderPipeline) {
  65553. return;
  65554. }
  65555. renderPipeline._detachCameras(cameras);
  65556. };
  65557. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65558. var renderPipeline = this._renderPipelines[renderPipelineName];
  65559. if (!renderPipeline) {
  65560. return;
  65561. }
  65562. renderPipeline._enableEffect(renderEffectName, cameras);
  65563. };
  65564. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65565. var renderPipeline = this._renderPipelines[renderPipelineName];
  65566. if (!renderPipeline) {
  65567. return;
  65568. }
  65569. renderPipeline._disableEffect(renderEffectName, cameras);
  65570. };
  65571. PostProcessRenderPipelineManager.prototype.update = function () {
  65572. for (var renderPipelineName in this._renderPipelines) {
  65573. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65574. var pipeline = this._renderPipelines[renderPipelineName];
  65575. if (!pipeline.isSupported) {
  65576. pipeline.dispose();
  65577. delete this._renderPipelines[renderPipelineName];
  65578. }
  65579. else {
  65580. pipeline._update();
  65581. }
  65582. }
  65583. }
  65584. };
  65585. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65586. for (var renderPipelineName in this._renderPipelines) {
  65587. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65588. var pipeline = this._renderPipelines[renderPipelineName];
  65589. pipeline._rebuild();
  65590. }
  65591. }
  65592. };
  65593. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65594. for (var renderPipelineName in this._renderPipelines) {
  65595. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65596. var pipeline = this._renderPipelines[renderPipelineName];
  65597. pipeline.dispose();
  65598. }
  65599. }
  65600. };
  65601. return PostProcessRenderPipelineManager;
  65602. }());
  65603. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65604. })(BABYLON || (BABYLON = {}));
  65605. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65606. var BABYLON;
  65607. (function (BABYLON) {
  65608. /**
  65609. * This represents a set of one or more post processes in Babylon.
  65610. * A post process can be used to apply a shader to a texture after it is rendered.
  65611. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65612. */
  65613. var PostProcessRenderEffect = /** @class */ (function () {
  65614. /**
  65615. * Instantiates a post process render effect.
  65616. * A post process can be used to apply a shader to a texture after it is rendered.
  65617. * @param engine The engine the effect is tied to
  65618. * @param name The name of the effect
  65619. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65620. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65621. */
  65622. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65623. this._name = name;
  65624. this._singleInstance = singleInstance || true;
  65625. this._getPostProcesses = getPostProcesses;
  65626. this._cameras = {};
  65627. this._indicesForCamera = {};
  65628. this._postProcesses = {};
  65629. }
  65630. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65631. /**
  65632. * Checks if all the post processes in the effect are supported.
  65633. */
  65634. get: function () {
  65635. for (var index in this._postProcesses) {
  65636. for (var ppIndex in this._postProcesses[index]) {
  65637. if (!this._postProcesses[index][ppIndex].isSupported) {
  65638. return false;
  65639. }
  65640. }
  65641. }
  65642. return true;
  65643. },
  65644. enumerable: true,
  65645. configurable: true
  65646. });
  65647. /**
  65648. * Updates the current state of the effect
  65649. */
  65650. PostProcessRenderEffect.prototype._update = function () {
  65651. };
  65652. /**
  65653. * Attaches the effect on cameras
  65654. * @param cameras The camera to attach to.
  65655. */
  65656. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65657. var _this = this;
  65658. var cameraKey;
  65659. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65660. if (!cams) {
  65661. return;
  65662. }
  65663. for (var i = 0; i < cams.length; i++) {
  65664. var camera = cams[i];
  65665. var cameraName = camera.name;
  65666. if (this._singleInstance) {
  65667. cameraKey = 0;
  65668. }
  65669. else {
  65670. cameraKey = cameraName;
  65671. }
  65672. if (!this._postProcesses[cameraKey]) {
  65673. var postProcess = this._getPostProcesses();
  65674. if (postProcess) {
  65675. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65676. }
  65677. }
  65678. if (!this._indicesForCamera[cameraName]) {
  65679. this._indicesForCamera[cameraName] = [];
  65680. }
  65681. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65682. var index = camera.attachPostProcess(postProcess);
  65683. _this._indicesForCamera[cameraName].push(index);
  65684. });
  65685. if (!this._cameras[cameraName]) {
  65686. this._cameras[cameraName] = camera;
  65687. }
  65688. }
  65689. };
  65690. /**
  65691. * Detatches the effect on cameras
  65692. * @param cameras The camera to detatch from.
  65693. */
  65694. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65695. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65696. if (!cams) {
  65697. return;
  65698. }
  65699. for (var i = 0; i < cams.length; i++) {
  65700. var camera = cams[i];
  65701. var cameraName = camera.name;
  65702. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65703. camera.detachPostProcess(postProcess);
  65704. });
  65705. if (this._cameras[cameraName]) {
  65706. //this._indicesForCamera.splice(index, 1);
  65707. this._cameras[cameraName] = null;
  65708. }
  65709. }
  65710. };
  65711. /**
  65712. * Enables the effect on given cameras
  65713. * @param cameras The camera to enable.
  65714. */
  65715. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65716. var _this = this;
  65717. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65718. if (!cams) {
  65719. return;
  65720. }
  65721. for (var i = 0; i < cams.length; i++) {
  65722. var camera = cams[i];
  65723. var cameraName = camera.name;
  65724. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65725. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65726. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65727. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65728. });
  65729. }
  65730. }
  65731. }
  65732. };
  65733. /**
  65734. * Disables the effect on the given cameras
  65735. * @param cameras The camera to disable.
  65736. */
  65737. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65738. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65739. if (!cams) {
  65740. return;
  65741. }
  65742. for (var i = 0; i < cams.length; i++) {
  65743. var camera = cams[i];
  65744. var cameraName = camera.name;
  65745. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65746. camera.detachPostProcess(postProcess);
  65747. });
  65748. }
  65749. };
  65750. /**
  65751. * Gets a list of the post processes contained in the effect.
  65752. * @param camera The camera to get the post processes on.
  65753. * @returns The list of the post processes in the effect.
  65754. */
  65755. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65756. if (this._singleInstance) {
  65757. return this._postProcesses[0];
  65758. }
  65759. else {
  65760. if (!camera) {
  65761. return null;
  65762. }
  65763. return this._postProcesses[camera.name];
  65764. }
  65765. };
  65766. return PostProcessRenderEffect;
  65767. }());
  65768. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65769. })(BABYLON || (BABYLON = {}));
  65770. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65771. var BABYLON;
  65772. (function (BABYLON) {
  65773. var PostProcessRenderPipeline = /** @class */ (function () {
  65774. function PostProcessRenderPipeline(engine, name) {
  65775. this.engine = engine;
  65776. this._name = name;
  65777. this._renderEffects = {};
  65778. this._renderEffectsForIsolatedPass = new Array();
  65779. this._cameras = [];
  65780. }
  65781. PostProcessRenderPipeline.prototype.getClassName = function () {
  65782. return "PostProcessRenderPipeline";
  65783. };
  65784. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65785. get: function () {
  65786. for (var renderEffectName in this._renderEffects) {
  65787. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65788. if (!this._renderEffects[renderEffectName].isSupported) {
  65789. return false;
  65790. }
  65791. }
  65792. }
  65793. return true;
  65794. },
  65795. enumerable: true,
  65796. configurable: true
  65797. });
  65798. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65799. this._renderEffects[renderEffect._name] = renderEffect;
  65800. };
  65801. // private
  65802. PostProcessRenderPipeline.prototype._rebuild = function () {
  65803. };
  65804. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65805. var renderEffects = this._renderEffects[renderEffectName];
  65806. if (!renderEffects) {
  65807. return;
  65808. }
  65809. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65810. };
  65811. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65812. var renderEffects = this._renderEffects[renderEffectName];
  65813. if (!renderEffects) {
  65814. return;
  65815. }
  65816. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65817. };
  65818. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65819. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65820. if (!cams) {
  65821. return;
  65822. }
  65823. var indicesToDelete = [];
  65824. var i;
  65825. for (i = 0; i < cams.length; i++) {
  65826. var camera = cams[i];
  65827. var cameraName = camera.name;
  65828. if (this._cameras.indexOf(camera) === -1) {
  65829. this._cameras[cameraName] = camera;
  65830. }
  65831. else if (unique) {
  65832. indicesToDelete.push(i);
  65833. }
  65834. }
  65835. for (i = 0; i < indicesToDelete.length; i++) {
  65836. cameras.splice(indicesToDelete[i], 1);
  65837. }
  65838. for (var renderEffectName in this._renderEffects) {
  65839. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65840. this._renderEffects[renderEffectName]._attachCameras(cams);
  65841. }
  65842. }
  65843. };
  65844. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65846. if (!cams) {
  65847. return;
  65848. }
  65849. for (var renderEffectName in this._renderEffects) {
  65850. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65851. this._renderEffects[renderEffectName]._detachCameras(cams);
  65852. }
  65853. }
  65854. for (var i = 0; i < cams.length; i++) {
  65855. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65856. }
  65857. };
  65858. PostProcessRenderPipeline.prototype._update = function () {
  65859. for (var renderEffectName in this._renderEffects) {
  65860. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65861. this._renderEffects[renderEffectName]._update();
  65862. }
  65863. }
  65864. for (var i = 0; i < this._cameras.length; i++) {
  65865. var cameraName = this._cameras[i].name;
  65866. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65867. this._renderEffectsForIsolatedPass[cameraName]._update();
  65868. }
  65869. }
  65870. };
  65871. PostProcessRenderPipeline.prototype._reset = function () {
  65872. this._renderEffects = {};
  65873. this._renderEffectsForIsolatedPass = new Array();
  65874. };
  65875. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65876. // 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)
  65877. var effectKeys = Object.keys(this._renderEffects);
  65878. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  65879. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  65880. if (postProcesses) {
  65881. postProcesses[0].samples = 4;
  65882. return true;
  65883. }
  65884. }
  65885. return false;
  65886. };
  65887. PostProcessRenderPipeline.prototype.dispose = function () {
  65888. // Must be implemented by children
  65889. };
  65890. __decorate([
  65891. BABYLON.serialize()
  65892. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65893. return PostProcessRenderPipeline;
  65894. }());
  65895. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65896. })(BABYLON || (BABYLON = {}));
  65897. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65898. var BABYLON;
  65899. (function (BABYLON) {
  65900. /**
  65901. * This represents a depth renderer in Babylon.
  65902. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65903. */
  65904. var DepthRenderer = /** @class */ (function () {
  65905. /**
  65906. * Instantiates a depth renderer
  65907. * @param scene The scene the renderer belongs to
  65908. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65909. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65910. */
  65911. function DepthRenderer(scene, type, camera) {
  65912. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65913. if (camera === void 0) { camera = null; }
  65914. var _this = this;
  65915. this._scene = scene;
  65916. this._camera = camera;
  65917. var engine = scene.getEngine();
  65918. // Render target
  65919. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65920. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65921. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65922. this._depthMap.refreshRate = 1;
  65923. this._depthMap.renderParticles = false;
  65924. this._depthMap.renderList = null;
  65925. // Camera to get depth map from to support multiple concurrent cameras
  65926. this._depthMap.activeCamera = this._camera;
  65927. this._depthMap.ignoreCameraViewport = true;
  65928. this._depthMap.useCameraPostProcesses = false;
  65929. // set default depth value to 1.0 (far away)
  65930. this._depthMap.onClearObservable.add(function (engine) {
  65931. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65932. });
  65933. // Custom render function
  65934. var renderSubMesh = function (subMesh) {
  65935. var mesh = subMesh.getRenderingMesh();
  65936. var scene = _this._scene;
  65937. var engine = scene.getEngine();
  65938. var material = subMesh.getMaterial();
  65939. if (!material) {
  65940. return;
  65941. }
  65942. // Culling and reverse (right handed system)
  65943. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65944. // Managing instances
  65945. var batch = mesh._getInstancesRenderList(subMesh._id);
  65946. if (batch.mustReturn) {
  65947. return;
  65948. }
  65949. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65950. var camera = _this._camera || scene.activeCamera;
  65951. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  65952. engine.enableEffect(_this._effect);
  65953. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65954. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65955. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  65956. // Alpha test
  65957. if (material && material.needAlphaTesting()) {
  65958. var alphaTexture = material.getAlphaTestTexture();
  65959. if (alphaTexture) {
  65960. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65961. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65962. }
  65963. }
  65964. // Bones
  65965. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65966. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65967. }
  65968. // Draw
  65969. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65970. }
  65971. };
  65972. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65973. var index;
  65974. if (depthOnlySubMeshes.length) {
  65975. engine.setColorWrite(false);
  65976. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65977. renderSubMesh(depthOnlySubMeshes.data[index]);
  65978. }
  65979. engine.setColorWrite(true);
  65980. }
  65981. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65982. renderSubMesh(opaqueSubMeshes.data[index]);
  65983. }
  65984. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65985. renderSubMesh(alphaTestSubMeshes.data[index]);
  65986. }
  65987. };
  65988. }
  65989. /**
  65990. * Creates the depth rendering effect and checks if the effect is ready.
  65991. * @param subMesh The submesh to be used to render the depth map of
  65992. * @param useInstances If multiple world instances should be used
  65993. * @returns if the depth renderer is ready to render the depth map
  65994. */
  65995. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65996. var material = subMesh.getMaterial();
  65997. if (material.disableDepthWrite) {
  65998. return false;
  65999. }
  66000. var defines = [];
  66001. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66002. var mesh = subMesh.getMesh();
  66003. // Alpha test
  66004. if (material && material.needAlphaTesting()) {
  66005. defines.push("#define ALPHATEST");
  66006. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66007. attribs.push(BABYLON.VertexBuffer.UVKind);
  66008. defines.push("#define UV1");
  66009. }
  66010. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66011. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66012. defines.push("#define UV2");
  66013. }
  66014. }
  66015. // Bones
  66016. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66017. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66018. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66019. if (mesh.numBoneInfluencers > 4) {
  66020. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66021. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66022. }
  66023. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66024. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66025. }
  66026. else {
  66027. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66028. }
  66029. // Instances
  66030. if (useInstances) {
  66031. defines.push("#define INSTANCES");
  66032. attribs.push("world0");
  66033. attribs.push("world1");
  66034. attribs.push("world2");
  66035. attribs.push("world3");
  66036. }
  66037. // Get correct effect
  66038. var join = defines.join("\n");
  66039. if (this._cachedDefines !== join) {
  66040. this._cachedDefines = join;
  66041. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  66042. }
  66043. return this._effect.isReady();
  66044. };
  66045. /**
  66046. * Gets the texture which the depth map will be written to.
  66047. * @returns The depth map texture
  66048. */
  66049. DepthRenderer.prototype.getDepthMap = function () {
  66050. return this._depthMap;
  66051. };
  66052. /**
  66053. * Disposes of the depth renderer.
  66054. */
  66055. DepthRenderer.prototype.dispose = function () {
  66056. this._depthMap.dispose();
  66057. };
  66058. return DepthRenderer;
  66059. }());
  66060. BABYLON.DepthRenderer = DepthRenderer;
  66061. })(BABYLON || (BABYLON = {}));
  66062. //# sourceMappingURL=babylon.depthRenderer.js.map
  66063. var BABYLON;
  66064. (function (BABYLON) {
  66065. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66066. __extends(SSAORenderingPipeline, _super);
  66067. /**
  66068. * @constructor
  66069. * @param {string} name - The rendering pipeline name
  66070. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66071. * @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 }
  66072. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66073. */
  66074. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66075. var _this = _super.call(this, scene.getEngine(), name) || this;
  66076. // Members
  66077. /**
  66078. * The PassPostProcess id in the pipeline that contains the original scene color
  66079. * @type {string}
  66080. */
  66081. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66082. /**
  66083. * The SSAO PostProcess id in the pipeline
  66084. * @type {string}
  66085. */
  66086. _this.SSAORenderEffect = "SSAORenderEffect";
  66087. /**
  66088. * The horizontal blur PostProcess id in the pipeline
  66089. * @type {string}
  66090. */
  66091. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66092. /**
  66093. * The vertical blur PostProcess id in the pipeline
  66094. * @type {string}
  66095. */
  66096. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66097. /**
  66098. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66099. * @type {string}
  66100. */
  66101. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66102. /**
  66103. * The output strength of the SSAO post-process. Default value is 1.0.
  66104. * @type {number}
  66105. */
  66106. _this.totalStrength = 1.0;
  66107. /**
  66108. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66109. * @type {number}
  66110. */
  66111. _this.radius = 0.0001;
  66112. /**
  66113. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66114. * Must not be equal to fallOff and superior to fallOff.
  66115. * Default value is 0.975
  66116. * @type {number}
  66117. */
  66118. _this.area = 0.0075;
  66119. /**
  66120. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66121. * Must not be equal to area and inferior to area.
  66122. * Default value is 0.0
  66123. * @type {number}
  66124. */
  66125. _this.fallOff = 0.000001;
  66126. /**
  66127. * The base color of the SSAO post-process
  66128. * The final result is "base + ssao" between [0, 1]
  66129. * @type {number}
  66130. */
  66131. _this.base = 0.5;
  66132. _this._firstUpdate = true;
  66133. _this._scene = scene;
  66134. // Set up assets
  66135. _this._createRandomTexture();
  66136. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66137. var ssaoRatio = ratio.ssaoRatio || ratio;
  66138. var combineRatio = ratio.combineRatio || ratio;
  66139. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66140. _this._createSSAOPostProcess(ssaoRatio);
  66141. _this._createBlurPostProcess(ssaoRatio);
  66142. _this._createSSAOCombinePostProcess(combineRatio);
  66143. // Set up pipeline
  66144. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66145. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66148. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66149. // Finish
  66150. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66151. if (cameras)
  66152. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66153. return _this;
  66154. }
  66155. // Public Methods
  66156. /**
  66157. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66158. */
  66159. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66160. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66161. for (var i = 0; i < this._scene.cameras.length; i++) {
  66162. var camera = this._scene.cameras[i];
  66163. this._originalColorPostProcess.dispose(camera);
  66164. this._ssaoPostProcess.dispose(camera);
  66165. this._blurHPostProcess.dispose(camera);
  66166. this._blurVPostProcess.dispose(camera);
  66167. this._ssaoCombinePostProcess.dispose(camera);
  66168. }
  66169. this._randomTexture.dispose();
  66170. if (disableDepthRender)
  66171. this._scene.disableDepthRenderer();
  66172. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66173. _super.prototype.dispose.call(this);
  66174. };
  66175. // Private Methods
  66176. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66177. var _this = this;
  66178. var size = 16;
  66179. 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);
  66180. 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);
  66181. this._blurHPostProcess.onActivateObservable.add(function () {
  66182. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66183. _this._blurHPostProcess.kernel = size * dw;
  66184. });
  66185. this._blurVPostProcess.onActivateObservable.add(function () {
  66186. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66187. _this._blurVPostProcess.kernel = size * dw;
  66188. });
  66189. };
  66190. SSAORenderingPipeline.prototype._rebuild = function () {
  66191. this._firstUpdate = true;
  66192. _super.prototype._rebuild.call(this);
  66193. };
  66194. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66195. var _this = this;
  66196. var numSamples = 16;
  66197. var sampleSphere = [
  66198. 0.5381, 0.1856, -0.4319,
  66199. 0.1379, 0.2486, 0.4430,
  66200. 0.3371, 0.5679, -0.0057,
  66201. -0.6999, -0.0451, -0.0019,
  66202. 0.0689, -0.1598, -0.8547,
  66203. 0.0560, 0.0069, -0.1843,
  66204. -0.0146, 0.1402, 0.0762,
  66205. 0.0100, -0.1924, -0.0344,
  66206. -0.3577, -0.5301, -0.4358,
  66207. -0.3169, 0.1063, 0.0158,
  66208. 0.0103, -0.5869, 0.0046,
  66209. -0.0897, -0.4940, 0.3287,
  66210. 0.7119, -0.0154, -0.0918,
  66211. -0.0533, 0.0596, -0.5411,
  66212. 0.0352, -0.0631, 0.5460,
  66213. -0.4776, 0.2847, -0.0271
  66214. ];
  66215. var samplesFactor = 1.0 / numSamples;
  66216. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66217. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66218. "area", "fallOff", "base", "range", "viewport"
  66219. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66220. this._ssaoPostProcess.onApply = function (effect) {
  66221. if (_this._firstUpdate) {
  66222. effect.setArray3("sampleSphere", sampleSphere);
  66223. effect.setFloat("samplesFactor", samplesFactor);
  66224. effect.setFloat("randTextureTiles", 4.0);
  66225. }
  66226. effect.setFloat("totalStrength", _this.totalStrength);
  66227. effect.setFloat("radius", _this.radius);
  66228. effect.setFloat("area", _this.area);
  66229. effect.setFloat("fallOff", _this.fallOff);
  66230. effect.setFloat("base", _this.base);
  66231. effect.setTexture("textureSampler", _this._depthTexture);
  66232. effect.setTexture("randomSampler", _this._randomTexture);
  66233. };
  66234. };
  66235. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66236. var _this = this;
  66237. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66238. this._ssaoCombinePostProcess.onApply = function (effect) {
  66239. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66240. };
  66241. };
  66242. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66243. var size = 512;
  66244. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66245. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66246. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66247. var context = this._randomTexture.getContext();
  66248. var rand = function (min, max) {
  66249. return Math.random() * (max - min) + min;
  66250. };
  66251. var randVector = BABYLON.Vector3.Zero();
  66252. for (var x = 0; x < size; x++) {
  66253. for (var y = 0; y < size; y++) {
  66254. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66255. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66256. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66257. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66258. context.fillRect(x, y, 1, 1);
  66259. }
  66260. }
  66261. this._randomTexture.update(false);
  66262. };
  66263. __decorate([
  66264. BABYLON.serialize()
  66265. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66266. __decorate([
  66267. BABYLON.serialize()
  66268. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66269. __decorate([
  66270. BABYLON.serialize()
  66271. ], SSAORenderingPipeline.prototype, "area", void 0);
  66272. __decorate([
  66273. BABYLON.serialize()
  66274. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66275. __decorate([
  66276. BABYLON.serialize()
  66277. ], SSAORenderingPipeline.prototype, "base", void 0);
  66278. return SSAORenderingPipeline;
  66279. }(BABYLON.PostProcessRenderPipeline));
  66280. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66281. })(BABYLON || (BABYLON = {}));
  66282. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66283. var BABYLON;
  66284. (function (BABYLON) {
  66285. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66286. __extends(SSAO2RenderingPipeline, _super);
  66287. /**
  66288. * @constructor
  66289. * @param {string} name - The rendering pipeline name
  66290. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66291. * @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 }
  66292. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66293. */
  66294. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66295. var _this = _super.call(this, scene.getEngine(), name) || this;
  66296. // Members
  66297. /**
  66298. * The PassPostProcess id in the pipeline that contains the original scene color
  66299. * @type {string}
  66300. */
  66301. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66302. /**
  66303. * The SSAO PostProcess id in the pipeline
  66304. * @type {string}
  66305. */
  66306. _this.SSAORenderEffect = "SSAORenderEffect";
  66307. /**
  66308. * The horizontal blur PostProcess id in the pipeline
  66309. * @type {string}
  66310. */
  66311. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66312. /**
  66313. * The vertical blur PostProcess id in the pipeline
  66314. * @type {string}
  66315. */
  66316. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66317. /**
  66318. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66319. * @type {string}
  66320. */
  66321. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66322. /**
  66323. * The output strength of the SSAO post-process. Default value is 1.0.
  66324. * @type {number}
  66325. */
  66326. _this.totalStrength = 1.0;
  66327. /**
  66328. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66329. * @type {number}
  66330. */
  66331. _this.maxZ = 100.0;
  66332. /**
  66333. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66334. * @type {number}
  66335. */
  66336. _this.minZAspect = 0.2;
  66337. /**
  66338. * Number of samples used for the SSAO calculations. Default value is 8
  66339. * @type {number}
  66340. */
  66341. _this._samples = 8;
  66342. /**
  66343. * Are we using bilateral blur ?
  66344. * @type {boolean}
  66345. */
  66346. _this._expensiveBlur = true;
  66347. /**
  66348. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66349. * @type {number}
  66350. */
  66351. _this.radius = 2.0;
  66352. /**
  66353. * The base color of the SSAO post-process
  66354. * The final result is "base + ssao" between [0, 1]
  66355. * @type {number}
  66356. */
  66357. _this.base = 0.1;
  66358. _this._firstUpdate = true;
  66359. _this._scene = scene;
  66360. if (!_this.isSupported) {
  66361. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66362. return _this;
  66363. }
  66364. var ssaoRatio = ratio.ssaoRatio || ratio;
  66365. var blurRatio = ratio.blurRatio || ratio;
  66366. // Set up assets
  66367. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66368. _this._createRandomTexture();
  66369. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66370. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66371. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66372. _this._createSSAOPostProcess(1.0);
  66373. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66374. _this._createSSAOCombinePostProcess(blurRatio);
  66375. // Set up pipeline
  66376. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66377. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66378. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66379. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66380. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66381. // Finish
  66382. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66383. if (cameras)
  66384. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66385. return _this;
  66386. }
  66387. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66388. get: function () {
  66389. return this._samples;
  66390. },
  66391. set: function (n) {
  66392. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66393. this._samples = n;
  66394. this._sampleSphere = this._generateHemisphere();
  66395. this._firstUpdate = true;
  66396. },
  66397. enumerable: true,
  66398. configurable: true
  66399. });
  66400. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66401. get: function () {
  66402. return this._expensiveBlur;
  66403. },
  66404. set: function (b) {
  66405. 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"]);
  66406. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66407. this._expensiveBlur = b;
  66408. this._firstUpdate = true;
  66409. },
  66410. enumerable: true,
  66411. configurable: true
  66412. });
  66413. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66414. /**
  66415. * Support test.
  66416. * @type {boolean}
  66417. */
  66418. get: function () {
  66419. var engine = BABYLON.Engine.LastCreatedEngine;
  66420. if (!engine) {
  66421. return false;
  66422. }
  66423. return engine.getCaps().drawBuffersExtension;
  66424. },
  66425. enumerable: true,
  66426. configurable: true
  66427. });
  66428. // Public Methods
  66429. /**
  66430. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66431. */
  66432. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66433. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66434. for (var i = 0; i < this._scene.cameras.length; i++) {
  66435. var camera = this._scene.cameras[i];
  66436. this._originalColorPostProcess.dispose(camera);
  66437. this._ssaoPostProcess.dispose(camera);
  66438. this._blurHPostProcess.dispose(camera);
  66439. this._blurVPostProcess.dispose(camera);
  66440. this._ssaoCombinePostProcess.dispose(camera);
  66441. }
  66442. this._randomTexture.dispose();
  66443. if (disableGeometryBufferRenderer)
  66444. this._scene.disableGeometryBufferRenderer();
  66445. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66446. _super.prototype.dispose.call(this);
  66447. };
  66448. // Private Methods
  66449. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66450. var _this = this;
  66451. this._samplerOffsets = [];
  66452. var expensive = this.expensiveBlur;
  66453. for (var i = -8; i < 8; i++) {
  66454. this._samplerOffsets.push(i * 2 + 0.5);
  66455. }
  66456. 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");
  66457. this._blurHPostProcess.onApply = function (effect) {
  66458. if (!_this._scene.activeCamera) {
  66459. return;
  66460. }
  66461. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66462. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66463. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66464. effect.setFloat("radius", _this.radius);
  66465. effect.setTexture("depthSampler", _this._depthTexture);
  66466. if (_this._firstUpdate) {
  66467. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66468. }
  66469. };
  66470. 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");
  66471. this._blurVPostProcess.onApply = function (effect) {
  66472. if (!_this._scene.activeCamera) {
  66473. return;
  66474. }
  66475. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66476. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66477. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66478. effect.setFloat("radius", _this.radius);
  66479. effect.setTexture("depthSampler", _this._depthTexture);
  66480. if (_this._firstUpdate) {
  66481. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66482. _this._firstUpdate = false;
  66483. }
  66484. };
  66485. };
  66486. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66487. this._firstUpdate = true;
  66488. _super.prototype._rebuild.call(this);
  66489. };
  66490. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66491. var numSamples = this.samples;
  66492. var result = [];
  66493. var vector, scale;
  66494. var rand = function (min, max) {
  66495. return Math.random() * (max - min) + min;
  66496. };
  66497. var i = 0;
  66498. while (i < numSamples) {
  66499. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66500. vector.normalize();
  66501. scale = i / numSamples;
  66502. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66503. vector.scaleInPlace(scale);
  66504. result.push(vector.x, vector.y, vector.z);
  66505. i++;
  66506. }
  66507. return result;
  66508. };
  66509. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66510. var _this = this;
  66511. var numSamples = this.samples;
  66512. this._sampleSphere = this._generateHemisphere();
  66513. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66514. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66515. "base", "range", "projection", "near", "far", "texelSize",
  66516. "xViewport", "yViewport", "maxZ", "minZAspect"
  66517. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66518. this._ssaoPostProcess.onApply = function (effect) {
  66519. if (_this._firstUpdate) {
  66520. effect.setArray3("sampleSphere", _this._sampleSphere);
  66521. effect.setFloat("randTextureTiles", 4.0);
  66522. }
  66523. if (!_this._scene.activeCamera) {
  66524. return;
  66525. }
  66526. effect.setFloat("samplesFactor", 1 / _this.samples);
  66527. effect.setFloat("totalStrength", _this.totalStrength);
  66528. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66529. effect.setFloat("radius", _this.radius);
  66530. effect.setFloat("maxZ", _this.maxZ);
  66531. effect.setFloat("minZAspect", _this.minZAspect);
  66532. effect.setFloat("base", _this.base);
  66533. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66534. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66535. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66536. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66537. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66538. effect.setTexture("textureSampler", _this._depthTexture);
  66539. effect.setTexture("normalSampler", _this._normalTexture);
  66540. effect.setTexture("randomSampler", _this._randomTexture);
  66541. };
  66542. };
  66543. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66544. var _this = this;
  66545. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66546. this._ssaoCombinePostProcess.onApply = function (effect) {
  66547. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66548. };
  66549. };
  66550. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66551. var size = 512;
  66552. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66553. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66554. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66555. var context = this._randomTexture.getContext();
  66556. var rand = function (min, max) {
  66557. return Math.random() * (max - min) + min;
  66558. };
  66559. var randVector = BABYLON.Vector3.Zero();
  66560. for (var x = 0; x < size; x++) {
  66561. for (var y = 0; y < size; y++) {
  66562. randVector.x = rand(0.0, 1.0);
  66563. randVector.y = rand(0.0, 1.0);
  66564. randVector.z = 0.0;
  66565. randVector.normalize();
  66566. randVector.scaleInPlace(255);
  66567. randVector.x = Math.floor(randVector.x);
  66568. randVector.y = Math.floor(randVector.y);
  66569. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66570. context.fillRect(x, y, 1, 1);
  66571. }
  66572. }
  66573. this._randomTexture.update(false);
  66574. };
  66575. __decorate([
  66576. BABYLON.serialize()
  66577. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66578. __decorate([
  66579. BABYLON.serialize()
  66580. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66581. __decorate([
  66582. BABYLON.serialize()
  66583. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66584. __decorate([
  66585. BABYLON.serialize("samples")
  66586. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66587. __decorate([
  66588. BABYLON.serialize("expensiveBlur")
  66589. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66590. __decorate([
  66591. BABYLON.serialize()
  66592. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66593. __decorate([
  66594. BABYLON.serialize()
  66595. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66596. return SSAO2RenderingPipeline;
  66597. }(BABYLON.PostProcessRenderPipeline));
  66598. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66599. })(BABYLON || (BABYLON = {}));
  66600. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66601. // BABYLON.JS Chromatic Aberration GLSL Shader
  66602. // Author: Olivier Guyot
  66603. // Separates very slightly R, G and B colors on the edges of the screen
  66604. // Inspired by Francois Tarlier & Martins Upitis
  66605. var BABYLON;
  66606. (function (BABYLON) {
  66607. var LensRenderingPipeline = /** @class */ (function (_super) {
  66608. __extends(LensRenderingPipeline, _super);
  66609. /**
  66610. * @constructor
  66611. *
  66612. * Effect parameters are as follow:
  66613. * {
  66614. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66615. * edge_blur: number; // from 0 to x (1 for realism)
  66616. * distortion: number; // from 0 to x (1 for realism)
  66617. * grain_amount: number; // from 0 to 1
  66618. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66619. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66620. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66621. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66622. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66623. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66624. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66625. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66626. * }
  66627. * Note: if an effect parameter is unset, effect is disabled
  66628. *
  66629. * @param {string} name - The rendering pipeline name
  66630. * @param {object} parameters - An object containing all parameters (see above)
  66631. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66632. * @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)
  66633. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66634. */
  66635. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66636. if (ratio === void 0) { ratio = 1.0; }
  66637. var _this = _super.call(this, scene.getEngine(), name) || this;
  66638. // Lens effects can be of the following:
  66639. // - chromatic aberration (slight shift of RGB colors)
  66640. // - blur on the edge of the lens
  66641. // - lens distortion
  66642. // - depth-of-field blur & highlights enhancing
  66643. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66644. // - grain effect (noise or custom texture)
  66645. // Two additional texture samplers are needed:
  66646. // - depth map (for depth-of-field)
  66647. // - grain texture
  66648. /**
  66649. * The chromatic aberration PostProcess id in the pipeline
  66650. * @type {string}
  66651. */
  66652. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66653. /**
  66654. * The highlights enhancing PostProcess id in the pipeline
  66655. * @type {string}
  66656. */
  66657. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66658. /**
  66659. * The depth-of-field PostProcess id in the pipeline
  66660. * @type {string}
  66661. */
  66662. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66663. _this._scene = scene;
  66664. // Fetch texture samplers
  66665. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66666. if (parameters.grain_texture) {
  66667. _this._grainTexture = parameters.grain_texture;
  66668. }
  66669. else {
  66670. _this._createGrainTexture();
  66671. }
  66672. // save parameters
  66673. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66674. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66675. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66676. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66677. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66678. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66679. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66680. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66681. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66682. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66683. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66684. // Create effects
  66685. _this._createChromaticAberrationPostProcess(ratio);
  66686. _this._createHighlightsPostProcess(ratio);
  66687. _this._createDepthOfFieldPostProcess(ratio / 4);
  66688. // Set up pipeline
  66689. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66690. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66691. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66692. if (_this._highlightsGain === -1) {
  66693. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66694. }
  66695. // Finish
  66696. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66697. if (cameras) {
  66698. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66699. }
  66700. return _this;
  66701. }
  66702. // public methods (self explanatory)
  66703. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66704. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66705. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66706. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66707. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66708. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66709. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66710. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66711. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66712. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66713. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66714. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66715. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66716. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66717. };
  66718. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66719. this._highlightsPostProcess.updateEffect();
  66720. };
  66721. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66722. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66723. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66724. this._highlightsGain = amount;
  66725. };
  66726. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66727. if (this._highlightsGain === -1) {
  66728. this._highlightsGain = 1.0;
  66729. }
  66730. this._highlightsThreshold = amount;
  66731. };
  66732. LensRenderingPipeline.prototype.disableHighlights = function () {
  66733. this._highlightsGain = -1;
  66734. };
  66735. /**
  66736. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66737. */
  66738. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66739. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66740. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66741. this._chromaticAberrationPostProcess = null;
  66742. this._highlightsPostProcess = null;
  66743. this._depthOfFieldPostProcess = null;
  66744. this._grainTexture.dispose();
  66745. if (disableDepthRender)
  66746. this._scene.disableDepthRenderer();
  66747. };
  66748. // colors shifting and distortion
  66749. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66750. var _this = this;
  66751. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  66752. [], // samplers
  66753. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66754. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66755. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66756. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66757. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66758. effect.setFloat('radialIntensity', 1);
  66759. effect.setFloat2('direction', 17, 17);
  66760. effect.setFloat2('centerPosition', 0.5, 0.5);
  66761. };
  66762. };
  66763. // highlights enhancing
  66764. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66765. var _this = this;
  66766. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66767. [], // samplers
  66768. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66769. this._highlightsPostProcess.onApply = function (effect) {
  66770. effect.setFloat('gain', _this._highlightsGain);
  66771. effect.setFloat('threshold', _this._highlightsThreshold);
  66772. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66773. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66774. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66775. };
  66776. };
  66777. // colors shifting and distortion
  66778. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66779. var _this = this;
  66780. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66781. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66782. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66783. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66784. this._depthOfFieldPostProcess.onApply = function (effect) {
  66785. effect.setTexture("depthSampler", _this._depthTexture);
  66786. effect.setTexture("grainSampler", _this._grainTexture);
  66787. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66788. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66789. effect.setFloat('grain_amount', _this._grainAmount);
  66790. effect.setBool('blur_noise', _this._blurNoise);
  66791. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66792. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66793. effect.setFloat('distortion', _this._distortion);
  66794. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66795. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66796. effect.setFloat('aperture', _this._dofAperture);
  66797. effect.setFloat('darken', _this._dofDarken);
  66798. effect.setFloat('edge_blur', _this._edgeBlur);
  66799. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66800. if (_this._scene.activeCamera) {
  66801. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66802. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66803. }
  66804. };
  66805. };
  66806. // creates a black and white random noise texture, 512x512
  66807. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66808. var size = 512;
  66809. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66810. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66811. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66812. var context = this._grainTexture.getContext();
  66813. var rand = function (min, max) {
  66814. return Math.random() * (max - min) + min;
  66815. };
  66816. var value;
  66817. for (var x = 0; x < size; x++) {
  66818. for (var y = 0; y < size; y++) {
  66819. value = Math.floor(rand(0.42, 0.58) * 255);
  66820. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66821. context.fillRect(x, y, 1, 1);
  66822. }
  66823. }
  66824. this._grainTexture.update(false);
  66825. };
  66826. return LensRenderingPipeline;
  66827. }(BABYLON.PostProcessRenderPipeline));
  66828. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66829. })(BABYLON || (BABYLON = {}));
  66830. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66831. var BABYLON;
  66832. (function (BABYLON) {
  66833. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66834. __extends(StandardRenderingPipeline, _super);
  66835. /**
  66836. * @constructor
  66837. * @param {string} name - The rendering pipeline name
  66838. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66839. * @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)
  66840. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66841. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66842. */
  66843. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66844. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66845. var _this = _super.call(this, scene.getEngine(), name) || this;
  66846. _this.downSampleX4PostProcess = null;
  66847. _this.brightPassPostProcess = null;
  66848. _this.blurHPostProcesses = [];
  66849. _this.blurVPostProcesses = [];
  66850. _this.textureAdderPostProcess = null;
  66851. _this.volumetricLightPostProcess = null;
  66852. _this.volumetricLightSmoothXPostProcess = null;
  66853. _this.volumetricLightSmoothYPostProcess = null;
  66854. _this.volumetricLightMergePostProces = null;
  66855. _this.volumetricLightFinalPostProcess = null;
  66856. _this.luminancePostProcess = null;
  66857. _this.luminanceDownSamplePostProcesses = [];
  66858. _this.hdrPostProcess = null;
  66859. _this.textureAdderFinalPostProcess = null;
  66860. _this.lensFlareFinalPostProcess = null;
  66861. _this.hdrFinalPostProcess = null;
  66862. _this.lensFlarePostProcess = null;
  66863. _this.lensFlareComposePostProcess = null;
  66864. _this.motionBlurPostProcess = null;
  66865. _this.depthOfFieldPostProcess = null;
  66866. // Values
  66867. _this.brightThreshold = 1.0;
  66868. _this.blurWidth = 512.0;
  66869. _this.horizontalBlur = false;
  66870. _this.exposure = 1.0;
  66871. _this.lensTexture = null;
  66872. _this.volumetricLightCoefficient = 0.2;
  66873. _this.volumetricLightPower = 4.0;
  66874. _this.volumetricLightBlurScale = 64.0;
  66875. _this.sourceLight = null;
  66876. _this.hdrMinimumLuminance = 1.0;
  66877. _this.hdrDecreaseRate = 0.5;
  66878. _this.hdrIncreaseRate = 0.5;
  66879. _this.lensColorTexture = null;
  66880. _this.lensFlareStrength = 20.0;
  66881. _this.lensFlareGhostDispersal = 1.4;
  66882. _this.lensFlareHaloWidth = 0.7;
  66883. _this.lensFlareDistortionStrength = 16.0;
  66884. _this.lensStarTexture = null;
  66885. _this.lensFlareDirtTexture = null;
  66886. _this.depthOfFieldDistance = 10.0;
  66887. _this.depthOfFieldBlurWidth = 64.0;
  66888. _this.motionStrength = 1.0;
  66889. // IAnimatable
  66890. _this.animations = [];
  66891. _this._currentDepthOfFieldSource = null;
  66892. _this._hdrCurrentLuminance = 1.0;
  66893. // Getters and setters
  66894. _this._bloomEnabled = true;
  66895. _this._depthOfFieldEnabled = false;
  66896. _this._vlsEnabled = false;
  66897. _this._lensFlareEnabled = false;
  66898. _this._hdrEnabled = false;
  66899. _this._motionBlurEnabled = false;
  66900. _this._motionBlurSamples = 64.0;
  66901. _this._volumetricLightStepsCount = 50.0;
  66902. _this._cameras = cameras || [];
  66903. // Initialize
  66904. _this._scene = scene;
  66905. _this._basePostProcess = originalPostProcess;
  66906. _this._ratio = ratio;
  66907. // Misc
  66908. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66909. // Finish
  66910. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66911. _this._buildPipeline();
  66912. return _this;
  66913. }
  66914. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66915. get: function () {
  66916. return this._bloomEnabled;
  66917. },
  66918. set: function (enabled) {
  66919. if (this._bloomEnabled === enabled) {
  66920. return;
  66921. }
  66922. this._bloomEnabled = enabled;
  66923. this._buildPipeline();
  66924. },
  66925. enumerable: true,
  66926. configurable: true
  66927. });
  66928. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66929. get: function () {
  66930. return this._depthOfFieldEnabled;
  66931. },
  66932. set: function (enabled) {
  66933. if (this._depthOfFieldEnabled === enabled) {
  66934. return;
  66935. }
  66936. this._depthOfFieldEnabled = enabled;
  66937. this._buildPipeline();
  66938. },
  66939. enumerable: true,
  66940. configurable: true
  66941. });
  66942. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66943. get: function () {
  66944. return this._lensFlareEnabled;
  66945. },
  66946. set: function (enabled) {
  66947. if (this._lensFlareEnabled === enabled) {
  66948. return;
  66949. }
  66950. this._lensFlareEnabled = enabled;
  66951. this._buildPipeline();
  66952. },
  66953. enumerable: true,
  66954. configurable: true
  66955. });
  66956. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66957. get: function () {
  66958. return this._hdrEnabled;
  66959. },
  66960. set: function (enabled) {
  66961. if (this._hdrEnabled === enabled) {
  66962. return;
  66963. }
  66964. this._hdrEnabled = enabled;
  66965. this._buildPipeline();
  66966. },
  66967. enumerable: true,
  66968. configurable: true
  66969. });
  66970. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66971. get: function () {
  66972. return this._vlsEnabled;
  66973. },
  66974. set: function (enabled) {
  66975. if (this._vlsEnabled === enabled) {
  66976. return;
  66977. }
  66978. if (enabled) {
  66979. var geometry = this._scene.enableGeometryBufferRenderer();
  66980. if (!geometry) {
  66981. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66982. return;
  66983. }
  66984. }
  66985. this._vlsEnabled = enabled;
  66986. this._buildPipeline();
  66987. },
  66988. enumerable: true,
  66989. configurable: true
  66990. });
  66991. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66992. get: function () {
  66993. return this._motionBlurEnabled;
  66994. },
  66995. set: function (enabled) {
  66996. if (this._motionBlurEnabled === enabled) {
  66997. return;
  66998. }
  66999. this._motionBlurEnabled = enabled;
  67000. this._buildPipeline();
  67001. },
  67002. enumerable: true,
  67003. configurable: true
  67004. });
  67005. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  67006. get: function () {
  67007. return this._volumetricLightStepsCount;
  67008. },
  67009. set: function (count) {
  67010. if (this.volumetricLightPostProcess) {
  67011. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  67012. }
  67013. this._volumetricLightStepsCount = count;
  67014. },
  67015. enumerable: true,
  67016. configurable: true
  67017. });
  67018. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  67019. get: function () {
  67020. return this._motionBlurSamples;
  67021. },
  67022. set: function (samples) {
  67023. if (this.motionBlurPostProcess) {
  67024. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  67025. }
  67026. this._motionBlurSamples = samples;
  67027. },
  67028. enumerable: true,
  67029. configurable: true
  67030. });
  67031. StandardRenderingPipeline.prototype._buildPipeline = function () {
  67032. var _this = this;
  67033. var ratio = this._ratio;
  67034. var scene = this._scene;
  67035. this._disposePostProcesses();
  67036. this._reset();
  67037. // Create pass post-process
  67038. if (!this._basePostProcess) {
  67039. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  67040. this.originalPostProcess.onApply = function (effect) {
  67041. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  67042. };
  67043. }
  67044. else {
  67045. this.originalPostProcess = this._basePostProcess;
  67046. }
  67047. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  67048. this._currentDepthOfFieldSource = this.originalPostProcess;
  67049. if (this._vlsEnabled) {
  67050. // Create volumetric light
  67051. this._createVolumetricLightPostProcess(scene, ratio);
  67052. // Create volumetric light final post-process
  67053. 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);
  67054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  67055. }
  67056. if (this._bloomEnabled) {
  67057. // Create down sample X4 post-process
  67058. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67059. // Create bright pass post-process
  67060. this._createBrightPassPostProcess(scene, ratio / 2);
  67061. // Create gaussian blur post-processes (down sampling blurs)
  67062. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67063. // Create texture adder post-process
  67064. this._createTextureAdderPostProcess(scene, ratio);
  67065. // Create depth-of-field source post-process
  67066. 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);
  67067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67068. }
  67069. if (this._lensFlareEnabled) {
  67070. // Create lens flare post-process
  67071. this._createLensFlarePostProcess(scene, ratio);
  67072. // Create depth-of-field source post-process post lens-flare and disable it now
  67073. 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);
  67074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67075. }
  67076. if (this._hdrEnabled) {
  67077. // Create luminance
  67078. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67079. // Create HDR
  67080. this._createHdrPostProcess(scene, ratio);
  67081. // Create depth-of-field source post-process post hdr and disable it now
  67082. 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);
  67083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67084. }
  67085. if (this._depthOfFieldEnabled) {
  67086. // Create gaussian blur used by depth-of-field
  67087. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67088. // Create depth-of-field post-process
  67089. this._createDepthOfFieldPostProcess(scene, ratio);
  67090. }
  67091. if (this._motionBlurEnabled) {
  67092. // Create motion blur post-process
  67093. this._createMotionBlurPostProcess(scene, ratio);
  67094. }
  67095. if (this._cameras !== null) {
  67096. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67097. }
  67098. };
  67099. // Down Sample X4 Post-Processs
  67100. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67101. var _this = this;
  67102. var downSampleX4Offsets = new Array(32);
  67103. 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);
  67104. this.downSampleX4PostProcess.onApply = function (effect) {
  67105. var id = 0;
  67106. var width = _this.downSampleX4PostProcess.width;
  67107. var height = _this.downSampleX4PostProcess.height;
  67108. for (var i = -2; i < 2; i++) {
  67109. for (var j = -2; j < 2; j++) {
  67110. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67111. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67112. id += 2;
  67113. }
  67114. }
  67115. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67116. };
  67117. // Add to pipeline
  67118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67119. };
  67120. // Brightpass Post-Process
  67121. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67122. var _this = this;
  67123. var brightOffsets = new Array(8);
  67124. 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);
  67125. this.brightPassPostProcess.onApply = function (effect) {
  67126. var sU = (1.0 / _this.brightPassPostProcess.width);
  67127. var sV = (1.0 / _this.brightPassPostProcess.height);
  67128. brightOffsets[0] = -0.5 * sU;
  67129. brightOffsets[1] = 0.5 * sV;
  67130. brightOffsets[2] = 0.5 * sU;
  67131. brightOffsets[3] = 0.5 * sV;
  67132. brightOffsets[4] = -0.5 * sU;
  67133. brightOffsets[5] = -0.5 * sV;
  67134. brightOffsets[6] = 0.5 * sU;
  67135. brightOffsets[7] = -0.5 * sV;
  67136. effect.setArray2("dsOffsets", brightOffsets);
  67137. effect.setFloat("brightThreshold", _this.brightThreshold);
  67138. };
  67139. // Add to pipeline
  67140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67141. };
  67142. // Create blur H&V post-processes
  67143. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67144. var _this = this;
  67145. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67146. var engine = scene.getEngine();
  67147. 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);
  67148. 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);
  67149. blurX.onActivateObservable.add(function () {
  67150. var dw = blurX.width / engine.getRenderWidth();
  67151. blurX.kernel = _this[blurWidthKey] * dw;
  67152. });
  67153. blurY.onActivateObservable.add(function () {
  67154. var dw = blurY.height / engine.getRenderHeight();
  67155. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67156. });
  67157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67159. this.blurHPostProcesses.push(blurX);
  67160. this.blurVPostProcesses.push(blurY);
  67161. };
  67162. // Create texture adder post-process
  67163. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67164. var _this = this;
  67165. 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);
  67166. this.textureAdderPostProcess.onApply = function (effect) {
  67167. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67168. effect.setTexture("lensSampler", _this.lensTexture);
  67169. effect.setFloat("exposure", _this.exposure);
  67170. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67171. };
  67172. // Add to pipeline
  67173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67174. };
  67175. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67176. var _this = this;
  67177. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67178. geometryRenderer.enablePosition = true;
  67179. var geometry = geometryRenderer.getGBuffer();
  67180. // Base post-process
  67181. 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));
  67182. var depthValues = BABYLON.Vector2.Zero();
  67183. this.volumetricLightPostProcess.onApply = function (effect) {
  67184. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67185. var generator = _this.sourceLight.getShadowGenerator();
  67186. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67187. effect.setTexture("positionSampler", geometry.textures[2]);
  67188. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67189. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67190. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67191. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67192. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67193. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67194. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67195. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67196. effect.setVector2("depthValues", depthValues);
  67197. }
  67198. };
  67199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67200. // Smooth
  67201. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67202. // Merge
  67203. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67204. this.volumetricLightMergePostProces.onApply = function (effect) {
  67205. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67206. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67207. };
  67208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67209. };
  67210. // Create luminance
  67211. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67212. var _this = this;
  67213. // Create luminance
  67214. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67215. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67216. var offsets = [];
  67217. this.luminancePostProcess.onApply = function (effect) {
  67218. var sU = (1.0 / _this.luminancePostProcess.width);
  67219. var sV = (1.0 / _this.luminancePostProcess.height);
  67220. offsets[0] = -0.5 * sU;
  67221. offsets[1] = 0.5 * sV;
  67222. offsets[2] = 0.5 * sU;
  67223. offsets[3] = 0.5 * sV;
  67224. offsets[4] = -0.5 * sU;
  67225. offsets[5] = -0.5 * sV;
  67226. offsets[6] = 0.5 * sU;
  67227. offsets[7] = -0.5 * sV;
  67228. effect.setArray2("lumOffsets", offsets);
  67229. };
  67230. // Add to pipeline
  67231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67232. // Create down sample luminance
  67233. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67234. var size = Math.pow(3, i);
  67235. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67236. if (i === 0) {
  67237. defines += "#define FINAL_DOWN_SAMPLER";
  67238. }
  67239. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67240. this.luminanceDownSamplePostProcesses.push(postProcess);
  67241. }
  67242. // Create callbacks and add effects
  67243. var lastLuminance = this.luminancePostProcess;
  67244. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67245. var downSampleOffsets = new Array(18);
  67246. pp.onApply = function (effect) {
  67247. if (!lastLuminance) {
  67248. return;
  67249. }
  67250. var id = 0;
  67251. for (var x = -1; x < 2; x++) {
  67252. for (var y = -1; y < 2; y++) {
  67253. downSampleOffsets[id] = x / lastLuminance.width;
  67254. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67255. id += 2;
  67256. }
  67257. }
  67258. effect.setArray2("dsOffsets", downSampleOffsets);
  67259. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67260. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67261. lastLuminance = _this.luminancePostProcess;
  67262. }
  67263. else {
  67264. lastLuminance = pp;
  67265. }
  67266. };
  67267. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67268. pp.onAfterRender = function (effect) {
  67269. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67270. 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);
  67271. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67272. };
  67273. }
  67274. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67275. });
  67276. };
  67277. // Create HDR post-process
  67278. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67279. var _this = this;
  67280. 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);
  67281. var outputLiminance = 1;
  67282. var time = 0;
  67283. var lastTime = 0;
  67284. this.hdrPostProcess.onApply = function (effect) {
  67285. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67286. time += scene.getEngine().getDeltaTime();
  67287. if (outputLiminance < 0) {
  67288. outputLiminance = _this._hdrCurrentLuminance;
  67289. }
  67290. else {
  67291. var dt = (lastTime - time) / 1000.0;
  67292. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67293. outputLiminance += _this.hdrDecreaseRate * dt;
  67294. }
  67295. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67296. outputLiminance -= _this.hdrIncreaseRate * dt;
  67297. }
  67298. else {
  67299. outputLiminance = _this._hdrCurrentLuminance;
  67300. }
  67301. }
  67302. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67303. effect.setFloat("averageLuminance", outputLiminance);
  67304. lastTime = time;
  67305. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67306. };
  67307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67308. };
  67309. // Create lens flare post-process
  67310. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67311. var _this = this;
  67312. 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);
  67313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67314. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67315. 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);
  67316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67317. var resolution = new BABYLON.Vector2(0, 0);
  67318. // Lens flare
  67319. this.lensFlarePostProcess.onApply = function (effect) {
  67320. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67321. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67322. effect.setFloat("strength", _this.lensFlareStrength);
  67323. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67324. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67325. // Shift
  67326. resolution.x = _this.lensFlarePostProcess.width;
  67327. resolution.y = _this.lensFlarePostProcess.height;
  67328. effect.setVector2("resolution", resolution);
  67329. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67330. };
  67331. // Compose
  67332. 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);
  67333. 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);
  67334. this.lensFlareComposePostProcess.onApply = function (effect) {
  67335. if (!_this._scene.activeCamera) {
  67336. return;
  67337. }
  67338. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67339. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67340. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67341. // Lens start rotation matrix
  67342. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67343. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67344. 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));
  67345. camRot *= 4.0;
  67346. 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);
  67347. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67348. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67349. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67350. };
  67351. };
  67352. // Create depth-of-field post-process
  67353. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67354. var _this = this;
  67355. 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);
  67356. this.depthOfFieldPostProcess.onApply = function (effect) {
  67357. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67358. effect.setTexture("depthSampler", _this._getDepthTexture());
  67359. effect.setFloat("distance", _this.depthOfFieldDistance);
  67360. };
  67361. // Add to pipeline
  67362. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67363. };
  67364. // Create motion blur post-process
  67365. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67366. var _this = this;
  67367. 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);
  67368. var motionScale = 0;
  67369. var prevViewProjection = BABYLON.Matrix.Identity();
  67370. var invViewProjection = BABYLON.Matrix.Identity();
  67371. var viewProjection = BABYLON.Matrix.Identity();
  67372. var screenSize = BABYLON.Vector2.Zero();
  67373. this.motionBlurPostProcess.onApply = function (effect) {
  67374. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67375. viewProjection.invertToRef(invViewProjection);
  67376. effect.setMatrix("inverseViewProjection", invViewProjection);
  67377. effect.setMatrix("prevViewProjection", prevViewProjection);
  67378. prevViewProjection = viewProjection;
  67379. screenSize.x = _this.motionBlurPostProcess.width;
  67380. screenSize.y = _this.motionBlurPostProcess.height;
  67381. effect.setVector2("screenSize", screenSize);
  67382. motionScale = scene.getEngine().getFps() / 60.0;
  67383. effect.setFloat("motionScale", motionScale);
  67384. effect.setFloat("motionStrength", _this.motionStrength);
  67385. effect.setTexture("depthSampler", _this._getDepthTexture());
  67386. };
  67387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67388. };
  67389. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67390. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67391. var renderer = this._scene.enableGeometryBufferRenderer();
  67392. return renderer.getGBuffer().textures[0];
  67393. }
  67394. return this._scene.enableDepthRenderer().getDepthMap();
  67395. };
  67396. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67397. for (var i = 0; i < this._cameras.length; i++) {
  67398. var camera = this._cameras[i];
  67399. if (this.originalPostProcess) {
  67400. this.originalPostProcess.dispose(camera);
  67401. }
  67402. if (this.downSampleX4PostProcess) {
  67403. this.downSampleX4PostProcess.dispose(camera);
  67404. }
  67405. if (this.brightPassPostProcess) {
  67406. this.brightPassPostProcess.dispose(camera);
  67407. }
  67408. if (this.textureAdderPostProcess) {
  67409. this.textureAdderPostProcess.dispose(camera);
  67410. }
  67411. if (this.textureAdderFinalPostProcess) {
  67412. this.textureAdderFinalPostProcess.dispose(camera);
  67413. }
  67414. if (this.volumetricLightPostProcess) {
  67415. this.volumetricLightPostProcess.dispose(camera);
  67416. }
  67417. if (this.volumetricLightSmoothXPostProcess) {
  67418. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67419. }
  67420. if (this.volumetricLightSmoothYPostProcess) {
  67421. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67422. }
  67423. if (this.volumetricLightMergePostProces) {
  67424. this.volumetricLightMergePostProces.dispose(camera);
  67425. }
  67426. if (this.volumetricLightFinalPostProcess) {
  67427. this.volumetricLightFinalPostProcess.dispose(camera);
  67428. }
  67429. if (this.lensFlarePostProcess) {
  67430. this.lensFlarePostProcess.dispose(camera);
  67431. }
  67432. if (this.lensFlareComposePostProcess) {
  67433. this.lensFlareComposePostProcess.dispose(camera);
  67434. }
  67435. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67436. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67437. }
  67438. if (this.luminancePostProcess) {
  67439. this.luminancePostProcess.dispose(camera);
  67440. }
  67441. if (this.hdrPostProcess) {
  67442. this.hdrPostProcess.dispose(camera);
  67443. }
  67444. if (this.hdrFinalPostProcess) {
  67445. this.hdrFinalPostProcess.dispose(camera);
  67446. }
  67447. if (this.depthOfFieldPostProcess) {
  67448. this.depthOfFieldPostProcess.dispose(camera);
  67449. }
  67450. if (this.motionBlurPostProcess) {
  67451. this.motionBlurPostProcess.dispose(camera);
  67452. }
  67453. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67454. this.blurHPostProcesses[j].dispose(camera);
  67455. }
  67456. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67457. this.blurVPostProcesses[j].dispose(camera);
  67458. }
  67459. }
  67460. this.originalPostProcess = null;
  67461. this.downSampleX4PostProcess = null;
  67462. this.brightPassPostProcess = null;
  67463. this.textureAdderPostProcess = null;
  67464. this.textureAdderFinalPostProcess = null;
  67465. this.volumetricLightPostProcess = null;
  67466. this.volumetricLightSmoothXPostProcess = null;
  67467. this.volumetricLightSmoothYPostProcess = null;
  67468. this.volumetricLightMergePostProces = null;
  67469. this.volumetricLightFinalPostProcess = null;
  67470. this.lensFlarePostProcess = null;
  67471. this.lensFlareComposePostProcess = null;
  67472. this.luminancePostProcess = null;
  67473. this.hdrPostProcess = null;
  67474. this.hdrFinalPostProcess = null;
  67475. this.depthOfFieldPostProcess = null;
  67476. this.motionBlurPostProcess = null;
  67477. this.luminanceDownSamplePostProcesses = [];
  67478. this.blurHPostProcesses = [];
  67479. this.blurVPostProcesses = [];
  67480. };
  67481. // Dispose
  67482. StandardRenderingPipeline.prototype.dispose = function () {
  67483. this._disposePostProcesses();
  67484. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67485. _super.prototype.dispose.call(this);
  67486. };
  67487. // Serialize rendering pipeline
  67488. StandardRenderingPipeline.prototype.serialize = function () {
  67489. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67490. serializationObject.customType = "StandardRenderingPipeline";
  67491. return serializationObject;
  67492. };
  67493. /**
  67494. * Static members
  67495. */
  67496. // Parse serialized pipeline
  67497. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67498. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67499. };
  67500. // Luminance steps
  67501. StandardRenderingPipeline.LuminanceSteps = 6;
  67502. __decorate([
  67503. BABYLON.serialize()
  67504. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67505. __decorate([
  67506. BABYLON.serialize()
  67507. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67508. __decorate([
  67509. BABYLON.serialize()
  67510. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67511. __decorate([
  67512. BABYLON.serialize()
  67513. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67514. __decorate([
  67515. BABYLON.serializeAsTexture("lensTexture")
  67516. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67517. __decorate([
  67518. BABYLON.serialize()
  67519. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67520. __decorate([
  67521. BABYLON.serialize()
  67522. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67523. __decorate([
  67524. BABYLON.serialize()
  67525. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67526. __decorate([
  67527. BABYLON.serialize()
  67528. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67529. __decorate([
  67530. BABYLON.serialize()
  67531. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67532. __decorate([
  67533. BABYLON.serialize()
  67534. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67535. __decorate([
  67536. BABYLON.serializeAsTexture("lensColorTexture")
  67537. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67538. __decorate([
  67539. BABYLON.serialize()
  67540. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67541. __decorate([
  67542. BABYLON.serialize()
  67543. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67544. __decorate([
  67545. BABYLON.serialize()
  67546. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67547. __decorate([
  67548. BABYLON.serialize()
  67549. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67550. __decorate([
  67551. BABYLON.serializeAsTexture("lensStarTexture")
  67552. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67553. __decorate([
  67554. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67555. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67556. __decorate([
  67557. BABYLON.serialize()
  67558. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67559. __decorate([
  67560. BABYLON.serialize()
  67561. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67562. __decorate([
  67563. BABYLON.serialize()
  67564. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67565. __decorate([
  67566. BABYLON.serialize()
  67567. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67568. __decorate([
  67569. BABYLON.serialize()
  67570. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67571. __decorate([
  67572. BABYLON.serialize()
  67573. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67574. __decorate([
  67575. BABYLON.serialize()
  67576. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67577. __decorate([
  67578. BABYLON.serialize()
  67579. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67580. __decorate([
  67581. BABYLON.serialize()
  67582. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67583. __decorate([
  67584. BABYLON.serialize()
  67585. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67586. __decorate([
  67587. BABYLON.serialize()
  67588. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67589. __decorate([
  67590. BABYLON.serialize()
  67591. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67592. return StandardRenderingPipeline;
  67593. }(BABYLON.PostProcessRenderPipeline));
  67594. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67595. })(BABYLON || (BABYLON = {}));
  67596. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67597. var BABYLON;
  67598. (function (BABYLON) {
  67599. var FxaaPostProcess = /** @class */ (function (_super) {
  67600. __extends(FxaaPostProcess, _super);
  67601. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67602. if (camera === void 0) { camera = null; }
  67603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67604. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67605. _this.onApplyObservable.add(function (effect) {
  67606. var texelSize = _this.texelSize;
  67607. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67608. });
  67609. return _this;
  67610. }
  67611. return FxaaPostProcess;
  67612. }(BABYLON.PostProcess));
  67613. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67614. })(BABYLON || (BABYLON = {}));
  67615. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67616. var BABYLON;
  67617. (function (BABYLON) {
  67618. /**
  67619. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67620. */
  67621. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67622. __extends(CircleOfConfusionPostProcess, _super);
  67623. /**
  67624. * Creates a new instance of @see CircleOfConfusionPostProcess
  67625. * @param name The name of the effect.
  67626. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67627. * @param options The required width/height ratio to downsize to before computing the render pass.
  67628. * @param camera The camera to apply the render pass to.
  67629. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67630. * @param engine The engine which the post process will be applied. (default: current engine)
  67631. * @param reusable If the post process can be reused on the same frame. (default: false)
  67632. * @param textureType Type of textures used when performing the post process. (default: 0)
  67633. */
  67634. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67635. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67636. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67637. /**
  67638. * 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.
  67639. */
  67640. _this.lensSize = 50;
  67641. /**
  67642. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67643. */
  67644. _this.fStop = 1.4;
  67645. /**
  67646. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67647. */
  67648. _this.focusDistance = 2000;
  67649. /**
  67650. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67651. */
  67652. _this.focalLength = 50;
  67653. _this.onApplyObservable.add(function (effect) {
  67654. effect.setTexture("depthSampler", depthTexture);
  67655. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67656. var aperture = _this.lensSize / _this.fStop;
  67657. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67658. effect.setFloat('focusDistance', _this.focusDistance);
  67659. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67660. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  67661. });
  67662. return _this;
  67663. }
  67664. return CircleOfConfusionPostProcess;
  67665. }(BABYLON.PostProcess));
  67666. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67667. })(BABYLON || (BABYLON = {}));
  67668. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67669. var BABYLON;
  67670. (function (BABYLON) {
  67671. /**
  67672. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67673. */
  67674. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67675. __extends(DepthOfFieldMergePostProcess, _super);
  67676. /**
  67677. * Creates a new instance of @see CircleOfConfusionPostProcess
  67678. * @param name The name of the effect.
  67679. * @param original The non-blurred image to be modified
  67680. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67681. * @param blurSteps Incrimental bluring post processes.
  67682. * @param options The required width/height ratio to downsize to before computing the render pass.
  67683. * @param camera The camera to apply the render pass to.
  67684. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67685. * @param engine The engine which the post process will be applied. (default: current engine)
  67686. * @param reusable If the post process can be reused on the same frame. (default: false)
  67687. * @param textureType Type of textures used when performing the post process. (default: 0)
  67688. */
  67689. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67690. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67691. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67692. _this.onApplyObservable.add(function (effect) {
  67693. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67694. effect.setTextureFromPostProcess("originalSampler", original);
  67695. blurSteps.forEach(function (step, index) {
  67696. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67697. });
  67698. });
  67699. return _this;
  67700. }
  67701. return DepthOfFieldMergePostProcess;
  67702. }(BABYLON.PostProcess));
  67703. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67704. })(BABYLON || (BABYLON = {}));
  67705. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67706. var BABYLON;
  67707. (function (BABYLON) {
  67708. /**
  67709. * Specifies the level of max blur that should be applied when using the depth of field effect
  67710. */
  67711. var DepthOfFieldEffectBlurLevel;
  67712. (function (DepthOfFieldEffectBlurLevel) {
  67713. /**
  67714. * Subtle blur
  67715. */
  67716. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67717. /**
  67718. * Medium blur
  67719. */
  67720. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67721. /**
  67722. * Large blur
  67723. */
  67724. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67725. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67726. ;
  67727. /**
  67728. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67729. */
  67730. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67731. __extends(DepthOfFieldEffect, _super);
  67732. /**
  67733. * Creates a new instance of @see DepthOfFieldEffect
  67734. * @param scene The scene the effect belongs to.
  67735. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67736. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67737. */
  67738. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67739. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67740. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67741. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67742. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67743. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67744. // Capture circle of confusion texture
  67745. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67746. _this._depthOfFieldPass.autoClear = false;
  67747. // 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)
  67748. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67749. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67750. _this._depthOfFieldBlurY = [];
  67751. _this._depthOfFieldBlurX = [];
  67752. var blurCount = 1;
  67753. var kernelSize = 15;
  67754. switch (blurLevel) {
  67755. case DepthOfFieldEffectBlurLevel.High: {
  67756. blurCount = 3;
  67757. kernelSize = 51;
  67758. break;
  67759. }
  67760. case DepthOfFieldEffectBlurLevel.Medium: {
  67761. blurCount = 2;
  67762. kernelSize = 31;
  67763. break;
  67764. }
  67765. default: {
  67766. kernelSize = 15;
  67767. blurCount = 1;
  67768. break;
  67769. }
  67770. }
  67771. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67772. for (var i = 0; i < blurCount; i++) {
  67773. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67774. blurY.autoClear = false;
  67775. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67776. blurX.autoClear = false;
  67777. _this._depthOfFieldBlurY.push(blurY);
  67778. _this._depthOfFieldBlurX.push(blurX);
  67779. }
  67780. // Merge blurred images with original image based on circleOfConfusion
  67781. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67782. _this._depthOfFieldMerge.autoClear = false;
  67783. // Set all post processes on the effect.
  67784. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67785. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67786. effects.push(_this._depthOfFieldBlurY[i]);
  67787. effects.push(_this._depthOfFieldBlurX[i]);
  67788. }
  67789. effects.push(_this._depthOfFieldMerge);
  67790. return effects;
  67791. }, true) || this;
  67792. return _this;
  67793. }
  67794. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67795. get: function () {
  67796. return this._circleOfConfusion.focalLength;
  67797. },
  67798. /**
  67799. * The focal the length of the camera used in the effect
  67800. */
  67801. set: function (value) {
  67802. this._circleOfConfusion.focalLength = value;
  67803. },
  67804. enumerable: true,
  67805. configurable: true
  67806. });
  67807. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67808. get: function () {
  67809. return this._circleOfConfusion.fStop;
  67810. },
  67811. /**
  67812. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67813. */
  67814. set: function (value) {
  67815. this._circleOfConfusion.fStop = value;
  67816. },
  67817. enumerable: true,
  67818. configurable: true
  67819. });
  67820. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67821. get: function () {
  67822. return this._circleOfConfusion.focusDistance;
  67823. },
  67824. /**
  67825. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67826. */
  67827. set: function (value) {
  67828. this._circleOfConfusion.focusDistance = value;
  67829. },
  67830. enumerable: true,
  67831. configurable: true
  67832. });
  67833. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67834. get: function () {
  67835. return this._circleOfConfusion.lensSize;
  67836. },
  67837. /**
  67838. * 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.
  67839. */
  67840. set: function (value) {
  67841. this._circleOfConfusion.lensSize = value;
  67842. },
  67843. enumerable: true,
  67844. configurable: true
  67845. });
  67846. /**
  67847. * Disposes each of the internal effects for a given camera.
  67848. * @param camera The camera to dispose the effect on.
  67849. */
  67850. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67851. this._depthOfFieldPass.dispose(camera);
  67852. this._circleOfConfusion.dispose(camera);
  67853. this._depthOfFieldBlurX.forEach(function (element) {
  67854. element.dispose(camera);
  67855. });
  67856. this._depthOfFieldBlurY.forEach(function (element) {
  67857. element.dispose(camera);
  67858. });
  67859. this._depthOfFieldMerge.dispose(camera);
  67860. };
  67861. return DepthOfFieldEffect;
  67862. }(BABYLON.PostProcessRenderEffect));
  67863. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67864. })(BABYLON || (BABYLON = {}));
  67865. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67866. var BABYLON;
  67867. (function (BABYLON) {
  67868. /**
  67869. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67870. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67871. */
  67872. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67873. __extends(DefaultRenderingPipeline, _super);
  67874. /**
  67875. * @constructor
  67876. * @param {string} name - The rendering pipeline name
  67877. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67878. * @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)
  67879. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67880. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67881. */
  67882. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67883. if (automaticBuild === void 0) { automaticBuild = true; }
  67884. var _this = _super.call(this, scene.getEngine(), name) || this;
  67885. /**
  67886. * ID of the sharpen post process,
  67887. */
  67888. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  67889. /**
  67890. * ID of the pass post process used for bloom,
  67891. */
  67892. _this.PassPostProcessId = "PassPostProcessEffect";
  67893. /**
  67894. * ID of the highlight post process used for bloom,
  67895. */
  67896. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67897. /**
  67898. * ID of the blurX post process used for bloom,
  67899. */
  67900. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67901. /**
  67902. * ID of the blurY post process used for bloom,
  67903. */
  67904. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67905. /**
  67906. * ID of the copy back post process used for bloom,
  67907. */
  67908. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67909. /**
  67910. * ID of the image processing post process;
  67911. */
  67912. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67913. /**
  67914. * ID of the Fast Approximate Anti-Aliasing post process;
  67915. */
  67916. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67917. /**
  67918. * ID of the final merge post process;
  67919. */
  67920. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67921. /**
  67922. * ID of the chromatic aberration post process,
  67923. */
  67924. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  67925. /**
  67926. * Animations which can be used to tweak settings over a period of time
  67927. */
  67928. _this.animations = [];
  67929. // Values
  67930. _this._sharpenEnabled = false;
  67931. _this._bloomEnabled = false;
  67932. _this._depthOfFieldEnabled = false;
  67933. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67934. _this._fxaaEnabled = false;
  67935. _this._msaaEnabled = false;
  67936. _this._imageProcessingEnabled = true;
  67937. _this._bloomScale = 0.6;
  67938. _this._chromaticAberrationEnabled = false;
  67939. _this._buildAllowed = true;
  67940. /**
  67941. * Specifies the size of the bloom blur kernel, relative to the final output size
  67942. */
  67943. _this.bloomKernel = 64;
  67944. /**
  67945. * Specifies the weight of the bloom in the final rendering
  67946. */
  67947. _this._bloomWeight = 0.15;
  67948. _this._cameras = cameras || [];
  67949. _this._buildAllowed = automaticBuild;
  67950. // Initialize
  67951. _this._scene = scene;
  67952. var caps = _this._scene.getEngine().getCaps();
  67953. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67954. // Misc
  67955. if (_this._hdr) {
  67956. if (caps.textureHalfFloatRender) {
  67957. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67958. }
  67959. else if (caps.textureFloatRender) {
  67960. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67961. }
  67962. }
  67963. else {
  67964. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67965. }
  67966. // Attach
  67967. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67968. _this._buildPipeline();
  67969. return _this;
  67970. }
  67971. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  67972. get: function () {
  67973. return this._sharpenEnabled;
  67974. },
  67975. /**
  67976. * Enable or disable the sharpen process from the pipeline
  67977. */
  67978. set: function (enabled) {
  67979. if (this._sharpenEnabled === enabled) {
  67980. return;
  67981. }
  67982. this._sharpenEnabled = enabled;
  67983. this._buildPipeline();
  67984. },
  67985. enumerable: true,
  67986. configurable: true
  67987. });
  67988. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67989. get: function () {
  67990. return this._bloomWeight;
  67991. },
  67992. /**
  67993. * The strength of the bloom.
  67994. */
  67995. set: function (value) {
  67996. if (this._bloomWeight === value) {
  67997. return;
  67998. }
  67999. this._bloomWeight = value;
  68000. if (this._hdr && this.copyBack) {
  68001. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  68002. }
  68003. },
  68004. enumerable: true,
  68005. configurable: true
  68006. });
  68007. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  68008. get: function () {
  68009. return this._bloomScale;
  68010. },
  68011. /**
  68012. * The scale of the bloom, lower value will provide better performance.
  68013. */
  68014. set: function (value) {
  68015. if (this._bloomScale === value) {
  68016. return;
  68017. }
  68018. this._bloomScale = value;
  68019. this._buildPipeline();
  68020. },
  68021. enumerable: true,
  68022. configurable: true
  68023. });
  68024. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  68025. get: function () {
  68026. return this._bloomEnabled;
  68027. },
  68028. /**
  68029. * Enable or disable the bloom from the pipeline
  68030. */
  68031. set: function (enabled) {
  68032. if (this._bloomEnabled === enabled) {
  68033. return;
  68034. }
  68035. this._bloomEnabled = enabled;
  68036. this._buildPipeline();
  68037. },
  68038. enumerable: true,
  68039. configurable: true
  68040. });
  68041. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  68042. /**
  68043. * If the depth of field is enabled.
  68044. */
  68045. get: function () {
  68046. return this._depthOfFieldEnabled;
  68047. },
  68048. set: function (enabled) {
  68049. if (this._depthOfFieldEnabled === enabled) {
  68050. return;
  68051. }
  68052. this._depthOfFieldEnabled = enabled;
  68053. this._buildPipeline();
  68054. },
  68055. enumerable: true,
  68056. configurable: true
  68057. });
  68058. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  68059. /**
  68060. * Blur level of the depth of field effect. (Higher blur will effect performance)
  68061. */
  68062. get: function () {
  68063. return this._depthOfFieldBlurLevel;
  68064. },
  68065. set: function (value) {
  68066. if (this._depthOfFieldBlurLevel === value) {
  68067. return;
  68068. }
  68069. this._depthOfFieldBlurLevel = value;
  68070. this._buildPipeline();
  68071. },
  68072. enumerable: true,
  68073. configurable: true
  68074. });
  68075. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  68076. get: function () {
  68077. return this._fxaaEnabled;
  68078. },
  68079. /**
  68080. * If the anti aliasing is enabled.
  68081. */
  68082. set: function (enabled) {
  68083. if (this._fxaaEnabled === enabled) {
  68084. return;
  68085. }
  68086. this._fxaaEnabled = enabled;
  68087. this._buildPipeline();
  68088. },
  68089. enumerable: true,
  68090. configurable: true
  68091. });
  68092. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  68093. get: function () {
  68094. return this._msaaEnabled;
  68095. },
  68096. /**
  68097. * If the multisample anti-aliasing is enabled.
  68098. */
  68099. set: function (enabled) {
  68100. if (this._msaaEnabled === enabled) {
  68101. return;
  68102. }
  68103. this._msaaEnabled = enabled;
  68104. this._buildPipeline();
  68105. },
  68106. enumerable: true,
  68107. configurable: true
  68108. });
  68109. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68110. get: function () {
  68111. return this._imageProcessingEnabled;
  68112. },
  68113. /**
  68114. * If image processing is enabled.
  68115. */
  68116. set: function (enabled) {
  68117. if (this._imageProcessingEnabled === enabled) {
  68118. return;
  68119. }
  68120. this._imageProcessingEnabled = enabled;
  68121. this._buildPipeline();
  68122. },
  68123. enumerable: true,
  68124. configurable: true
  68125. });
  68126. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  68127. get: function () {
  68128. return this._chromaticAberrationEnabled;
  68129. },
  68130. /**
  68131. * Enable or disable the chromaticAberration process from the pipeline
  68132. */
  68133. set: function (enabled) {
  68134. if (this._chromaticAberrationEnabled === enabled) {
  68135. return;
  68136. }
  68137. this._chromaticAberrationEnabled = enabled;
  68138. this._buildPipeline();
  68139. },
  68140. enumerable: true,
  68141. configurable: true
  68142. });
  68143. /**
  68144. * Force the compilation of the entire pipeline.
  68145. */
  68146. DefaultRenderingPipeline.prototype.prepare = function () {
  68147. var previousState = this._buildAllowed;
  68148. this._buildAllowed = true;
  68149. this._buildPipeline();
  68150. this._buildAllowed = previousState;
  68151. };
  68152. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68153. var _this = this;
  68154. if (!this._buildAllowed) {
  68155. return;
  68156. }
  68157. var engine = this._scene.getEngine();
  68158. this._disposePostProcesses();
  68159. this._reset();
  68160. if (this.sharpenEnabled) {
  68161. this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68162. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.SharpenPostProcessId, function () { return _this.sharpen; }, true));
  68163. }
  68164. if (this.depthOfFieldEnabled) {
  68165. // Enable and get current depth map
  68166. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68167. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68168. this.addEffect(this.depthOfField);
  68169. }
  68170. if (this.bloomEnabled) {
  68171. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68172. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68173. if (!this._hdr) {
  68174. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68175. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68176. this.highlights.autoClear = false;
  68177. this.highlights.alwaysForcePOT = true;
  68178. }
  68179. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68180. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68181. this.blurX.alwaysForcePOT = true;
  68182. this.blurX.autoClear = false;
  68183. this.blurX.onActivateObservable.add(function () {
  68184. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68185. _this.blurX.kernel = _this.bloomKernel * dw;
  68186. });
  68187. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68188. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68189. this.blurY.alwaysForcePOT = true;
  68190. this.blurY.autoClear = false;
  68191. this.blurY.onActivateObservable.add(function () {
  68192. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68193. _this.blurY.kernel = _this.bloomKernel * dh;
  68194. });
  68195. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68196. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68197. this.copyBack.alwaysForcePOT = true;
  68198. if (this._hdr) {
  68199. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68200. var w = this.bloomWeight;
  68201. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68202. }
  68203. else {
  68204. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68205. }
  68206. this.copyBack.autoClear = false;
  68207. }
  68208. if (this._imageProcessingEnabled) {
  68209. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68210. if (this._hdr) {
  68211. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68212. }
  68213. else {
  68214. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68215. }
  68216. }
  68217. if (this.fxaaEnabled) {
  68218. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68219. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68220. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68221. }
  68222. else if (this._hdr && this.imageProcessing) {
  68223. this.finalMerge = this.imageProcessing;
  68224. }
  68225. else {
  68226. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68227. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68228. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68229. }
  68230. if (this.bloomEnabled) {
  68231. if (this._hdr) {
  68232. this.copyBack.shareOutputWith(this.blurX);
  68233. if (this.imageProcessing) {
  68234. this.imageProcessing.shareOutputWith(this.pass);
  68235. this.imageProcessing.autoClear = false;
  68236. }
  68237. else if (this.fxaa) {
  68238. this.fxaa.shareOutputWith(this.pass);
  68239. }
  68240. else {
  68241. this.finalMerge.shareOutputWith(this.pass);
  68242. }
  68243. }
  68244. else {
  68245. if (this.fxaa) {
  68246. this.fxaa.shareOutputWith(this.pass);
  68247. }
  68248. else {
  68249. this.finalMerge.shareOutputWith(this.pass);
  68250. }
  68251. }
  68252. }
  68253. if (this.chromaticAberrationEnabled) {
  68254. this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68255. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true));
  68256. }
  68257. if (this._cameras !== null) {
  68258. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68259. }
  68260. if (this.msaaEnabled) {
  68261. if (!this._enableMSAAOnFirstPostProcess()) {
  68262. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68263. }
  68264. }
  68265. };
  68266. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68267. for (var i = 0; i < this._cameras.length; i++) {
  68268. var camera = this._cameras[i];
  68269. if (this.sharpen) {
  68270. this.sharpen.dispose(camera);
  68271. }
  68272. if (this.pass) {
  68273. this.pass.dispose(camera);
  68274. }
  68275. if (this.highlights) {
  68276. this.highlights.dispose(camera);
  68277. }
  68278. if (this.blurX) {
  68279. this.blurX.dispose(camera);
  68280. }
  68281. if (this.blurY) {
  68282. this.blurY.dispose(camera);
  68283. }
  68284. if (this.copyBack) {
  68285. this.copyBack.dispose(camera);
  68286. }
  68287. if (this.imageProcessing) {
  68288. this.imageProcessing.dispose(camera);
  68289. }
  68290. if (this.fxaa) {
  68291. this.fxaa.dispose(camera);
  68292. }
  68293. if (this.finalMerge) {
  68294. this.finalMerge.dispose(camera);
  68295. }
  68296. if (this.depthOfField) {
  68297. this.depthOfField.disposeEffects(camera);
  68298. }
  68299. if (this.chromaticAberration) {
  68300. this.chromaticAberration.dispose(camera);
  68301. }
  68302. }
  68303. this.sharpen = null;
  68304. this.pass = null;
  68305. this.highlights = null;
  68306. this.blurX = null;
  68307. this.blurY = null;
  68308. this.copyBack = null;
  68309. this.imageProcessing = null;
  68310. this.fxaa = null;
  68311. this.finalMerge = null;
  68312. this.depthOfField = null;
  68313. this.chromaticAberration = null;
  68314. };
  68315. /**
  68316. * Dispose of the pipeline and stop all post processes
  68317. */
  68318. DefaultRenderingPipeline.prototype.dispose = function () {
  68319. this._disposePostProcesses();
  68320. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68321. _super.prototype.dispose.call(this);
  68322. };
  68323. /**
  68324. * Serialize the rendering pipeline (Used when exporting)
  68325. * @returns the serialized object
  68326. */
  68327. DefaultRenderingPipeline.prototype.serialize = function () {
  68328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68329. serializationObject.customType = "DefaultRenderingPipeline";
  68330. return serializationObject;
  68331. };
  68332. /**
  68333. * Parse the serialized pipeline
  68334. * @param source Source pipeline.
  68335. * @param scene The scene to load the pipeline to.
  68336. * @param rootUrl The URL of the serialized pipeline.
  68337. * @returns An instantiated pipeline from the serialized object.
  68338. */
  68339. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68340. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68341. };
  68342. __decorate([
  68343. BABYLON.serialize()
  68344. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68345. __decorate([
  68346. BABYLON.serialize()
  68347. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68348. __decorate([
  68349. BABYLON.serialize()
  68350. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68351. __decorate([
  68352. BABYLON.serialize()
  68353. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68354. __decorate([
  68355. BABYLON.serialize()
  68356. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68357. __decorate([
  68358. BABYLON.serialize()
  68359. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68360. __decorate([
  68361. BABYLON.serialize()
  68362. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68363. __decorate([
  68364. BABYLON.serialize()
  68365. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68366. __decorate([
  68367. BABYLON.serialize()
  68368. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68369. __decorate([
  68370. BABYLON.serialize()
  68371. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68372. __decorate([
  68373. BABYLON.serialize()
  68374. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68375. __decorate([
  68376. BABYLON.serialize()
  68377. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68378. __decorate([
  68379. BABYLON.serialize()
  68380. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  68381. return DefaultRenderingPipeline;
  68382. }(BABYLON.PostProcessRenderPipeline));
  68383. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68384. })(BABYLON || (BABYLON = {}));
  68385. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68386. var BABYLON;
  68387. (function (BABYLON) {
  68388. /**
  68389. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68390. */
  68391. var GeometryBufferRenderer = /** @class */ (function () {
  68392. /**
  68393. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68394. * @param scene The scene the buffer belongs to
  68395. * @param ratio How big is the buffer related to the main canvas.
  68396. */
  68397. function GeometryBufferRenderer(scene, ratio) {
  68398. if (ratio === void 0) { ratio = 1; }
  68399. this._enablePosition = false;
  68400. this._scene = scene;
  68401. this._ratio = ratio;
  68402. // Render target
  68403. this._createRenderTargets();
  68404. }
  68405. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68406. /**
  68407. * Set the render list (meshes to be rendered) used in the G buffer.
  68408. */
  68409. set: function (meshes) {
  68410. this._multiRenderTarget.renderList = meshes;
  68411. },
  68412. enumerable: true,
  68413. configurable: true
  68414. });
  68415. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68416. /**
  68417. * Gets wether or not G buffer are supported by the running hardware.
  68418. * This requires draw buffer supports
  68419. */
  68420. get: function () {
  68421. return this._multiRenderTarget.isSupported;
  68422. },
  68423. enumerable: true,
  68424. configurable: true
  68425. });
  68426. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68427. /**
  68428. * Gets wether or not position are enabled for the G buffer.
  68429. */
  68430. get: function () {
  68431. return this._enablePosition;
  68432. },
  68433. /**
  68434. * Sets wether or not position are enabled for the G buffer.
  68435. */
  68436. set: function (enable) {
  68437. this._enablePosition = enable;
  68438. this.dispose();
  68439. this._createRenderTargets();
  68440. },
  68441. enumerable: true,
  68442. configurable: true
  68443. });
  68444. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68445. /**
  68446. * Gets the scene associated with the buffer.
  68447. */
  68448. get: function () {
  68449. return this._scene;
  68450. },
  68451. enumerable: true,
  68452. configurable: true
  68453. });
  68454. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68455. /**
  68456. * Gets the ratio used by the buffer during its creation.
  68457. * How big is the buffer related to the main canvas.
  68458. */
  68459. get: function () {
  68460. return this._ratio;
  68461. },
  68462. enumerable: true,
  68463. configurable: true
  68464. });
  68465. /**
  68466. * Checks wether everything is ready to render a submesh to the G buffer.
  68467. * @param subMesh the submesh to check readiness for
  68468. * @param useInstances is the mesh drawn using instance or not
  68469. * @returns true if ready otherwise false
  68470. */
  68471. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68472. var material = subMesh.getMaterial();
  68473. if (material && material.disableDepthWrite) {
  68474. return false;
  68475. }
  68476. var defines = [];
  68477. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68478. var mesh = subMesh.getMesh();
  68479. // Alpha test
  68480. if (material && material.needAlphaTesting()) {
  68481. defines.push("#define ALPHATEST");
  68482. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68483. attribs.push(BABYLON.VertexBuffer.UVKind);
  68484. defines.push("#define UV1");
  68485. }
  68486. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68487. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68488. defines.push("#define UV2");
  68489. }
  68490. }
  68491. // Buffers
  68492. if (this._enablePosition) {
  68493. defines.push("#define POSITION");
  68494. }
  68495. // Bones
  68496. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68497. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68498. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68499. if (mesh.numBoneInfluencers > 4) {
  68500. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68501. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68502. }
  68503. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68504. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68505. }
  68506. else {
  68507. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68508. }
  68509. // Instances
  68510. if (useInstances) {
  68511. defines.push("#define INSTANCES");
  68512. attribs.push("world0");
  68513. attribs.push("world1");
  68514. attribs.push("world2");
  68515. attribs.push("world3");
  68516. }
  68517. // Get correct effect
  68518. var join = defines.join("\n");
  68519. if (this._cachedDefines !== join) {
  68520. this._cachedDefines = join;
  68521. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68522. }
  68523. return this._effect.isReady();
  68524. };
  68525. /**
  68526. * Gets the current underlying G Buffer.
  68527. * @returns the buffer
  68528. */
  68529. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68530. return this._multiRenderTarget;
  68531. };
  68532. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68533. /**
  68534. * Gets the number of samples used to render the buffer (anti aliasing).
  68535. */
  68536. get: function () {
  68537. return this._multiRenderTarget.samples;
  68538. },
  68539. /**
  68540. * Sets the number of samples used to render the buffer (anti aliasing).
  68541. */
  68542. set: function (value) {
  68543. this._multiRenderTarget.samples = value;
  68544. },
  68545. enumerable: true,
  68546. configurable: true
  68547. });
  68548. /**
  68549. * Disposes the renderer and frees up associated resources.
  68550. */
  68551. GeometryBufferRenderer.prototype.dispose = function () {
  68552. this.getGBuffer().dispose();
  68553. };
  68554. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68555. var _this = this;
  68556. var engine = this._scene.getEngine();
  68557. var count = this._enablePosition ? 3 : 2;
  68558. 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 });
  68559. if (!this.isSupported) {
  68560. return;
  68561. }
  68562. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68563. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68564. this._multiRenderTarget.refreshRate = 1;
  68565. this._multiRenderTarget.renderParticles = false;
  68566. this._multiRenderTarget.renderList = null;
  68567. // set default depth value to 1.0 (far away)
  68568. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68569. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68570. });
  68571. // Custom render function
  68572. var renderSubMesh = function (subMesh) {
  68573. var mesh = subMesh.getRenderingMesh();
  68574. var scene = _this._scene;
  68575. var engine = scene.getEngine();
  68576. var material = subMesh.getMaterial();
  68577. if (!material) {
  68578. return;
  68579. }
  68580. // Culling
  68581. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68582. // Managing instances
  68583. var batch = mesh._getInstancesRenderList(subMesh._id);
  68584. if (batch.mustReturn) {
  68585. return;
  68586. }
  68587. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68588. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68589. engine.enableEffect(_this._effect);
  68590. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68591. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68592. _this._effect.setMatrix("view", scene.getViewMatrix());
  68593. // Alpha test
  68594. if (material && material.needAlphaTesting()) {
  68595. var alphaTexture = material.getAlphaTestTexture();
  68596. if (alphaTexture) {
  68597. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68598. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68599. }
  68600. }
  68601. // Bones
  68602. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68603. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68604. }
  68605. // Draw
  68606. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68607. }
  68608. };
  68609. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68610. var index;
  68611. if (depthOnlySubMeshes.length) {
  68612. engine.setColorWrite(false);
  68613. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68614. renderSubMesh(depthOnlySubMeshes.data[index]);
  68615. }
  68616. engine.setColorWrite(true);
  68617. }
  68618. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68619. renderSubMesh(opaqueSubMeshes.data[index]);
  68620. }
  68621. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68622. renderSubMesh(alphaTestSubMeshes.data[index]);
  68623. }
  68624. };
  68625. };
  68626. return GeometryBufferRenderer;
  68627. }());
  68628. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68629. })(BABYLON || (BABYLON = {}));
  68630. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68631. var BABYLON;
  68632. (function (BABYLON) {
  68633. var RefractionPostProcess = /** @class */ (function (_super) {
  68634. __extends(RefractionPostProcess, _super);
  68635. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68636. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68637. _this.color = color;
  68638. _this.depth = depth;
  68639. _this.colorLevel = colorLevel;
  68640. _this._ownRefractionTexture = true;
  68641. _this.onActivateObservable.add(function (cam) {
  68642. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68643. });
  68644. _this.onApplyObservable.add(function (effect) {
  68645. effect.setColor3("baseColor", _this.color);
  68646. effect.setFloat("depth", _this.depth);
  68647. effect.setFloat("colorLevel", _this.colorLevel);
  68648. effect.setTexture("refractionSampler", _this._refTexture);
  68649. });
  68650. return _this;
  68651. }
  68652. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68653. /**
  68654. * Gets or sets the refraction texture
  68655. * Please note that you are responsible for disposing the texture if you set it manually
  68656. */
  68657. get: function () {
  68658. return this._refTexture;
  68659. },
  68660. set: function (value) {
  68661. if (this._refTexture && this._ownRefractionTexture) {
  68662. this._refTexture.dispose();
  68663. }
  68664. this._refTexture = value;
  68665. this._ownRefractionTexture = false;
  68666. },
  68667. enumerable: true,
  68668. configurable: true
  68669. });
  68670. // Methods
  68671. RefractionPostProcess.prototype.dispose = function (camera) {
  68672. if (this._refTexture && this._ownRefractionTexture) {
  68673. this._refTexture.dispose();
  68674. this._refTexture = null;
  68675. }
  68676. _super.prototype.dispose.call(this, camera);
  68677. };
  68678. return RefractionPostProcess;
  68679. }(BABYLON.PostProcess));
  68680. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68681. })(BABYLON || (BABYLON = {}));
  68682. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68683. var BABYLON;
  68684. (function (BABYLON) {
  68685. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68686. __extends(BlackAndWhitePostProcess, _super);
  68687. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68688. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68689. _this.degree = 1;
  68690. _this.onApplyObservable.add(function (effect) {
  68691. effect.setFloat("degree", _this.degree);
  68692. });
  68693. return _this;
  68694. }
  68695. return BlackAndWhitePostProcess;
  68696. }(BABYLON.PostProcess));
  68697. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68698. })(BABYLON || (BABYLON = {}));
  68699. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68700. var BABYLON;
  68701. (function (BABYLON) {
  68702. /**
  68703. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  68704. * input texture to perform effects such as edge detection or sharpening
  68705. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68706. */
  68707. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68708. __extends(ConvolutionPostProcess, _super);
  68709. /**
  68710. * Creates a new instance of @see ConvolutionPostProcess
  68711. * @param name The name of the effect.
  68712. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  68713. * @param options The required width/height ratio to downsize to before computing the render pass.
  68714. * @param camera The camera to apply the render pass to.
  68715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68716. * @param engine The engine which the post process will be applied. (default: current engine)
  68717. * @param reusable If the post process can be reused on the same frame. (default: false)
  68718. * @param textureType Type of textures used when performing the post process. (default: 0)
  68719. */
  68720. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  68721. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68722. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68723. _this.kernel = kernel;
  68724. _this.onApply = function (effect) {
  68725. effect.setFloat2("screenSize", _this.width, _this.height);
  68726. effect.setArray("kernel", _this.kernel);
  68727. };
  68728. return _this;
  68729. }
  68730. // Statics
  68731. /**
  68732. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68733. */
  68734. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68735. /**
  68736. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68737. */
  68738. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68739. /**
  68740. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68741. */
  68742. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68743. /**
  68744. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68745. */
  68746. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68747. /**
  68748. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68749. */
  68750. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68751. /**
  68752. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68753. */
  68754. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68755. return ConvolutionPostProcess;
  68756. }(BABYLON.PostProcess));
  68757. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68758. })(BABYLON || (BABYLON = {}));
  68759. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68760. var BABYLON;
  68761. (function (BABYLON) {
  68762. /**
  68763. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68764. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68765. */
  68766. var SharpenPostProcess = /** @class */ (function (_super) {
  68767. __extends(SharpenPostProcess, _super);
  68768. /**
  68769. * Creates a new instance of @see ConvolutionPostProcess
  68770. * @param name The name of the effect.
  68771. * @param options The required width/height ratio to downsize to before computing the render pass.
  68772. * @param camera The camera to apply the render pass to.
  68773. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68774. * @param engine The engine which the post process will be applied. (default: current engine)
  68775. * @param reusable If the post process can be reused on the same frame. (default: false)
  68776. * @param textureType Type of textures used when performing the post process. (default: 0)
  68777. */
  68778. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68780. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68781. /**
  68782. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68783. */
  68784. _this.colorAmount = 1.0;
  68785. /**
  68786. * How much sharpness should be applied (default: 0.3)
  68787. */
  68788. _this.edgeAmount = 0.3;
  68789. _this.onApply = function (effect) {
  68790. effect.setFloat2("screenSize", _this.width, _this.height);
  68791. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68792. };
  68793. return _this;
  68794. }
  68795. return SharpenPostProcess;
  68796. }(BABYLON.PostProcess));
  68797. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68798. })(BABYLON || (BABYLON = {}));
  68799. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68800. var BABYLON;
  68801. (function (BABYLON) {
  68802. /**
  68803. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68804. */
  68805. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68806. __extends(ChromaticAberrationPostProcess, _super);
  68807. /**
  68808. * Creates a new instance of @see ChromaticAberrationPostProcess
  68809. * @param name The name of the effect.
  68810. * @param screenWidth The width of the screen to apply the effect on.
  68811. * @param screenHeight The height of the screen to apply the effect on.
  68812. * @param options The required width/height ratio to downsize to before computing the render pass.
  68813. * @param camera The camera to apply the render pass to.
  68814. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68815. * @param engine The engine which the post process will be applied. (default: current engine)
  68816. * @param reusable If the post process can be reused on the same frame. (default: false)
  68817. * @param textureType Type of textures used when performing the post process. (default: 0)
  68818. */
  68819. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType) {
  68820. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68821. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68822. /**
  68823. * The amount of seperation of rgb channels (default: 0)
  68824. */
  68825. _this.aberrationAmount = 0;
  68826. /**
  68827. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68828. */
  68829. _this.radialIntensity = 0;
  68830. /**
  68831. * 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))
  68832. */
  68833. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68834. /**
  68835. * 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))
  68836. */
  68837. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68838. _this.onApplyObservable.add(function (effect) {
  68839. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68840. effect.setFloat('screen_width', screenWidth);
  68841. effect.setFloat('screen_height', screenHeight);
  68842. effect.setFloat('radialIntensity', _this.radialIntensity);
  68843. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68844. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68845. });
  68846. return _this;
  68847. }
  68848. return ChromaticAberrationPostProcess;
  68849. }(BABYLON.PostProcess));
  68850. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68851. })(BABYLON || (BABYLON = {}));
  68852. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68853. var BABYLON;
  68854. (function (BABYLON) {
  68855. var FilterPostProcess = /** @class */ (function (_super) {
  68856. __extends(FilterPostProcess, _super);
  68857. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68858. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68859. _this.kernelMatrix = kernelMatrix;
  68860. _this.onApply = function (effect) {
  68861. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68862. };
  68863. return _this;
  68864. }
  68865. return FilterPostProcess;
  68866. }(BABYLON.PostProcess));
  68867. BABYLON.FilterPostProcess = FilterPostProcess;
  68868. })(BABYLON || (BABYLON = {}));
  68869. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68870. var BABYLON;
  68871. (function (BABYLON) {
  68872. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68873. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68874. __extends(VolumetricLightScatteringPostProcess, _super);
  68875. /**
  68876. * @constructor
  68877. * @param {string} name - The post-process name
  68878. * @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)
  68879. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68880. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68881. * @param {number} samples - The post-process quality, default 100
  68882. * @param {number} samplingMode - The post-process filtering mode
  68883. * @param {BABYLON.Engine} engine - The babylon engine
  68884. * @param {boolean} reusable - If the post-process is reusable
  68885. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68886. */
  68887. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68888. if (samples === void 0) { samples = 100; }
  68889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68890. 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;
  68891. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68892. /**
  68893. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68894. * @type {Vector3}
  68895. */
  68896. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68897. /**
  68898. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68899. * @type {boolean}
  68900. */
  68901. _this.useCustomMeshPosition = false;
  68902. /**
  68903. * If the post-process should inverse the light scattering direction
  68904. * @type {boolean}
  68905. */
  68906. _this.invert = true;
  68907. /**
  68908. * Array containing the excluded meshes not rendered in the internal pass
  68909. */
  68910. _this.excludedMeshes = new Array();
  68911. /**
  68912. * Controls the overall intensity of the post-process
  68913. * @type {number}
  68914. */
  68915. _this.exposure = 0.3;
  68916. /**
  68917. * Dissipates each sample's contribution in range [0, 1]
  68918. * @type {number}
  68919. */
  68920. _this.decay = 0.96815;
  68921. /**
  68922. * Controls the overall intensity of each sample
  68923. * @type {number}
  68924. */
  68925. _this.weight = 0.58767;
  68926. /**
  68927. * Controls the density of each sample
  68928. * @type {number}
  68929. */
  68930. _this.density = 0.926;
  68931. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68932. engine = scene.getEngine();
  68933. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68934. // Configure mesh
  68935. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68936. // Configure
  68937. _this._createPass(scene, ratio.passRatio || ratio);
  68938. _this.onActivate = function (camera) {
  68939. if (!_this.isSupported) {
  68940. _this.dispose(camera);
  68941. }
  68942. _this.onActivate = null;
  68943. };
  68944. _this.onApplyObservable.add(function (effect) {
  68945. _this._updateMeshScreenCoordinates(scene);
  68946. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68947. effect.setFloat("exposure", _this.exposure);
  68948. effect.setFloat("decay", _this.decay);
  68949. effect.setFloat("weight", _this.weight);
  68950. effect.setFloat("density", _this.density);
  68951. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68952. });
  68953. return _this;
  68954. }
  68955. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68956. get: function () {
  68957. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68958. return false;
  68959. },
  68960. set: function (useDiffuseColor) {
  68961. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68962. },
  68963. enumerable: true,
  68964. configurable: true
  68965. });
  68966. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68967. return "VolumetricLightScatteringPostProcess";
  68968. };
  68969. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68970. var mesh = subMesh.getMesh();
  68971. // Render this.mesh as default
  68972. if (mesh === this.mesh && mesh.material) {
  68973. return mesh.material.isReady(mesh);
  68974. }
  68975. var defines = [];
  68976. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68977. var material = subMesh.getMaterial();
  68978. // Alpha test
  68979. if (material) {
  68980. if (material.needAlphaTesting()) {
  68981. defines.push("#define ALPHATEST");
  68982. }
  68983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68984. attribs.push(BABYLON.VertexBuffer.UVKind);
  68985. defines.push("#define UV1");
  68986. }
  68987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68988. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68989. defines.push("#define UV2");
  68990. }
  68991. }
  68992. // Bones
  68993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68996. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68997. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68998. }
  68999. else {
  69000. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69001. }
  69002. // Instances
  69003. if (useInstances) {
  69004. defines.push("#define INSTANCES");
  69005. attribs.push("world0");
  69006. attribs.push("world1");
  69007. attribs.push("world2");
  69008. attribs.push("world3");
  69009. }
  69010. // Get correct effect
  69011. var join = defines.join("\n");
  69012. if (this._cachedDefines !== join) {
  69013. this._cachedDefines = join;
  69014. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  69015. }
  69016. return this._volumetricLightScatteringPass.isReady();
  69017. };
  69018. /**
  69019. * Sets the new light position for light scattering effect
  69020. * @param {BABYLON.Vector3} The new custom light position
  69021. */
  69022. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  69023. this.customMeshPosition = position;
  69024. };
  69025. /**
  69026. * Returns the light position for light scattering effect
  69027. * @return {BABYLON.Vector3} The custom light position
  69028. */
  69029. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  69030. return this.customMeshPosition;
  69031. };
  69032. /**
  69033. * Disposes the internal assets and detaches the post-process from the camera
  69034. */
  69035. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  69036. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  69037. if (rttIndex !== -1) {
  69038. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  69039. }
  69040. this._volumetricLightScatteringRTT.dispose();
  69041. _super.prototype.dispose.call(this, camera);
  69042. };
  69043. /**
  69044. * Returns the render target texture used by the post-process
  69045. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  69046. */
  69047. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  69048. return this._volumetricLightScatteringRTT;
  69049. };
  69050. // Private methods
  69051. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  69052. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  69053. return true;
  69054. }
  69055. return false;
  69056. };
  69057. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  69058. var _this = this;
  69059. var engine = scene.getEngine();
  69060. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69061. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69062. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69063. this._volumetricLightScatteringRTT.renderList = null;
  69064. this._volumetricLightScatteringRTT.renderParticles = false;
  69065. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  69066. var camera = this.getCamera();
  69067. if (camera) {
  69068. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69069. }
  69070. else {
  69071. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  69072. }
  69073. // Custom render function for submeshes
  69074. var renderSubMesh = function (subMesh) {
  69075. var mesh = subMesh.getRenderingMesh();
  69076. if (_this._meshExcluded(mesh)) {
  69077. return;
  69078. }
  69079. var material = subMesh.getMaterial();
  69080. if (!material) {
  69081. return;
  69082. }
  69083. var scene = mesh.getScene();
  69084. var engine = scene.getEngine();
  69085. // Culling
  69086. engine.setState(material.backFaceCulling);
  69087. // Managing instances
  69088. var batch = mesh._getInstancesRenderList(subMesh._id);
  69089. if (batch.mustReturn) {
  69090. return;
  69091. }
  69092. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  69093. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  69094. var effect = _this._volumetricLightScatteringPass;
  69095. if (mesh === _this.mesh) {
  69096. if (subMesh.effect) {
  69097. effect = subMesh.effect;
  69098. }
  69099. else {
  69100. effect = material.getEffect();
  69101. }
  69102. }
  69103. engine.enableEffect(effect);
  69104. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  69105. if (mesh === _this.mesh) {
  69106. material.bind(mesh.getWorldMatrix(), mesh);
  69107. }
  69108. else {
  69109. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  69110. // Alpha test
  69111. if (material && material.needAlphaTesting()) {
  69112. var alphaTexture = material.getAlphaTestTexture();
  69113. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  69114. if (alphaTexture) {
  69115. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69116. }
  69117. }
  69118. // Bones
  69119. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  69120. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69121. }
  69122. }
  69123. // Draw
  69124. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  69125. }
  69126. };
  69127. // Render target texture callbacks
  69128. var savedSceneClearColor;
  69129. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  69130. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  69131. savedSceneClearColor = scene.clearColor;
  69132. scene.clearColor = sceneClearColor;
  69133. });
  69134. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  69135. scene.clearColor = savedSceneClearColor;
  69136. });
  69137. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69138. var engine = scene.getEngine();
  69139. var index;
  69140. if (depthOnlySubMeshes.length) {
  69141. engine.setColorWrite(false);
  69142. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69143. renderSubMesh(depthOnlySubMeshes.data[index]);
  69144. }
  69145. engine.setColorWrite(true);
  69146. }
  69147. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69148. renderSubMesh(opaqueSubMeshes.data[index]);
  69149. }
  69150. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69151. renderSubMesh(alphaTestSubMeshes.data[index]);
  69152. }
  69153. if (transparentSubMeshes.length) {
  69154. // Sort sub meshes
  69155. for (index = 0; index < transparentSubMeshes.length; index++) {
  69156. var submesh = transparentSubMeshes.data[index];
  69157. var boundingInfo = submesh.getBoundingInfo();
  69158. if (boundingInfo && scene.activeCamera) {
  69159. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  69160. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  69161. }
  69162. }
  69163. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  69164. sortedArray.sort(function (a, b) {
  69165. // Alpha index first
  69166. if (a._alphaIndex > b._alphaIndex) {
  69167. return 1;
  69168. }
  69169. if (a._alphaIndex < b._alphaIndex) {
  69170. return -1;
  69171. }
  69172. // Then distance to camera
  69173. if (a._distanceToCamera < b._distanceToCamera) {
  69174. return 1;
  69175. }
  69176. if (a._distanceToCamera > b._distanceToCamera) {
  69177. return -1;
  69178. }
  69179. return 0;
  69180. });
  69181. // Render sub meshes
  69182. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  69183. for (index = 0; index < sortedArray.length; index++) {
  69184. renderSubMesh(sortedArray[index]);
  69185. }
  69186. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69187. }
  69188. };
  69189. };
  69190. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  69191. var transform = scene.getTransformMatrix();
  69192. var meshPosition;
  69193. if (this.useCustomMeshPosition) {
  69194. meshPosition = this.customMeshPosition;
  69195. }
  69196. else if (this.attachedNode) {
  69197. meshPosition = this.attachedNode.position;
  69198. }
  69199. else {
  69200. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  69201. }
  69202. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  69203. this._screenCoordinates.x = pos.x / this._viewPort.width;
  69204. this._screenCoordinates.y = pos.y / this._viewPort.height;
  69205. if (this.invert)
  69206. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  69207. };
  69208. // Static methods
  69209. /**
  69210. * Creates a default mesh for the Volumeric Light Scattering post-process
  69211. * @param {string} The mesh name
  69212. * @param {BABYLON.Scene} The scene where to create the mesh
  69213. * @return {BABYLON.Mesh} the default mesh
  69214. */
  69215. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  69216. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  69217. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  69218. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  69219. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69220. mesh.material = material;
  69221. return mesh;
  69222. };
  69223. __decorate([
  69224. BABYLON.serializeAsVector3()
  69225. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69226. __decorate([
  69227. BABYLON.serialize()
  69228. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69229. __decorate([
  69230. BABYLON.serialize()
  69231. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69232. __decorate([
  69233. BABYLON.serializeAsMeshReference()
  69234. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69235. __decorate([
  69236. BABYLON.serialize()
  69237. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69238. __decorate([
  69239. BABYLON.serialize()
  69240. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69241. __decorate([
  69242. BABYLON.serialize()
  69243. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69244. __decorate([
  69245. BABYLON.serialize()
  69246. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69247. __decorate([
  69248. BABYLON.serialize()
  69249. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69250. return VolumetricLightScatteringPostProcess;
  69251. }(BABYLON.PostProcess));
  69252. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69253. })(BABYLON || (BABYLON = {}));
  69254. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69255. //
  69256. // This post-process allows the modification of rendered colors by using
  69257. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69258. //
  69259. // The object needs to be provided an url to a texture containing the color
  69260. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69261. // Use an image editing software to tweak the LUT to match your needs.
  69262. //
  69263. // For an example of a color LUT, see here:
  69264. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69265. // For explanations on color grading, see here:
  69266. // http://udn.epicgames.com/Three/ColorGrading.html
  69267. //
  69268. var BABYLON;
  69269. (function (BABYLON) {
  69270. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69271. __extends(ColorCorrectionPostProcess, _super);
  69272. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69273. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69274. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69275. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69276. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69277. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69278. _this.onApply = function (effect) {
  69279. effect.setTexture("colorTable", _this._colorTableTexture);
  69280. };
  69281. return _this;
  69282. }
  69283. return ColorCorrectionPostProcess;
  69284. }(BABYLON.PostProcess));
  69285. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69286. })(BABYLON || (BABYLON = {}));
  69287. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69288. var BABYLON;
  69289. (function (BABYLON) {
  69290. var TonemappingOperator;
  69291. (function (TonemappingOperator) {
  69292. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69293. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69294. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69295. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69296. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69297. ;
  69298. var TonemapPostProcess = /** @class */ (function (_super) {
  69299. __extends(TonemapPostProcess, _super);
  69300. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69302. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69303. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69304. _this._operator = _operator;
  69305. _this.exposureAdjustment = exposureAdjustment;
  69306. var defines = "#define ";
  69307. if (_this._operator === TonemappingOperator.Hable)
  69308. defines += "HABLE_TONEMAPPING";
  69309. else if (_this._operator === TonemappingOperator.Reinhard)
  69310. defines += "REINHARD_TONEMAPPING";
  69311. else if (_this._operator === TonemappingOperator.HejiDawson)
  69312. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69313. else if (_this._operator === TonemappingOperator.Photographic)
  69314. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69315. //sadly a second call to create the effect.
  69316. _this.updateEffect(defines);
  69317. _this.onApply = function (effect) {
  69318. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69319. };
  69320. return _this;
  69321. }
  69322. return TonemapPostProcess;
  69323. }(BABYLON.PostProcess));
  69324. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69325. })(BABYLON || (BABYLON = {}));
  69326. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69327. var BABYLON;
  69328. (function (BABYLON) {
  69329. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69330. __extends(DisplayPassPostProcess, _super);
  69331. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69332. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69333. }
  69334. return DisplayPassPostProcess;
  69335. }(BABYLON.PostProcess));
  69336. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69337. })(BABYLON || (BABYLON = {}));
  69338. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69339. var BABYLON;
  69340. (function (BABYLON) {
  69341. var HighlightsPostProcess = /** @class */ (function (_super) {
  69342. __extends(HighlightsPostProcess, _super);
  69343. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69344. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69345. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69346. }
  69347. return HighlightsPostProcess;
  69348. }(BABYLON.PostProcess));
  69349. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69350. })(BABYLON || (BABYLON = {}));
  69351. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69352. var BABYLON;
  69353. (function (BABYLON) {
  69354. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69355. __extends(ImageProcessingPostProcess, _super);
  69356. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69357. if (camera === void 0) { camera = null; }
  69358. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69359. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69360. _this._fromLinearSpace = true;
  69361. /**
  69362. * Defines cache preventing GC.
  69363. */
  69364. _this._defines = {
  69365. IMAGEPROCESSING: false,
  69366. VIGNETTE: false,
  69367. VIGNETTEBLENDMODEMULTIPLY: false,
  69368. VIGNETTEBLENDMODEOPAQUE: false,
  69369. TONEMAPPING: false,
  69370. CONTRAST: false,
  69371. COLORCURVES: false,
  69372. COLORGRADING: false,
  69373. COLORGRADING3D: false,
  69374. FROMLINEARSPACE: false,
  69375. SAMPLER3DGREENDEPTH: false,
  69376. SAMPLER3DBGRMAP: false,
  69377. IMAGEPROCESSINGPOSTPROCESS: false,
  69378. EXPOSURE: false,
  69379. GRAIN: false,
  69380. };
  69381. // Setup the configuration as forced by the constructor. This would then not force the
  69382. // scene materials output in linear space and let untouched the default forward pass.
  69383. if (imageProcessingConfiguration) {
  69384. imageProcessingConfiguration.applyByPostProcess = true;
  69385. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69386. // This will cause the shader to be compiled
  69387. _this.fromLinearSpace = false;
  69388. }
  69389. else {
  69390. _this._attachImageProcessingConfiguration(null, true);
  69391. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69392. }
  69393. _this.onApply = function (effect) {
  69394. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69395. };
  69396. return _this;
  69397. }
  69398. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69399. /**
  69400. * Gets the image processing configuration used either in this material.
  69401. */
  69402. get: function () {
  69403. return this._imageProcessingConfiguration;
  69404. },
  69405. /**
  69406. * Sets the Default image processing configuration used either in the this material.
  69407. *
  69408. * If sets to null, the scene one is in use.
  69409. */
  69410. set: function (value) {
  69411. this._attachImageProcessingConfiguration(value);
  69412. },
  69413. enumerable: true,
  69414. configurable: true
  69415. });
  69416. /**
  69417. * Attaches a new image processing configuration to the PBR Material.
  69418. * @param configuration
  69419. */
  69420. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69421. var _this = this;
  69422. if (doNotBuild === void 0) { doNotBuild = false; }
  69423. if (configuration === this._imageProcessingConfiguration) {
  69424. return;
  69425. }
  69426. // Detaches observer.
  69427. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69428. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69429. }
  69430. // Pick the scene configuration if needed.
  69431. if (!configuration) {
  69432. var scene = null;
  69433. var engine = this.getEngine();
  69434. var camera = this.getCamera();
  69435. if (camera) {
  69436. scene = camera.getScene();
  69437. }
  69438. else if (engine && engine.scenes) {
  69439. var scenes = engine.scenes;
  69440. scene = scenes[scenes.length - 1];
  69441. }
  69442. else {
  69443. scene = BABYLON.Engine.LastCreatedScene;
  69444. }
  69445. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69446. }
  69447. else {
  69448. this._imageProcessingConfiguration = configuration;
  69449. }
  69450. // Attaches observer.
  69451. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69452. _this._updateParameters();
  69453. });
  69454. // Ensure the effect will be rebuilt.
  69455. if (!doNotBuild) {
  69456. this._updateParameters();
  69457. }
  69458. };
  69459. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69460. /**
  69461. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69462. */
  69463. get: function () {
  69464. return this.imageProcessingConfiguration.colorCurves;
  69465. },
  69466. /**
  69467. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69468. */
  69469. set: function (value) {
  69470. this.imageProcessingConfiguration.colorCurves = value;
  69471. },
  69472. enumerable: true,
  69473. configurable: true
  69474. });
  69475. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69476. /**
  69477. * Gets wether the color curves effect is enabled.
  69478. */
  69479. get: function () {
  69480. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69481. },
  69482. /**
  69483. * Sets wether the color curves effect is enabled.
  69484. */
  69485. set: function (value) {
  69486. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69487. },
  69488. enumerable: true,
  69489. configurable: true
  69490. });
  69491. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69492. /**
  69493. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69494. */
  69495. get: function () {
  69496. return this.imageProcessingConfiguration.colorGradingTexture;
  69497. },
  69498. /**
  69499. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69500. */
  69501. set: function (value) {
  69502. this.imageProcessingConfiguration.colorGradingTexture = value;
  69503. },
  69504. enumerable: true,
  69505. configurable: true
  69506. });
  69507. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69508. /**
  69509. * Gets wether the color grading effect is enabled.
  69510. */
  69511. get: function () {
  69512. return this.imageProcessingConfiguration.colorGradingEnabled;
  69513. },
  69514. /**
  69515. * Gets wether the color grading effect is enabled.
  69516. */
  69517. set: function (value) {
  69518. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69519. },
  69520. enumerable: true,
  69521. configurable: true
  69522. });
  69523. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69524. /**
  69525. * Gets exposure used in the effect.
  69526. */
  69527. get: function () {
  69528. return this.imageProcessingConfiguration.exposure;
  69529. },
  69530. /**
  69531. * Sets exposure used in the effect.
  69532. */
  69533. set: function (value) {
  69534. this.imageProcessingConfiguration.exposure = value;
  69535. },
  69536. enumerable: true,
  69537. configurable: true
  69538. });
  69539. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69540. /**
  69541. * Gets wether tonemapping is enabled or not.
  69542. */
  69543. get: function () {
  69544. return this._imageProcessingConfiguration.toneMappingEnabled;
  69545. },
  69546. /**
  69547. * Sets wether tonemapping is enabled or not
  69548. */
  69549. set: function (value) {
  69550. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69551. },
  69552. enumerable: true,
  69553. configurable: true
  69554. });
  69555. ;
  69556. ;
  69557. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69558. /**
  69559. * Gets contrast used in the effect.
  69560. */
  69561. get: function () {
  69562. return this.imageProcessingConfiguration.contrast;
  69563. },
  69564. /**
  69565. * Sets contrast used in the effect.
  69566. */
  69567. set: function (value) {
  69568. this.imageProcessingConfiguration.contrast = value;
  69569. },
  69570. enumerable: true,
  69571. configurable: true
  69572. });
  69573. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69574. /**
  69575. * Gets Vignette stretch size.
  69576. */
  69577. get: function () {
  69578. return this.imageProcessingConfiguration.vignetteStretch;
  69579. },
  69580. /**
  69581. * Sets Vignette stretch size.
  69582. */
  69583. set: function (value) {
  69584. this.imageProcessingConfiguration.vignetteStretch = value;
  69585. },
  69586. enumerable: true,
  69587. configurable: true
  69588. });
  69589. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69590. /**
  69591. * Gets Vignette centre X Offset.
  69592. */
  69593. get: function () {
  69594. return this.imageProcessingConfiguration.vignetteCentreX;
  69595. },
  69596. /**
  69597. * Sets Vignette centre X Offset.
  69598. */
  69599. set: function (value) {
  69600. this.imageProcessingConfiguration.vignetteCentreX = value;
  69601. },
  69602. enumerable: true,
  69603. configurable: true
  69604. });
  69605. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69606. /**
  69607. * Gets Vignette centre Y Offset.
  69608. */
  69609. get: function () {
  69610. return this.imageProcessingConfiguration.vignetteCentreY;
  69611. },
  69612. /**
  69613. * Sets Vignette centre Y Offset.
  69614. */
  69615. set: function (value) {
  69616. this.imageProcessingConfiguration.vignetteCentreY = value;
  69617. },
  69618. enumerable: true,
  69619. configurable: true
  69620. });
  69621. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69622. /**
  69623. * Gets Vignette weight or intensity of the vignette effect.
  69624. */
  69625. get: function () {
  69626. return this.imageProcessingConfiguration.vignetteWeight;
  69627. },
  69628. /**
  69629. * Sets Vignette weight or intensity of the vignette effect.
  69630. */
  69631. set: function (value) {
  69632. this.imageProcessingConfiguration.vignetteWeight = value;
  69633. },
  69634. enumerable: true,
  69635. configurable: true
  69636. });
  69637. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69638. /**
  69639. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69640. * if vignetteEnabled is set to true.
  69641. */
  69642. get: function () {
  69643. return this.imageProcessingConfiguration.vignetteColor;
  69644. },
  69645. /**
  69646. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69647. * if vignetteEnabled is set to true.
  69648. */
  69649. set: function (value) {
  69650. this.imageProcessingConfiguration.vignetteColor = value;
  69651. },
  69652. enumerable: true,
  69653. configurable: true
  69654. });
  69655. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69656. /**
  69657. * Gets Camera field of view used by the Vignette effect.
  69658. */
  69659. get: function () {
  69660. return this.imageProcessingConfiguration.vignetteCameraFov;
  69661. },
  69662. /**
  69663. * Sets Camera field of view used by the Vignette effect.
  69664. */
  69665. set: function (value) {
  69666. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69667. },
  69668. enumerable: true,
  69669. configurable: true
  69670. });
  69671. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69672. /**
  69673. * Gets the vignette blend mode allowing different kind of effect.
  69674. */
  69675. get: function () {
  69676. return this.imageProcessingConfiguration.vignetteBlendMode;
  69677. },
  69678. /**
  69679. * Sets the vignette blend mode allowing different kind of effect.
  69680. */
  69681. set: function (value) {
  69682. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69683. },
  69684. enumerable: true,
  69685. configurable: true
  69686. });
  69687. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69688. /**
  69689. * Gets wether the vignette effect is enabled.
  69690. */
  69691. get: function () {
  69692. return this.imageProcessingConfiguration.vignetteEnabled;
  69693. },
  69694. /**
  69695. * Sets wether the vignette effect is enabled.
  69696. */
  69697. set: function (value) {
  69698. this.imageProcessingConfiguration.vignetteEnabled = value;
  69699. },
  69700. enumerable: true,
  69701. configurable: true
  69702. });
  69703. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69704. /**
  69705. * Gets wether the input of the processing is in Gamma or Linear Space.
  69706. */
  69707. get: function () {
  69708. return this._fromLinearSpace;
  69709. },
  69710. /**
  69711. * Sets wether the input of the processing is in Gamma or Linear Space.
  69712. */
  69713. set: function (value) {
  69714. if (this._fromLinearSpace === value) {
  69715. return;
  69716. }
  69717. this._fromLinearSpace = value;
  69718. this._updateParameters();
  69719. },
  69720. enumerable: true,
  69721. configurable: true
  69722. });
  69723. ImageProcessingPostProcess.prototype.getClassName = function () {
  69724. return "ImageProcessingPostProcess";
  69725. };
  69726. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69727. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69728. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69729. var defines = "";
  69730. for (var define in this._defines) {
  69731. if (this._defines[define]) {
  69732. defines += "#define " + define + ";\r\n";
  69733. }
  69734. }
  69735. var samplers = ["textureSampler"];
  69736. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69737. var uniforms = ["scale"];
  69738. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69739. this.updateEffect(defines, uniforms, samplers);
  69740. };
  69741. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69742. _super.prototype.dispose.call(this, camera);
  69743. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69744. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69745. }
  69746. this.imageProcessingConfiguration.applyByPostProcess = false;
  69747. };
  69748. __decorate([
  69749. BABYLON.serialize()
  69750. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69751. return ImageProcessingPostProcess;
  69752. }(BABYLON.PostProcess));
  69753. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69754. })(BABYLON || (BABYLON = {}));
  69755. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69756. var BABYLON;
  69757. (function (BABYLON) {
  69758. /**
  69759. * The Blur Post Process which blurs an image based on a kernel and direction.
  69760. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69761. */
  69762. var BlurPostProcess = /** @class */ (function (_super) {
  69763. __extends(BlurPostProcess, _super);
  69764. /**
  69765. * Creates a new instance of @see BlurPostProcess
  69766. * @param name The name of the effect.
  69767. * @param direction The direction in which to blur the image.
  69768. * @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.
  69769. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69770. * @param camera The camera to apply the render pass to.
  69771. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69772. * @param engine The engine which the post process will be applied. (default: current engine)
  69773. * @param reusable If the post process can be reused on the same frame. (default: false)
  69774. * @param textureType Type of textures used when performing the post process. (default: 0)
  69775. */
  69776. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69777. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69778. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69779. if (defines === void 0) { defines = ""; }
  69780. 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;
  69781. _this.direction = direction;
  69782. _this._packedFloat = false;
  69783. _this._staticDefines = "";
  69784. _this._staticDefines = defines;
  69785. _this.onApplyObservable.add(function (effect) {
  69786. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69787. });
  69788. _this.kernel = kernel;
  69789. return _this;
  69790. }
  69791. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69792. /**
  69793. * Gets the length in pixels of the blur sample region
  69794. */
  69795. get: function () {
  69796. return this._idealKernel;
  69797. },
  69798. /**
  69799. * Sets the length in pixels of the blur sample region
  69800. */
  69801. set: function (v) {
  69802. if (this._idealKernel === v) {
  69803. return;
  69804. }
  69805. v = Math.max(v, 1);
  69806. this._idealKernel = v;
  69807. this._kernel = this._nearestBestKernel(v);
  69808. this._updateParameters();
  69809. },
  69810. enumerable: true,
  69811. configurable: true
  69812. });
  69813. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69814. /**
  69815. * Gets wether or not the blur is unpacking/repacking floats
  69816. */
  69817. get: function () {
  69818. return this._packedFloat;
  69819. },
  69820. /**
  69821. * Sets wether or not the blur needs to unpack/repack floats
  69822. */
  69823. set: function (v) {
  69824. if (this._packedFloat === v) {
  69825. return;
  69826. }
  69827. this._packedFloat = v;
  69828. this._updateParameters();
  69829. },
  69830. enumerable: true,
  69831. configurable: true
  69832. });
  69833. BlurPostProcess.prototype._updateParameters = function () {
  69834. // Generate sampling offsets and weights
  69835. var N = this._kernel;
  69836. var centerIndex = (N - 1) / 2;
  69837. // Generate Gaussian sampling weights over kernel
  69838. var offsets = [];
  69839. var weights = [];
  69840. var totalWeight = 0;
  69841. for (var i = 0; i < N; i++) {
  69842. var u = i / (N - 1);
  69843. var w = this._gaussianWeight(u * 2.0 - 1);
  69844. offsets[i] = (i - centerIndex);
  69845. weights[i] = w;
  69846. totalWeight += w;
  69847. }
  69848. // Normalize weights
  69849. for (var i = 0; i < weights.length; i++) {
  69850. weights[i] /= totalWeight;
  69851. }
  69852. // Optimize: combine samples to take advantage of hardware linear sampling
  69853. // Walk from left to center, combining pairs (symmetrically)
  69854. var linearSamplingWeights = [];
  69855. var linearSamplingOffsets = [];
  69856. var linearSamplingMap = [];
  69857. for (var i = 0; i <= centerIndex; i += 2) {
  69858. var j = Math.min(i + 1, Math.floor(centerIndex));
  69859. var singleCenterSample = i === j;
  69860. if (singleCenterSample) {
  69861. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69862. }
  69863. else {
  69864. var sharedCell = j === centerIndex;
  69865. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69866. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69867. if (offsetLinear === 0) {
  69868. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69869. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69870. }
  69871. else {
  69872. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69873. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69874. }
  69875. }
  69876. }
  69877. for (var i = 0; i < linearSamplingMap.length; i++) {
  69878. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69879. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69880. }
  69881. // Replace with optimized
  69882. offsets = linearSamplingOffsets;
  69883. weights = linearSamplingWeights;
  69884. // Generate shaders
  69885. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69886. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69887. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69888. var defines = "";
  69889. defines += this._staticDefines;
  69890. for (var i = 0; i < varyingCount; i++) {
  69891. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69892. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69893. }
  69894. var depCount = 0;
  69895. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69896. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69897. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69898. depCount++;
  69899. }
  69900. if (this.packedFloat) {
  69901. defines += "#define PACKEDFLOAT 1";
  69902. }
  69903. this.updateEffect(defines, null, null, {
  69904. varyingCount: varyingCount,
  69905. depCount: depCount
  69906. });
  69907. };
  69908. /**
  69909. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69910. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69911. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69912. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69913. * The gaps between physical kernels are compensated for in the weighting of the samples
  69914. * @param idealKernel Ideal blur kernel.
  69915. * @return Nearest best kernel.
  69916. */
  69917. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69918. var v = Math.round(idealKernel);
  69919. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69920. var k = _a[_i];
  69921. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69922. return Math.max(k, 3);
  69923. }
  69924. }
  69925. return Math.max(v, 3);
  69926. };
  69927. /**
  69928. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69929. * @param x The point on the Gaussian distribution to sample.
  69930. * @return the value of the Gaussian function at x.
  69931. */
  69932. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69933. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69934. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69935. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69936. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69937. // truncated at around 1.3% of peak strength.
  69938. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69939. var sigma = (1 / 3);
  69940. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69941. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69942. var weight = (1.0 / denominator) * Math.exp(exponent);
  69943. return weight;
  69944. };
  69945. /**
  69946. * Generates a string that can be used as a floating point number in GLSL.
  69947. * @param x Value to print.
  69948. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69949. * @return GLSL float string.
  69950. */
  69951. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69952. if (decimalFigures === void 0) { decimalFigures = 8; }
  69953. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69954. };
  69955. return BlurPostProcess;
  69956. }(BABYLON.PostProcess));
  69957. BABYLON.BlurPostProcess = BlurPostProcess;
  69958. })(BABYLON || (BABYLON = {}));
  69959. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69960. var BABYLON;
  69961. (function (BABYLON) {
  69962. var Bone = /** @class */ (function (_super) {
  69963. __extends(Bone, _super);
  69964. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69965. if (parentBone === void 0) { parentBone = null; }
  69966. if (localMatrix === void 0) { localMatrix = null; }
  69967. if (restPose === void 0) { restPose = null; }
  69968. if (baseMatrix === void 0) { baseMatrix = null; }
  69969. if (index === void 0) { index = null; }
  69970. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69971. _this.name = name;
  69972. _this.children = new Array();
  69973. _this.animations = new Array();
  69974. // Set this value to map this bone to a different index in the transform matrices.
  69975. // Set this value to -1 to exclude the bone from the transform matrices.
  69976. _this._index = null;
  69977. _this._worldTransform = new BABYLON.Matrix();
  69978. _this._absoluteTransform = new BABYLON.Matrix();
  69979. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69980. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69981. _this._scaleVector = BABYLON.Vector3.One();
  69982. _this._negateScaleChildren = BABYLON.Vector3.One();
  69983. _this._scalingDeterminant = 1;
  69984. _this._skeleton = skeleton;
  69985. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69986. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69987. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69988. _this._index = index;
  69989. skeleton.bones.push(_this);
  69990. _this.setParent(parentBone, false);
  69991. _this._updateDifferenceMatrix();
  69992. return _this;
  69993. }
  69994. Object.defineProperty(Bone.prototype, "_matrix", {
  69995. get: function () {
  69996. return this._localMatrix;
  69997. },
  69998. set: function (val) {
  69999. if (this._localMatrix) {
  70000. this._localMatrix.copyFrom(val);
  70001. }
  70002. else {
  70003. this._localMatrix = val;
  70004. }
  70005. },
  70006. enumerable: true,
  70007. configurable: true
  70008. });
  70009. // Members
  70010. Bone.prototype.getSkeleton = function () {
  70011. return this._skeleton;
  70012. };
  70013. Bone.prototype.getParent = function () {
  70014. return this._parent;
  70015. };
  70016. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  70017. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70018. if (this._parent === parent) {
  70019. return;
  70020. }
  70021. if (this._parent) {
  70022. var index = this._parent.children.indexOf(this);
  70023. if (index !== -1) {
  70024. this._parent.children.splice(index, 1);
  70025. }
  70026. }
  70027. this._parent = parent;
  70028. if (this._parent) {
  70029. this._parent.children.push(this);
  70030. }
  70031. if (updateDifferenceMatrix) {
  70032. this._updateDifferenceMatrix();
  70033. }
  70034. };
  70035. Bone.prototype.getLocalMatrix = function () {
  70036. return this._localMatrix;
  70037. };
  70038. Bone.prototype.getBaseMatrix = function () {
  70039. return this._baseMatrix;
  70040. };
  70041. Bone.prototype.getRestPose = function () {
  70042. return this._restPose;
  70043. };
  70044. Bone.prototype.returnToRest = function () {
  70045. this.updateMatrix(this._restPose.clone());
  70046. };
  70047. Bone.prototype.getWorldMatrix = function () {
  70048. return this._worldTransform;
  70049. };
  70050. Bone.prototype.getInvertedAbsoluteTransform = function () {
  70051. return this._invertedAbsoluteTransform;
  70052. };
  70053. Bone.prototype.getAbsoluteTransform = function () {
  70054. return this._absoluteTransform;
  70055. };
  70056. Object.defineProperty(Bone.prototype, "position", {
  70057. // Properties (matches AbstractMesh properties)
  70058. get: function () {
  70059. return this.getPosition();
  70060. },
  70061. set: function (newPosition) {
  70062. this.setPosition(newPosition);
  70063. },
  70064. enumerable: true,
  70065. configurable: true
  70066. });
  70067. Object.defineProperty(Bone.prototype, "rotation", {
  70068. get: function () {
  70069. return this.getRotation();
  70070. },
  70071. set: function (newRotation) {
  70072. this.setRotation(newRotation);
  70073. },
  70074. enumerable: true,
  70075. configurable: true
  70076. });
  70077. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  70078. get: function () {
  70079. return this.getRotationQuaternion();
  70080. },
  70081. set: function (newRotation) {
  70082. this.setRotationQuaternion(newRotation);
  70083. },
  70084. enumerable: true,
  70085. configurable: true
  70086. });
  70087. Object.defineProperty(Bone.prototype, "scaling", {
  70088. get: function () {
  70089. return this.getScale();
  70090. },
  70091. set: function (newScaling) {
  70092. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  70093. },
  70094. enumerable: true,
  70095. configurable: true
  70096. });
  70097. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  70098. /**
  70099. * Gets the animation properties override
  70100. */
  70101. get: function () {
  70102. return this._skeleton.animationPropertiesOverride;
  70103. },
  70104. enumerable: true,
  70105. configurable: true
  70106. });
  70107. // Methods
  70108. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  70109. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  70110. this._baseMatrix = matrix.clone();
  70111. this._localMatrix = matrix.clone();
  70112. this._skeleton._markAsDirty();
  70113. if (updateDifferenceMatrix) {
  70114. this._updateDifferenceMatrix();
  70115. }
  70116. };
  70117. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  70118. if (!rootMatrix) {
  70119. rootMatrix = this._baseMatrix;
  70120. }
  70121. if (this._parent) {
  70122. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70123. }
  70124. else {
  70125. this._absoluteTransform.copyFrom(rootMatrix);
  70126. }
  70127. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  70128. for (var index = 0; index < this.children.length; index++) {
  70129. this.children[index]._updateDifferenceMatrix();
  70130. }
  70131. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  70132. };
  70133. Bone.prototype.markAsDirty = function () {
  70134. this._currentRenderId++;
  70135. this._skeleton._markAsDirty();
  70136. };
  70137. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  70138. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70139. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  70140. // all animation may be coming from a library skeleton, so may need to create animation
  70141. if (this.animations.length === 0) {
  70142. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  70143. this.animations[0].setKeys([]);
  70144. }
  70145. // get animation info / verify there is such a range from the source bone
  70146. var sourceRange = source.animations[0].getRange(rangeName);
  70147. if (!sourceRange) {
  70148. return false;
  70149. }
  70150. var from = sourceRange.from;
  70151. var to = sourceRange.to;
  70152. var sourceKeys = source.animations[0].getKeys();
  70153. // rescaling prep
  70154. var sourceBoneLength = source.length;
  70155. var sourceParent = source.getParent();
  70156. var parent = this.getParent();
  70157. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  70158. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  70159. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  70160. var destKeys = this.animations[0].getKeys();
  70161. // loop vars declaration
  70162. var orig;
  70163. var origTranslation;
  70164. var mat;
  70165. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  70166. orig = sourceKeys[key];
  70167. if (orig.frame >= from && orig.frame <= to) {
  70168. if (rescaleAsRequired) {
  70169. mat = orig.value.clone();
  70170. // scale based on parent ratio, when bone has parent
  70171. if (parentScalingReqd) {
  70172. origTranslation = mat.getTranslation();
  70173. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  70174. // scale based on skeleton dimension ratio when root bone, and value is passed
  70175. }
  70176. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  70177. origTranslation = mat.getTranslation();
  70178. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  70179. // use original when root bone, and no data for skelDimensionsRatio
  70180. }
  70181. else {
  70182. mat = orig.value;
  70183. }
  70184. }
  70185. else {
  70186. mat = orig.value;
  70187. }
  70188. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  70189. }
  70190. }
  70191. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  70192. return true;
  70193. };
  70194. /**
  70195. * Translate the bone in local or world space.
  70196. * @param vec The amount to translate the bone.
  70197. * @param space The space that the translation is in.
  70198. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70199. */
  70200. Bone.prototype.translate = function (vec, space, mesh) {
  70201. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70202. var lm = this.getLocalMatrix();
  70203. if (space == BABYLON.Space.LOCAL) {
  70204. lm.m[12] += vec.x;
  70205. lm.m[13] += vec.y;
  70206. lm.m[14] += vec.z;
  70207. }
  70208. else {
  70209. var wm = null;
  70210. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70211. if (mesh) {
  70212. wm = mesh.getWorldMatrix();
  70213. }
  70214. this._skeleton.computeAbsoluteTransforms();
  70215. var tmat = Bone._tmpMats[0];
  70216. var tvec = Bone._tmpVecs[0];
  70217. if (this._parent) {
  70218. if (mesh && wm) {
  70219. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70220. tmat.multiplyToRef(wm, tmat);
  70221. }
  70222. else {
  70223. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70224. }
  70225. }
  70226. tmat.m[12] = 0;
  70227. tmat.m[13] = 0;
  70228. tmat.m[14] = 0;
  70229. tmat.invert();
  70230. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70231. lm.m[12] += tvec.x;
  70232. lm.m[13] += tvec.y;
  70233. lm.m[14] += tvec.z;
  70234. }
  70235. this.markAsDirty();
  70236. };
  70237. /**
  70238. * Set the postion of the bone in local or world space.
  70239. * @param position The position to set the bone.
  70240. * @param space The space that the position is in.
  70241. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70242. */
  70243. Bone.prototype.setPosition = function (position, space, mesh) {
  70244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70245. var lm = this.getLocalMatrix();
  70246. if (space == BABYLON.Space.LOCAL) {
  70247. lm.m[12] = position.x;
  70248. lm.m[13] = position.y;
  70249. lm.m[14] = position.z;
  70250. }
  70251. else {
  70252. var wm = null;
  70253. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70254. if (mesh) {
  70255. wm = mesh.getWorldMatrix();
  70256. }
  70257. this._skeleton.computeAbsoluteTransforms();
  70258. var tmat = Bone._tmpMats[0];
  70259. var vec = Bone._tmpVecs[0];
  70260. if (this._parent) {
  70261. if (mesh && wm) {
  70262. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70263. tmat.multiplyToRef(wm, tmat);
  70264. }
  70265. else {
  70266. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70267. }
  70268. }
  70269. tmat.invert();
  70270. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70271. lm.m[12] = vec.x;
  70272. lm.m[13] = vec.y;
  70273. lm.m[14] = vec.z;
  70274. }
  70275. this.markAsDirty();
  70276. };
  70277. /**
  70278. * Set the absolute postion of the bone (world space).
  70279. * @param position The position to set the bone.
  70280. * @param mesh The mesh that this bone is attached to.
  70281. */
  70282. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70283. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70284. };
  70285. /**
  70286. * Set the scale of the bone on the x, y and z axes.
  70287. * @param x The scale of the bone on the x axis.
  70288. * @param x The scale of the bone on the y axis.
  70289. * @param z The scale of the bone on the z axis.
  70290. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70291. */
  70292. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70293. if (scaleChildren === void 0) { scaleChildren = false; }
  70294. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70295. if (!scaleChildren) {
  70296. this._negateScaleChildren.x = 1 / x;
  70297. this._negateScaleChildren.y = 1 / y;
  70298. this._negateScaleChildren.z = 1 / z;
  70299. }
  70300. this._syncScaleVector();
  70301. }
  70302. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70303. };
  70304. /**
  70305. * Scale the bone on the x, y and z axes.
  70306. * @param x The amount to scale the bone on the x axis.
  70307. * @param x The amount to scale the bone on the y axis.
  70308. * @param z The amount to scale the bone on the z axis.
  70309. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70310. */
  70311. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70312. if (scaleChildren === void 0) { scaleChildren = false; }
  70313. var locMat = this.getLocalMatrix();
  70314. var origLocMat = Bone._tmpMats[0];
  70315. origLocMat.copyFrom(locMat);
  70316. var origLocMatInv = Bone._tmpMats[1];
  70317. origLocMatInv.copyFrom(origLocMat);
  70318. origLocMatInv.invert();
  70319. var scaleMat = Bone._tmpMats[2];
  70320. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70321. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70322. this._scaleVector.x *= x;
  70323. this._scaleVector.y *= y;
  70324. this._scaleVector.z *= z;
  70325. locMat.multiplyToRef(origLocMatInv, locMat);
  70326. locMat.multiplyToRef(scaleMat, locMat);
  70327. locMat.multiplyToRef(origLocMat, locMat);
  70328. var parent = this.getParent();
  70329. if (parent) {
  70330. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70331. }
  70332. else {
  70333. this.getAbsoluteTransform().copyFrom(locMat);
  70334. }
  70335. var len = this.children.length;
  70336. scaleMat.invert();
  70337. for (var i = 0; i < len; i++) {
  70338. var child = this.children[i];
  70339. var cm = child.getLocalMatrix();
  70340. cm.multiplyToRef(scaleMat, cm);
  70341. var lm = child.getLocalMatrix();
  70342. lm.m[12] *= x;
  70343. lm.m[13] *= y;
  70344. lm.m[14] *= z;
  70345. }
  70346. this.computeAbsoluteTransforms();
  70347. if (scaleChildren) {
  70348. for (var i = 0; i < len; i++) {
  70349. this.children[i].scale(x, y, z, scaleChildren);
  70350. }
  70351. }
  70352. this.markAsDirty();
  70353. };
  70354. /**
  70355. * Set the yaw, pitch, and roll of the bone in local or world space.
  70356. * @param yaw The rotation of the bone on the y axis.
  70357. * @param pitch The rotation of the bone on the x axis.
  70358. * @param roll The rotation of the bone on the z axis.
  70359. * @param space The space that the axes of rotation are in.
  70360. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70361. */
  70362. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70363. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70364. var rotMat = Bone._tmpMats[0];
  70365. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70366. var rotMatInv = Bone._tmpMats[1];
  70367. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70368. rotMatInv.multiplyToRef(rotMat, rotMat);
  70369. this._rotateWithMatrix(rotMat, space, mesh);
  70370. };
  70371. /**
  70372. * Rotate the bone on an axis in local or world space.
  70373. * @param axis The axis to rotate the bone on.
  70374. * @param amount The amount to rotate the bone.
  70375. * @param space The space that the axis is in.
  70376. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70377. */
  70378. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70380. var rmat = Bone._tmpMats[0];
  70381. rmat.m[12] = 0;
  70382. rmat.m[13] = 0;
  70383. rmat.m[14] = 0;
  70384. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70385. this._rotateWithMatrix(rmat, space, mesh);
  70386. };
  70387. /**
  70388. * Set the rotation of the bone to a particular axis angle in local or world space.
  70389. * @param axis The axis to rotate the bone on.
  70390. * @param angle The angle that the bone should be rotated to.
  70391. * @param space The space that the axis is in.
  70392. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70393. */
  70394. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70395. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70396. var rotMat = Bone._tmpMats[0];
  70397. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70398. var rotMatInv = Bone._tmpMats[1];
  70399. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70400. rotMatInv.multiplyToRef(rotMat, rotMat);
  70401. this._rotateWithMatrix(rotMat, space, mesh);
  70402. };
  70403. /**
  70404. * Set the euler rotation of the bone in local of world space.
  70405. * @param rotation The euler rotation that the bone should be set to.
  70406. * @param space The space that the rotation is in.
  70407. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70408. */
  70409. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70411. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70412. };
  70413. /**
  70414. * Set the quaternion rotation of the bone in local of world space.
  70415. * @param quat The quaternion rotation that the bone should be set to.
  70416. * @param space The space that the rotation is in.
  70417. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70418. */
  70419. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70420. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70421. var rotMatInv = Bone._tmpMats[0];
  70422. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70423. var rotMat = Bone._tmpMats[1];
  70424. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70425. rotMatInv.multiplyToRef(rotMat, rotMat);
  70426. this._rotateWithMatrix(rotMat, space, mesh);
  70427. };
  70428. /**
  70429. * Set the rotation matrix of the bone in local of world space.
  70430. * @param rotMat The rotation matrix that the bone should be set to.
  70431. * @param space The space that the rotation is in.
  70432. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70433. */
  70434. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70436. var rotMatInv = Bone._tmpMats[0];
  70437. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70438. var rotMat2 = Bone._tmpMats[1];
  70439. rotMat2.copyFrom(rotMat);
  70440. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70441. this._rotateWithMatrix(rotMat2, space, mesh);
  70442. };
  70443. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70445. var lmat = this.getLocalMatrix();
  70446. var lx = lmat.m[12];
  70447. var ly = lmat.m[13];
  70448. var lz = lmat.m[14];
  70449. var parent = this.getParent();
  70450. var parentScale = Bone._tmpMats[3];
  70451. var parentScaleInv = Bone._tmpMats[4];
  70452. if (parent) {
  70453. if (space == BABYLON.Space.WORLD) {
  70454. if (mesh) {
  70455. parentScale.copyFrom(mesh.getWorldMatrix());
  70456. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70457. }
  70458. else {
  70459. parentScale.copyFrom(parent.getAbsoluteTransform());
  70460. }
  70461. }
  70462. else {
  70463. parentScale = parent._scaleMatrix;
  70464. }
  70465. parentScaleInv.copyFrom(parentScale);
  70466. parentScaleInv.invert();
  70467. lmat.multiplyToRef(parentScale, lmat);
  70468. lmat.multiplyToRef(rmat, lmat);
  70469. lmat.multiplyToRef(parentScaleInv, lmat);
  70470. }
  70471. else {
  70472. if (space == BABYLON.Space.WORLD && mesh) {
  70473. parentScale.copyFrom(mesh.getWorldMatrix());
  70474. parentScaleInv.copyFrom(parentScale);
  70475. parentScaleInv.invert();
  70476. lmat.multiplyToRef(parentScale, lmat);
  70477. lmat.multiplyToRef(rmat, lmat);
  70478. lmat.multiplyToRef(parentScaleInv, lmat);
  70479. }
  70480. else {
  70481. lmat.multiplyToRef(rmat, lmat);
  70482. }
  70483. }
  70484. lmat.m[12] = lx;
  70485. lmat.m[13] = ly;
  70486. lmat.m[14] = lz;
  70487. this.computeAbsoluteTransforms();
  70488. this.markAsDirty();
  70489. };
  70490. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70491. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70492. if (space == BABYLON.Space.WORLD) {
  70493. var scaleMatrix = Bone._tmpMats[2];
  70494. scaleMatrix.copyFrom(this._scaleMatrix);
  70495. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70496. if (mesh) {
  70497. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70498. var meshScale = Bone._tmpMats[3];
  70499. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70500. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70501. }
  70502. rotMatInv.invert();
  70503. scaleMatrix.m[0] *= this._scalingDeterminant;
  70504. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70505. }
  70506. else {
  70507. rotMatInv.copyFrom(this.getLocalMatrix());
  70508. rotMatInv.invert();
  70509. var scaleMatrix = Bone._tmpMats[2];
  70510. scaleMatrix.copyFrom(this._scaleMatrix);
  70511. if (this._parent) {
  70512. var pscaleMatrix = Bone._tmpMats[3];
  70513. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70514. pscaleMatrix.invert();
  70515. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70516. }
  70517. else {
  70518. scaleMatrix.m[0] *= this._scalingDeterminant;
  70519. }
  70520. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70521. }
  70522. };
  70523. /**
  70524. * Get the scale of the bone
  70525. * @returns the scale of the bone
  70526. */
  70527. Bone.prototype.getScale = function () {
  70528. return this._scaleVector.clone();
  70529. };
  70530. /**
  70531. * Copy the scale of the bone to a vector3.
  70532. * @param result The vector3 to copy the scale to
  70533. */
  70534. Bone.prototype.getScaleToRef = function (result) {
  70535. result.copyFrom(this._scaleVector);
  70536. };
  70537. /**
  70538. * Get the position of the bone in local or world space.
  70539. * @param space The space that the returned position is in.
  70540. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70541. * @returns The position of the bone
  70542. */
  70543. Bone.prototype.getPosition = function (space, mesh) {
  70544. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70545. if (mesh === void 0) { mesh = null; }
  70546. var pos = BABYLON.Vector3.Zero();
  70547. this.getPositionToRef(space, mesh, pos);
  70548. return pos;
  70549. };
  70550. /**
  70551. * Copy the position of the bone to a vector3 in local or world space.
  70552. * @param space The space that the returned position is in.
  70553. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70554. * @param result The vector3 to copy the position to.
  70555. */
  70556. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70557. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70558. if (space == BABYLON.Space.LOCAL) {
  70559. var lm = this.getLocalMatrix();
  70560. result.x = lm.m[12];
  70561. result.y = lm.m[13];
  70562. result.z = lm.m[14];
  70563. }
  70564. else {
  70565. var wm = null;
  70566. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70567. if (mesh) {
  70568. wm = mesh.getWorldMatrix();
  70569. }
  70570. this._skeleton.computeAbsoluteTransforms();
  70571. var tmat = Bone._tmpMats[0];
  70572. if (mesh && wm) {
  70573. tmat.copyFrom(this.getAbsoluteTransform());
  70574. tmat.multiplyToRef(wm, tmat);
  70575. }
  70576. else {
  70577. tmat = this.getAbsoluteTransform();
  70578. }
  70579. result.x = tmat.m[12];
  70580. result.y = tmat.m[13];
  70581. result.z = tmat.m[14];
  70582. }
  70583. };
  70584. /**
  70585. * Get the absolute position of the bone (world space).
  70586. * @param mesh The mesh that this bone is attached to.
  70587. * @returns The absolute position of the bone
  70588. */
  70589. Bone.prototype.getAbsolutePosition = function (mesh) {
  70590. if (mesh === void 0) { mesh = null; }
  70591. var pos = BABYLON.Vector3.Zero();
  70592. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70593. return pos;
  70594. };
  70595. /**
  70596. * Copy the absolute position of the bone (world space) to the result param.
  70597. * @param mesh The mesh that this bone is attached to.
  70598. * @param result The vector3 to copy the absolute position to.
  70599. */
  70600. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70601. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70602. };
  70603. /**
  70604. * Compute the absolute transforms of this bone and its children.
  70605. */
  70606. Bone.prototype.computeAbsoluteTransforms = function () {
  70607. if (this._parent) {
  70608. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70609. }
  70610. else {
  70611. this._absoluteTransform.copyFrom(this._localMatrix);
  70612. var poseMatrix = this._skeleton.getPoseMatrix();
  70613. if (poseMatrix) {
  70614. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70615. }
  70616. }
  70617. var children = this.children;
  70618. var len = children.length;
  70619. for (var i = 0; i < len; i++) {
  70620. children[i].computeAbsoluteTransforms();
  70621. }
  70622. };
  70623. Bone.prototype._syncScaleVector = function () {
  70624. var lm = this.getLocalMatrix();
  70625. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70626. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70627. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70628. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70629. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70630. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70631. this._scaleVector.x = xs * Math.sqrt(xsq);
  70632. this._scaleVector.y = ys * Math.sqrt(ysq);
  70633. this._scaleVector.z = zs * Math.sqrt(zsq);
  70634. if (this._parent) {
  70635. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70636. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70637. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70638. }
  70639. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  70640. };
  70641. /**
  70642. * Get the world direction from an axis that is in the local space of the bone.
  70643. * @param localAxis The local direction that is used to compute the world direction.
  70644. * @param mesh The mesh that this bone is attached to.
  70645. * @returns The world direction
  70646. */
  70647. Bone.prototype.getDirection = function (localAxis, mesh) {
  70648. if (mesh === void 0) { mesh = null; }
  70649. var result = BABYLON.Vector3.Zero();
  70650. this.getDirectionToRef(localAxis, mesh, result);
  70651. return result;
  70652. };
  70653. /**
  70654. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70655. * @param localAxis The local direction that is used to compute the world direction.
  70656. * @param mesh The mesh that this bone is attached to.
  70657. * @param result The vector3 that the world direction will be copied to.
  70658. */
  70659. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70660. if (mesh === void 0) { mesh = null; }
  70661. var wm = null;
  70662. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70663. if (mesh) {
  70664. wm = mesh.getWorldMatrix();
  70665. }
  70666. this._skeleton.computeAbsoluteTransforms();
  70667. var mat = Bone._tmpMats[0];
  70668. mat.copyFrom(this.getAbsoluteTransform());
  70669. if (mesh && wm) {
  70670. mat.multiplyToRef(wm, mat);
  70671. }
  70672. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70673. result.normalize();
  70674. };
  70675. /**
  70676. * Get the euler rotation of the bone in local or world space.
  70677. * @param space The space that the rotation should be in.
  70678. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70679. * @returns The euler rotation
  70680. */
  70681. Bone.prototype.getRotation = function (space, mesh) {
  70682. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70683. if (mesh === void 0) { mesh = null; }
  70684. var result = BABYLON.Vector3.Zero();
  70685. this.getRotationToRef(space, mesh, result);
  70686. return result;
  70687. };
  70688. /**
  70689. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70690. * @param space The space that the rotation should be in.
  70691. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70692. * @param result The vector3 that the rotation should be copied to.
  70693. */
  70694. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70696. if (mesh === void 0) { mesh = null; }
  70697. var quat = Bone._tmpQuat;
  70698. this.getRotationQuaternionToRef(space, mesh, quat);
  70699. quat.toEulerAnglesToRef(result);
  70700. };
  70701. /**
  70702. * Get the quaternion rotation of the bone in either local or world space.
  70703. * @param space The space that the rotation should be in.
  70704. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70705. * @returns The quaternion rotation
  70706. */
  70707. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70709. if (mesh === void 0) { mesh = null; }
  70710. var result = BABYLON.Quaternion.Identity();
  70711. this.getRotationQuaternionToRef(space, mesh, result);
  70712. return result;
  70713. };
  70714. /**
  70715. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70716. * @param space The space that the rotation should be in.
  70717. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70718. * @param result The quaternion that the rotation should be copied to.
  70719. */
  70720. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70722. if (mesh === void 0) { mesh = null; }
  70723. if (space == BABYLON.Space.LOCAL) {
  70724. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70725. }
  70726. else {
  70727. var mat = Bone._tmpMats[0];
  70728. var amat = this.getAbsoluteTransform();
  70729. if (mesh) {
  70730. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70731. }
  70732. else {
  70733. mat.copyFrom(amat);
  70734. }
  70735. mat.m[0] *= this._scalingDeterminant;
  70736. mat.m[1] *= this._scalingDeterminant;
  70737. mat.m[2] *= this._scalingDeterminant;
  70738. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70739. }
  70740. };
  70741. /**
  70742. * Get the rotation matrix of the bone in local or world space.
  70743. * @param space The space that the rotation should be in.
  70744. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70745. * @returns The rotation matrix
  70746. */
  70747. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70748. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70749. var result = BABYLON.Matrix.Identity();
  70750. this.getRotationMatrixToRef(space, mesh, result);
  70751. return result;
  70752. };
  70753. /**
  70754. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70755. * @param space The space that the rotation should be in.
  70756. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70757. * @param result The quaternion that the rotation should be copied to.
  70758. */
  70759. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70761. if (space == BABYLON.Space.LOCAL) {
  70762. this.getLocalMatrix().getRotationMatrixToRef(result);
  70763. }
  70764. else {
  70765. var mat = Bone._tmpMats[0];
  70766. var amat = this.getAbsoluteTransform();
  70767. if (mesh) {
  70768. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70769. }
  70770. else {
  70771. mat.copyFrom(amat);
  70772. }
  70773. mat.m[0] *= this._scalingDeterminant;
  70774. mat.m[1] *= this._scalingDeterminant;
  70775. mat.m[2] *= this._scalingDeterminant;
  70776. mat.getRotationMatrixToRef(result);
  70777. }
  70778. };
  70779. /**
  70780. * Get the world position of a point that is in the local space of the bone.
  70781. * @param position The local position
  70782. * @param mesh The mesh that this bone is attached to.
  70783. * @returns The world position
  70784. */
  70785. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70786. if (mesh === void 0) { mesh = null; }
  70787. var result = BABYLON.Vector3.Zero();
  70788. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70789. return result;
  70790. };
  70791. /**
  70792. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70793. * @param position The local position
  70794. * @param mesh The mesh that this bone is attached to.
  70795. * @param result The vector3 that the world position should be copied to.
  70796. */
  70797. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70798. if (mesh === void 0) { mesh = null; }
  70799. var wm = null;
  70800. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70801. if (mesh) {
  70802. wm = mesh.getWorldMatrix();
  70803. }
  70804. this._skeleton.computeAbsoluteTransforms();
  70805. var tmat = Bone._tmpMats[0];
  70806. if (mesh && wm) {
  70807. tmat.copyFrom(this.getAbsoluteTransform());
  70808. tmat.multiplyToRef(wm, tmat);
  70809. }
  70810. else {
  70811. tmat = this.getAbsoluteTransform();
  70812. }
  70813. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70814. };
  70815. /**
  70816. * Get the local position of a point that is in world space.
  70817. * @param position The world position
  70818. * @param mesh The mesh that this bone is attached to.
  70819. * @returns The local position
  70820. */
  70821. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70822. if (mesh === void 0) { mesh = null; }
  70823. var result = BABYLON.Vector3.Zero();
  70824. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70825. return result;
  70826. };
  70827. /**
  70828. * Get the local position of a point that is in world space and copy it to the result param.
  70829. * @param position The world position
  70830. * @param mesh The mesh that this bone is attached to.
  70831. * @param result The vector3 that the local position should be copied to.
  70832. */
  70833. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70834. if (mesh === void 0) { mesh = null; }
  70835. var wm = null;
  70836. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70837. if (mesh) {
  70838. wm = mesh.getWorldMatrix();
  70839. }
  70840. this._skeleton.computeAbsoluteTransforms();
  70841. var tmat = Bone._tmpMats[0];
  70842. tmat.copyFrom(this.getAbsoluteTransform());
  70843. if (mesh && wm) {
  70844. tmat.multiplyToRef(wm, tmat);
  70845. }
  70846. tmat.invert();
  70847. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70848. };
  70849. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70850. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70851. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70852. return Bone;
  70853. }(BABYLON.Node));
  70854. BABYLON.Bone = Bone;
  70855. })(BABYLON || (BABYLON = {}));
  70856. //# sourceMappingURL=babylon.bone.js.map
  70857. var BABYLON;
  70858. (function (BABYLON) {
  70859. var BoneIKController = /** @class */ (function () {
  70860. function BoneIKController(mesh, bone, options) {
  70861. this.targetPosition = BABYLON.Vector3.Zero();
  70862. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70863. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70864. this.poleAngle = 0;
  70865. this.slerpAmount = 1;
  70866. this._bone1Quat = BABYLON.Quaternion.Identity();
  70867. this._bone1Mat = BABYLON.Matrix.Identity();
  70868. this._bone2Ang = Math.PI;
  70869. this._maxAngle = Math.PI;
  70870. this._rightHandedSystem = false;
  70871. this._bendAxis = BABYLON.Vector3.Right();
  70872. this._slerping = false;
  70873. this._adjustRoll = 0;
  70874. this._bone2 = bone;
  70875. this._bone1 = bone.getParent();
  70876. if (!this._bone1) {
  70877. return;
  70878. }
  70879. this.mesh = mesh;
  70880. var bonePos = bone.getPosition();
  70881. if (bone.getAbsoluteTransform().determinant() > 0) {
  70882. this._rightHandedSystem = true;
  70883. this._bendAxis.x = 0;
  70884. this._bendAxis.y = 0;
  70885. this._bendAxis.z = -1;
  70886. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70887. this._adjustRoll = Math.PI * .5;
  70888. this._bendAxis.z = 1;
  70889. }
  70890. }
  70891. if (this._bone1.length) {
  70892. var boneScale1 = this._bone1.getScale();
  70893. var boneScale2 = this._bone2.getScale();
  70894. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70895. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70896. }
  70897. else if (this._bone1.children[0]) {
  70898. mesh.computeWorldMatrix(true);
  70899. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70900. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70901. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70902. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70903. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70904. }
  70905. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70906. this.maxAngle = Math.PI;
  70907. if (options) {
  70908. if (options.targetMesh) {
  70909. this.targetMesh = options.targetMesh;
  70910. this.targetMesh.computeWorldMatrix(true);
  70911. }
  70912. if (options.poleTargetMesh) {
  70913. this.poleTargetMesh = options.poleTargetMesh;
  70914. this.poleTargetMesh.computeWorldMatrix(true);
  70915. }
  70916. else if (options.poleTargetBone) {
  70917. this.poleTargetBone = options.poleTargetBone;
  70918. }
  70919. else if (this._bone1.getParent()) {
  70920. this.poleTargetBone = this._bone1.getParent();
  70921. }
  70922. if (options.poleTargetLocalOffset) {
  70923. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70924. }
  70925. if (options.poleAngle) {
  70926. this.poleAngle = options.poleAngle;
  70927. }
  70928. if (options.bendAxis) {
  70929. this._bendAxis.copyFrom(options.bendAxis);
  70930. }
  70931. if (options.maxAngle) {
  70932. this.maxAngle = options.maxAngle;
  70933. }
  70934. if (options.slerpAmount) {
  70935. this.slerpAmount = options.slerpAmount;
  70936. }
  70937. }
  70938. }
  70939. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70940. get: function () {
  70941. return this._maxAngle;
  70942. },
  70943. set: function (value) {
  70944. this._setMaxAngle(value);
  70945. },
  70946. enumerable: true,
  70947. configurable: true
  70948. });
  70949. BoneIKController.prototype._setMaxAngle = function (ang) {
  70950. if (ang < 0) {
  70951. ang = 0;
  70952. }
  70953. if (ang > Math.PI || ang == undefined) {
  70954. ang = Math.PI;
  70955. }
  70956. this._maxAngle = ang;
  70957. var a = this._bone1Length;
  70958. var b = this._bone2Length;
  70959. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70960. };
  70961. BoneIKController.prototype.update = function () {
  70962. var bone1 = this._bone1;
  70963. if (!bone1) {
  70964. return;
  70965. }
  70966. var target = this.targetPosition;
  70967. var poleTarget = this.poleTargetPosition;
  70968. var mat1 = BoneIKController._tmpMats[0];
  70969. var mat2 = BoneIKController._tmpMats[1];
  70970. if (this.targetMesh) {
  70971. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70972. }
  70973. if (this.poleTargetBone) {
  70974. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70975. }
  70976. else if (this.poleTargetMesh) {
  70977. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70978. }
  70979. var bonePos = BoneIKController._tmpVecs[0];
  70980. var zaxis = BoneIKController._tmpVecs[1];
  70981. var xaxis = BoneIKController._tmpVecs[2];
  70982. var yaxis = BoneIKController._tmpVecs[3];
  70983. var upAxis = BoneIKController._tmpVecs[4];
  70984. var _tmpQuat = BoneIKController._tmpQuat;
  70985. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70986. poleTarget.subtractToRef(bonePos, upAxis);
  70987. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70988. upAxis.y = 1;
  70989. }
  70990. else {
  70991. upAxis.normalize();
  70992. }
  70993. target.subtractToRef(bonePos, yaxis);
  70994. yaxis.normalize();
  70995. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70996. zaxis.normalize();
  70997. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70998. xaxis.normalize();
  70999. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  71000. var a = this._bone1Length;
  71001. var b = this._bone2Length;
  71002. var c = BABYLON.Vector3.Distance(bonePos, target);
  71003. if (this._maxReach > 0) {
  71004. c = Math.min(this._maxReach, c);
  71005. }
  71006. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  71007. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  71008. if (acosa > 1) {
  71009. acosa = 1;
  71010. }
  71011. if (acosb > 1) {
  71012. acosb = 1;
  71013. }
  71014. if (acosa < -1) {
  71015. acosa = -1;
  71016. }
  71017. if (acosb < -1) {
  71018. acosb = -1;
  71019. }
  71020. var angA = Math.acos(acosa);
  71021. var angB = Math.acos(acosb);
  71022. var angC = -angA - angB;
  71023. if (this._rightHandedSystem) {
  71024. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  71025. mat2.multiplyToRef(mat1, mat1);
  71026. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  71027. mat2.multiplyToRef(mat1, mat1);
  71028. }
  71029. else {
  71030. var _tmpVec = BoneIKController._tmpVecs[5];
  71031. _tmpVec.copyFrom(this._bendAxis);
  71032. _tmpVec.x *= -1;
  71033. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  71034. mat2.multiplyToRef(mat1, mat1);
  71035. }
  71036. if (this.poleAngle) {
  71037. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  71038. mat1.multiplyToRef(mat2, mat1);
  71039. }
  71040. if (this._bone1) {
  71041. if (this.slerpAmount < 1) {
  71042. if (!this._slerping) {
  71043. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  71044. }
  71045. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  71046. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  71047. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  71048. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  71049. this._slerping = true;
  71050. }
  71051. else {
  71052. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  71053. this._bone1Mat.copyFrom(mat1);
  71054. this._slerping = false;
  71055. }
  71056. }
  71057. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  71058. this._bone2Ang = angC;
  71059. };
  71060. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71061. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  71062. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71063. return BoneIKController;
  71064. }());
  71065. BABYLON.BoneIKController = BoneIKController;
  71066. })(BABYLON || (BABYLON = {}));
  71067. //# sourceMappingURL=babylon.boneIKController.js.map
  71068. var BABYLON;
  71069. (function (BABYLON) {
  71070. var BoneLookController = /** @class */ (function () {
  71071. /**
  71072. * Create a BoneLookController
  71073. * @param mesh the mesh that the bone belongs to
  71074. * @param bone the bone that will be looking to the target
  71075. * @param target the target Vector3 to look at
  71076. * @param settings optional settings:
  71077. * - maxYaw: the maximum angle the bone will yaw to
  71078. * - minYaw: the minimum angle the bone will yaw to
  71079. * - maxPitch: the maximum angle the bone will pitch to
  71080. * - minPitch: the minimum angle the bone will yaw to
  71081. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  71082. * - upAxis: the up axis of the coordinate system
  71083. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71084. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  71085. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  71086. * - adjustYaw: used to make an adjustment to the yaw of the bone
  71087. * - adjustPitch: used to make an adjustment to the pitch of the bone
  71088. * - adjustRoll: used to make an adjustment to the roll of the bone
  71089. **/
  71090. function BoneLookController(mesh, bone, target, options) {
  71091. /**
  71092. * The up axis of the coordinate system that is used when the bone is rotated.
  71093. */
  71094. this.upAxis = BABYLON.Vector3.Up();
  71095. /**
  71096. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  71097. */
  71098. this.upAxisSpace = BABYLON.Space.LOCAL;
  71099. /**
  71100. * Used to make an adjustment to the yaw of the bone.
  71101. */
  71102. this.adjustYaw = 0;
  71103. /**
  71104. * Used to make an adjustment to the pitch of the bone.
  71105. */
  71106. this.adjustPitch = 0;
  71107. /**
  71108. * Used to make an adjustment to the roll of the bone.
  71109. */
  71110. this.adjustRoll = 0;
  71111. /**
  71112. * 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).
  71113. */
  71114. this.slerpAmount = 1;
  71115. this._boneQuat = BABYLON.Quaternion.Identity();
  71116. this._slerping = false;
  71117. this._firstFrameSkipped = false;
  71118. this._fowardAxis = BABYLON.Vector3.Forward();
  71119. this.mesh = mesh;
  71120. this.bone = bone;
  71121. this.target = target;
  71122. if (options) {
  71123. if (options.adjustYaw) {
  71124. this.adjustYaw = options.adjustYaw;
  71125. }
  71126. if (options.adjustPitch) {
  71127. this.adjustPitch = options.adjustPitch;
  71128. }
  71129. if (options.adjustRoll) {
  71130. this.adjustRoll = options.adjustRoll;
  71131. }
  71132. if (options.maxYaw != null) {
  71133. this.maxYaw = options.maxYaw;
  71134. }
  71135. else {
  71136. this.maxYaw = Math.PI;
  71137. }
  71138. if (options.minYaw != null) {
  71139. this.minYaw = options.minYaw;
  71140. }
  71141. else {
  71142. this.minYaw = -Math.PI;
  71143. }
  71144. if (options.maxPitch != null) {
  71145. this.maxPitch = options.maxPitch;
  71146. }
  71147. else {
  71148. this.maxPitch = Math.PI;
  71149. }
  71150. if (options.minPitch != null) {
  71151. this.minPitch = options.minPitch;
  71152. }
  71153. else {
  71154. this.minPitch = -Math.PI;
  71155. }
  71156. if (options.slerpAmount != null) {
  71157. this.slerpAmount = options.slerpAmount;
  71158. }
  71159. if (options.upAxis != null) {
  71160. this.upAxis = options.upAxis;
  71161. }
  71162. if (options.upAxisSpace != null) {
  71163. this.upAxisSpace = options.upAxisSpace;
  71164. }
  71165. if (options.yawAxis != null || options.pitchAxis != null) {
  71166. var newYawAxis = BABYLON.Axis.Y;
  71167. var newPitchAxis = BABYLON.Axis.X;
  71168. if (options.yawAxis != null) {
  71169. newYawAxis = options.yawAxis.clone();
  71170. newYawAxis.normalize();
  71171. }
  71172. if (options.pitchAxis != null) {
  71173. newPitchAxis = options.pitchAxis.clone();
  71174. newPitchAxis.normalize();
  71175. }
  71176. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  71177. this._transformYawPitch = BABYLON.Matrix.Identity();
  71178. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  71179. this._transformYawPitchInv = this._transformYawPitch.clone();
  71180. this._transformYawPitch.invert();
  71181. }
  71182. }
  71183. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  71184. this.upAxisSpace = BABYLON.Space.LOCAL;
  71185. }
  71186. }
  71187. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  71188. /**
  71189. * Get/set the minimum yaw angle that the bone can look to.
  71190. */
  71191. get: function () {
  71192. return this._minYaw;
  71193. },
  71194. set: function (value) {
  71195. this._minYaw = value;
  71196. this._minYawSin = Math.sin(value);
  71197. this._minYawCos = Math.cos(value);
  71198. if (this._maxYaw != null) {
  71199. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71200. this._yawRange = this._maxYaw - this._minYaw;
  71201. }
  71202. },
  71203. enumerable: true,
  71204. configurable: true
  71205. });
  71206. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  71207. /**
  71208. * Get/set the maximum yaw angle that the bone can look to.
  71209. */
  71210. get: function () {
  71211. return this._maxYaw;
  71212. },
  71213. set: function (value) {
  71214. this._maxYaw = value;
  71215. this._maxYawSin = Math.sin(value);
  71216. this._maxYawCos = Math.cos(value);
  71217. if (this._minYaw != null) {
  71218. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  71219. this._yawRange = this._maxYaw - this._minYaw;
  71220. }
  71221. },
  71222. enumerable: true,
  71223. configurable: true
  71224. });
  71225. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71226. /**
  71227. * Get/set the minimum pitch angle that the bone can look to.
  71228. */
  71229. get: function () {
  71230. return this._minPitch;
  71231. },
  71232. set: function (value) {
  71233. this._minPitch = value;
  71234. this._minPitchTan = Math.tan(value);
  71235. },
  71236. enumerable: true,
  71237. configurable: true
  71238. });
  71239. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71240. /**
  71241. * Get/set the maximum pitch angle that the bone can look to.
  71242. */
  71243. get: function () {
  71244. return this._maxPitch;
  71245. },
  71246. set: function (value) {
  71247. this._maxPitch = value;
  71248. this._maxPitchTan = Math.tan(value);
  71249. },
  71250. enumerable: true,
  71251. configurable: true
  71252. });
  71253. /**
  71254. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71255. */
  71256. BoneLookController.prototype.update = function () {
  71257. //skip the first frame when slerping so that the mesh rotation is correct
  71258. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71259. this._firstFrameSkipped = true;
  71260. return;
  71261. }
  71262. var bone = this.bone;
  71263. var bonePos = BoneLookController._tmpVecs[0];
  71264. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71265. var target = this.target;
  71266. var _tmpMat1 = BoneLookController._tmpMats[0];
  71267. var _tmpMat2 = BoneLookController._tmpMats[1];
  71268. var mesh = this.mesh;
  71269. var parentBone = bone.getParent();
  71270. var upAxis = BoneLookController._tmpVecs[1];
  71271. upAxis.copyFrom(this.upAxis);
  71272. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71273. if (this._transformYawPitch) {
  71274. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71275. }
  71276. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71277. }
  71278. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71279. mesh.getDirectionToRef(upAxis, upAxis);
  71280. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71281. upAxis.normalize();
  71282. }
  71283. }
  71284. var checkYaw = false;
  71285. var checkPitch = false;
  71286. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71287. checkYaw = true;
  71288. }
  71289. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71290. checkPitch = true;
  71291. }
  71292. if (checkYaw || checkPitch) {
  71293. var spaceMat = BoneLookController._tmpMats[2];
  71294. var spaceMatInv = BoneLookController._tmpMats[3];
  71295. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71296. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71297. }
  71298. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71299. spaceMat.copyFrom(mesh.getWorldMatrix());
  71300. }
  71301. else {
  71302. var forwardAxis = BoneLookController._tmpVecs[2];
  71303. forwardAxis.copyFrom(this._fowardAxis);
  71304. if (this._transformYawPitch) {
  71305. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71306. }
  71307. if (parentBone) {
  71308. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71309. }
  71310. else {
  71311. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71312. }
  71313. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71314. rightAxis.normalize();
  71315. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71316. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71317. }
  71318. spaceMat.invertToRef(spaceMatInv);
  71319. var xzlen = null;
  71320. if (checkPitch) {
  71321. var localTarget = BoneLookController._tmpVecs[3];
  71322. target.subtractToRef(bonePos, localTarget);
  71323. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71324. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71325. var pitch = Math.atan2(localTarget.y, xzlen);
  71326. var newPitch = pitch;
  71327. if (pitch > this._maxPitch) {
  71328. localTarget.y = this._maxPitchTan * xzlen;
  71329. newPitch = this._maxPitch;
  71330. }
  71331. else if (pitch < this._minPitch) {
  71332. localTarget.y = this._minPitchTan * xzlen;
  71333. newPitch = this._minPitch;
  71334. }
  71335. if (pitch != newPitch) {
  71336. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71337. localTarget.addInPlace(bonePos);
  71338. target = localTarget;
  71339. }
  71340. }
  71341. if (checkYaw) {
  71342. var localTarget = BoneLookController._tmpVecs[4];
  71343. target.subtractToRef(bonePos, localTarget);
  71344. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71345. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71346. var newYaw = yaw;
  71347. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71348. if (xzlen == null) {
  71349. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71350. }
  71351. if (this._yawRange > Math.PI) {
  71352. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71353. localTarget.z = this._maxYawCos * xzlen;
  71354. localTarget.x = this._maxYawSin * xzlen;
  71355. newYaw = this._maxYaw;
  71356. }
  71357. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71358. localTarget.z = this._minYawCos * xzlen;
  71359. localTarget.x = this._minYawSin * xzlen;
  71360. newYaw = this._minYaw;
  71361. }
  71362. }
  71363. else {
  71364. if (yaw > this._maxYaw) {
  71365. localTarget.z = this._maxYawCos * xzlen;
  71366. localTarget.x = this._maxYawSin * xzlen;
  71367. newYaw = this._maxYaw;
  71368. }
  71369. else if (yaw < this._minYaw) {
  71370. localTarget.z = this._minYawCos * xzlen;
  71371. localTarget.x = this._minYawSin * xzlen;
  71372. newYaw = this._minYaw;
  71373. }
  71374. }
  71375. }
  71376. if (this._slerping && this._yawRange > Math.PI) {
  71377. //are we going to be crossing into the min/max region?
  71378. var boneFwd = BoneLookController._tmpVecs[8];
  71379. boneFwd.copyFrom(BABYLON.Axis.Z);
  71380. if (this._transformYawPitch) {
  71381. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71382. }
  71383. var boneRotMat = BoneLookController._tmpMats[4];
  71384. this._boneQuat.toRotationMatrix(boneRotMat);
  71385. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71386. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71387. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71388. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71389. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71390. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71391. if (angBtwTar > angBtwMidYaw) {
  71392. if (xzlen == null) {
  71393. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71394. }
  71395. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71396. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71397. if (angBtwMin < angBtwMax) {
  71398. newYaw = boneYaw + Math.PI * .75;
  71399. localTarget.z = Math.cos(newYaw) * xzlen;
  71400. localTarget.x = Math.sin(newYaw) * xzlen;
  71401. }
  71402. else {
  71403. newYaw = boneYaw - Math.PI * .75;
  71404. localTarget.z = Math.cos(newYaw) * xzlen;
  71405. localTarget.x = Math.sin(newYaw) * xzlen;
  71406. }
  71407. }
  71408. }
  71409. if (yaw != newYaw) {
  71410. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71411. localTarget.addInPlace(bonePos);
  71412. target = localTarget;
  71413. }
  71414. }
  71415. }
  71416. var zaxis = BoneLookController._tmpVecs[5];
  71417. var xaxis = BoneLookController._tmpVecs[6];
  71418. var yaxis = BoneLookController._tmpVecs[7];
  71419. var _tmpQuat = BoneLookController._tmpQuat;
  71420. target.subtractToRef(bonePos, zaxis);
  71421. zaxis.normalize();
  71422. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71423. xaxis.normalize();
  71424. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71425. yaxis.normalize();
  71426. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71427. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71428. return;
  71429. }
  71430. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71431. return;
  71432. }
  71433. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71434. return;
  71435. }
  71436. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71437. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71438. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71439. }
  71440. if (this.slerpAmount < 1) {
  71441. if (!this._slerping) {
  71442. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71443. }
  71444. if (this._transformYawPitch) {
  71445. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71446. }
  71447. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71448. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71449. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71450. this._slerping = true;
  71451. }
  71452. else {
  71453. if (this._transformYawPitch) {
  71454. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71455. }
  71456. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71457. this._slerping = false;
  71458. }
  71459. };
  71460. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71461. var angDiff = ang2 - ang1;
  71462. angDiff %= Math.PI * 2;
  71463. if (angDiff > Math.PI) {
  71464. angDiff -= Math.PI * 2;
  71465. }
  71466. else if (angDiff < -Math.PI) {
  71467. angDiff += Math.PI * 2;
  71468. }
  71469. return angDiff;
  71470. };
  71471. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71472. ang1 %= (2 * Math.PI);
  71473. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71474. ang2 %= (2 * Math.PI);
  71475. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71476. var ab = 0;
  71477. if (ang1 < ang2) {
  71478. ab = ang2 - ang1;
  71479. }
  71480. else {
  71481. ab = ang1 - ang2;
  71482. }
  71483. if (ab > Math.PI) {
  71484. ab = Math.PI * 2 - ab;
  71485. }
  71486. return ab;
  71487. };
  71488. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71489. ang %= (2 * Math.PI);
  71490. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71491. ang1 %= (2 * Math.PI);
  71492. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71493. ang2 %= (2 * Math.PI);
  71494. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71495. if (ang1 < ang2) {
  71496. if (ang > ang1 && ang < ang2) {
  71497. return true;
  71498. }
  71499. }
  71500. else {
  71501. if (ang > ang2 && ang < ang1) {
  71502. return true;
  71503. }
  71504. }
  71505. return false;
  71506. };
  71507. 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()];
  71508. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71509. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71510. return BoneLookController;
  71511. }());
  71512. BABYLON.BoneLookController = BoneLookController;
  71513. })(BABYLON || (BABYLON = {}));
  71514. //# sourceMappingURL=babylon.boneLookController.js.map
  71515. var BABYLON;
  71516. (function (BABYLON) {
  71517. var Skeleton = /** @class */ (function () {
  71518. function Skeleton(name, id, scene) {
  71519. this.name = name;
  71520. this.id = id;
  71521. this.bones = new Array();
  71522. this.needInitialSkinMatrix = false;
  71523. this._isDirty = true;
  71524. this._meshesWithPoseMatrix = new Array();
  71525. this._identity = BABYLON.Matrix.Identity();
  71526. this._ranges = {};
  71527. this._lastAbsoluteTransformsUpdateId = -1;
  71528. /**
  71529. * Specifies if the skeleton should be serialized.
  71530. */
  71531. this.doNotSerialize = false;
  71532. // Events
  71533. /**
  71534. * An event triggered before computing the skeleton's matrices
  71535. * @type {BABYLON.Observable}
  71536. */
  71537. this.onBeforeComputeObservable = new BABYLON.Observable();
  71538. this.bones = [];
  71539. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71540. scene.skeletons.push(this);
  71541. //make sure it will recalculate the matrix next time prepare is called.
  71542. this._isDirty = true;
  71543. }
  71544. // Members
  71545. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71546. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71547. return mesh._bonesTransformMatrices;
  71548. }
  71549. if (!this._transformMatrices) {
  71550. this.prepare();
  71551. }
  71552. return this._transformMatrices;
  71553. };
  71554. Skeleton.prototype.getScene = function () {
  71555. return this._scene;
  71556. };
  71557. // Methods
  71558. /**
  71559. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71560. */
  71561. Skeleton.prototype.toString = function (fullDetails) {
  71562. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71563. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71564. if (fullDetails) {
  71565. ret += ", Ranges: {";
  71566. var first = true;
  71567. for (var name_1 in this._ranges) {
  71568. if (first) {
  71569. ret += ", ";
  71570. first = false;
  71571. }
  71572. ret += name_1;
  71573. }
  71574. ret += "}";
  71575. }
  71576. return ret;
  71577. };
  71578. /**
  71579. * Get bone's index searching by name
  71580. * @param {string} name is bone's name to search for
  71581. * @return {number} Indice of the bone. Returns -1 if not found
  71582. */
  71583. Skeleton.prototype.getBoneIndexByName = function (name) {
  71584. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71585. if (this.bones[boneIndex].name === name) {
  71586. return boneIndex;
  71587. }
  71588. }
  71589. return -1;
  71590. };
  71591. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71592. // check name not already in use
  71593. if (!this._ranges[name]) {
  71594. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71595. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71596. if (this.bones[i].animations[0]) {
  71597. this.bones[i].animations[0].createRange(name, from, to);
  71598. }
  71599. }
  71600. }
  71601. };
  71602. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71603. if (deleteFrames === void 0) { deleteFrames = true; }
  71604. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71605. if (this.bones[i].animations[0]) {
  71606. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71607. }
  71608. }
  71609. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71610. };
  71611. Skeleton.prototype.getAnimationRange = function (name) {
  71612. return this._ranges[name];
  71613. };
  71614. /**
  71615. * Returns as an Array, all AnimationRanges defined on this skeleton
  71616. */
  71617. Skeleton.prototype.getAnimationRanges = function () {
  71618. var animationRanges = [];
  71619. var name;
  71620. var i = 0;
  71621. for (name in this._ranges) {
  71622. animationRanges[i] = this._ranges[name];
  71623. i++;
  71624. }
  71625. return animationRanges;
  71626. };
  71627. /**
  71628. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71629. */
  71630. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71631. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71632. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71633. return false;
  71634. }
  71635. var ret = true;
  71636. var frameOffset = this._getHighestAnimationFrame() + 1;
  71637. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71638. var boneDict = {};
  71639. var sourceBones = source.bones;
  71640. var nBones;
  71641. var i;
  71642. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71643. boneDict[sourceBones[i].name] = sourceBones[i];
  71644. }
  71645. if (this.bones.length !== sourceBones.length) {
  71646. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71647. ret = false;
  71648. }
  71649. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71650. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71651. var boneName = this.bones[i].name;
  71652. var sourceBone = boneDict[boneName];
  71653. if (sourceBone) {
  71654. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71655. }
  71656. else {
  71657. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71658. ret = false;
  71659. }
  71660. }
  71661. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71662. var range = source.getAnimationRange(name);
  71663. if (range) {
  71664. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71665. }
  71666. return ret;
  71667. };
  71668. Skeleton.prototype.returnToRest = function () {
  71669. for (var index = 0; index < this.bones.length; index++) {
  71670. this.bones[index].returnToRest();
  71671. }
  71672. };
  71673. Skeleton.prototype._getHighestAnimationFrame = function () {
  71674. var ret = 0;
  71675. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71676. if (this.bones[i].animations[0]) {
  71677. var highest = this.bones[i].animations[0].getHighestFrame();
  71678. if (ret < highest) {
  71679. ret = highest;
  71680. }
  71681. }
  71682. }
  71683. return ret;
  71684. };
  71685. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71686. var range = this.getAnimationRange(name);
  71687. if (!range) {
  71688. return null;
  71689. }
  71690. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71691. };
  71692. Skeleton.prototype._markAsDirty = function () {
  71693. this._isDirty = true;
  71694. };
  71695. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71696. this._meshesWithPoseMatrix.push(mesh);
  71697. };
  71698. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71699. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71700. if (index > -1) {
  71701. this._meshesWithPoseMatrix.splice(index, 1);
  71702. }
  71703. };
  71704. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71705. this.onBeforeComputeObservable.notifyObservers(this);
  71706. for (var index = 0; index < this.bones.length; index++) {
  71707. var bone = this.bones[index];
  71708. var parentBone = bone.getParent();
  71709. if (parentBone) {
  71710. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71711. }
  71712. else {
  71713. if (initialSkinMatrix) {
  71714. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71715. }
  71716. else {
  71717. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71718. }
  71719. }
  71720. if (bone._index !== -1) {
  71721. var mappedIndex = bone._index === null ? index : bone._index;
  71722. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71723. }
  71724. }
  71725. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71726. };
  71727. Skeleton.prototype.prepare = function () {
  71728. if (!this._isDirty) {
  71729. return;
  71730. }
  71731. if (this.needInitialSkinMatrix) {
  71732. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71733. var mesh = this._meshesWithPoseMatrix[index];
  71734. var poseMatrix = mesh.getPoseMatrix();
  71735. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71736. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71737. }
  71738. if (this._synchronizedWithMesh !== mesh) {
  71739. this._synchronizedWithMesh = mesh;
  71740. // Prepare bones
  71741. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71742. var bone = this.bones[boneIndex];
  71743. if (!bone.getParent()) {
  71744. var matrix = bone.getBaseMatrix();
  71745. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71746. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71747. }
  71748. }
  71749. }
  71750. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71751. }
  71752. }
  71753. else {
  71754. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71755. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71756. }
  71757. this._computeTransformMatrices(this._transformMatrices, null);
  71758. }
  71759. this._isDirty = false;
  71760. this._scene._activeBones.addCount(this.bones.length, false);
  71761. };
  71762. Skeleton.prototype.getAnimatables = function () {
  71763. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71764. this._animatables = [];
  71765. for (var index = 0; index < this.bones.length; index++) {
  71766. this._animatables.push(this.bones[index]);
  71767. }
  71768. }
  71769. return this._animatables;
  71770. };
  71771. Skeleton.prototype.clone = function (name, id) {
  71772. var result = new Skeleton(name, id || name, this._scene);
  71773. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71774. for (var index = 0; index < this.bones.length; index++) {
  71775. var source = this.bones[index];
  71776. var parentBone = null;
  71777. var parent_1 = source.getParent();
  71778. if (parent_1) {
  71779. var parentIndex = this.bones.indexOf(parent_1);
  71780. parentBone = result.bones[parentIndex];
  71781. }
  71782. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71783. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71784. }
  71785. if (this._ranges) {
  71786. result._ranges = {};
  71787. for (var rangeName in this._ranges) {
  71788. var range = this._ranges[rangeName];
  71789. if (range) {
  71790. result._ranges[rangeName] = range.clone();
  71791. }
  71792. }
  71793. }
  71794. this._isDirty = true;
  71795. return result;
  71796. };
  71797. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71798. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71799. this.bones.forEach(function (bone) {
  71800. bone.animations.forEach(function (animation) {
  71801. animation.enableBlending = true;
  71802. animation.blendingSpeed = blendingSpeed;
  71803. });
  71804. });
  71805. };
  71806. Skeleton.prototype.dispose = function () {
  71807. this._meshesWithPoseMatrix = [];
  71808. // Animations
  71809. this.getScene().stopAnimation(this);
  71810. // Remove from scene
  71811. this.getScene().removeSkeleton(this);
  71812. };
  71813. Skeleton.prototype.serialize = function () {
  71814. var serializationObject = {};
  71815. serializationObject.name = this.name;
  71816. serializationObject.id = this.id;
  71817. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71818. serializationObject.bones = [];
  71819. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71820. for (var index = 0; index < this.bones.length; index++) {
  71821. var bone = this.bones[index];
  71822. var parent_2 = bone.getParent();
  71823. var serializedBone = {
  71824. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71825. name: bone.name,
  71826. matrix: bone.getBaseMatrix().toArray(),
  71827. rest: bone.getRestPose().toArray()
  71828. };
  71829. serializationObject.bones.push(serializedBone);
  71830. if (bone.length) {
  71831. serializedBone.length = bone.length;
  71832. }
  71833. if (bone.animations && bone.animations.length > 0) {
  71834. serializedBone.animation = bone.animations[0].serialize();
  71835. }
  71836. serializationObject.ranges = [];
  71837. for (var name in this._ranges) {
  71838. var source = this._ranges[name];
  71839. if (!source) {
  71840. continue;
  71841. }
  71842. var range = {};
  71843. range.name = name;
  71844. range.from = source.from;
  71845. range.to = source.to;
  71846. serializationObject.ranges.push(range);
  71847. }
  71848. }
  71849. return serializationObject;
  71850. };
  71851. Skeleton.Parse = function (parsedSkeleton, scene) {
  71852. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71853. if (parsedSkeleton.dimensionsAtRest) {
  71854. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71855. }
  71856. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71857. var index;
  71858. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71859. var parsedBone = parsedSkeleton.bones[index];
  71860. var parentBone = null;
  71861. if (parsedBone.parentBoneIndex > -1) {
  71862. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71863. }
  71864. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71865. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71866. if (parsedBone.length) {
  71867. bone.length = parsedBone.length;
  71868. }
  71869. if (parsedBone.animation) {
  71870. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71871. }
  71872. }
  71873. // placed after bones, so createAnimationRange can cascade down
  71874. if (parsedSkeleton.ranges) {
  71875. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71876. var data = parsedSkeleton.ranges[index];
  71877. skeleton.createAnimationRange(data.name, data.from, data.to);
  71878. }
  71879. }
  71880. return skeleton;
  71881. };
  71882. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71883. if (forceUpdate === void 0) { forceUpdate = false; }
  71884. var renderId = this._scene.getRenderId();
  71885. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71886. this.bones[0].computeAbsoluteTransforms();
  71887. this._lastAbsoluteTransformsUpdateId = renderId;
  71888. }
  71889. };
  71890. Skeleton.prototype.getPoseMatrix = function () {
  71891. var poseMatrix = null;
  71892. if (this._meshesWithPoseMatrix.length > 0) {
  71893. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71894. }
  71895. return poseMatrix;
  71896. };
  71897. Skeleton.prototype.sortBones = function () {
  71898. var bones = new Array();
  71899. var visited = new Array(this.bones.length);
  71900. for (var index = 0; index < this.bones.length; index++) {
  71901. this._sortBones(index, bones, visited);
  71902. }
  71903. this.bones = bones;
  71904. };
  71905. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71906. if (visited[index]) {
  71907. return;
  71908. }
  71909. visited[index] = true;
  71910. var bone = this.bones[index];
  71911. if (bone._index === undefined) {
  71912. bone._index = index;
  71913. }
  71914. var parentBone = bone.getParent();
  71915. if (parentBone) {
  71916. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71917. }
  71918. bones.push(bone);
  71919. };
  71920. return Skeleton;
  71921. }());
  71922. BABYLON.Skeleton = Skeleton;
  71923. })(BABYLON || (BABYLON = {}));
  71924. //# sourceMappingURL=babylon.skeleton.js.map
  71925. var BABYLON;
  71926. (function (BABYLON) {
  71927. var SphericalPolynomial = /** @class */ (function () {
  71928. function SphericalPolynomial() {
  71929. this.x = BABYLON.Vector3.Zero();
  71930. this.y = BABYLON.Vector3.Zero();
  71931. this.z = BABYLON.Vector3.Zero();
  71932. this.xx = BABYLON.Vector3.Zero();
  71933. this.yy = BABYLON.Vector3.Zero();
  71934. this.zz = BABYLON.Vector3.Zero();
  71935. this.xy = BABYLON.Vector3.Zero();
  71936. this.yz = BABYLON.Vector3.Zero();
  71937. this.zx = BABYLON.Vector3.Zero();
  71938. }
  71939. SphericalPolynomial.prototype.addAmbient = function (color) {
  71940. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71941. this.xx = this.xx.add(colorVector);
  71942. this.yy = this.yy.add(colorVector);
  71943. this.zz = this.zz.add(colorVector);
  71944. };
  71945. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71946. var result = new SphericalPolynomial();
  71947. result.x = harmonics.L11.scale(1.02333);
  71948. result.y = harmonics.L1_1.scale(1.02333);
  71949. result.z = harmonics.L10.scale(1.02333);
  71950. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71951. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71952. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71953. result.yz = harmonics.L2_1.scale(0.858086);
  71954. result.zx = harmonics.L21.scale(0.858086);
  71955. result.xy = harmonics.L2_2.scale(0.858086);
  71956. result.scale(1.0 / Math.PI);
  71957. return result;
  71958. };
  71959. SphericalPolynomial.prototype.scale = function (scale) {
  71960. this.x = this.x.scale(scale);
  71961. this.y = this.y.scale(scale);
  71962. this.z = this.z.scale(scale);
  71963. this.xx = this.xx.scale(scale);
  71964. this.yy = this.yy.scale(scale);
  71965. this.zz = this.zz.scale(scale);
  71966. this.yz = this.yz.scale(scale);
  71967. this.zx = this.zx.scale(scale);
  71968. this.xy = this.xy.scale(scale);
  71969. };
  71970. return SphericalPolynomial;
  71971. }());
  71972. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71973. var SphericalHarmonics = /** @class */ (function () {
  71974. function SphericalHarmonics() {
  71975. this.L00 = BABYLON.Vector3.Zero();
  71976. this.L1_1 = BABYLON.Vector3.Zero();
  71977. this.L10 = BABYLON.Vector3.Zero();
  71978. this.L11 = BABYLON.Vector3.Zero();
  71979. this.L2_2 = BABYLON.Vector3.Zero();
  71980. this.L2_1 = BABYLON.Vector3.Zero();
  71981. this.L20 = BABYLON.Vector3.Zero();
  71982. this.L21 = BABYLON.Vector3.Zero();
  71983. this.L22 = BABYLON.Vector3.Zero();
  71984. }
  71985. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71986. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71987. var c = colorVector.scale(deltaSolidAngle);
  71988. this.L00 = this.L00.add(c.scale(0.282095));
  71989. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71990. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71991. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71992. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71993. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71994. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71995. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71996. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71997. };
  71998. SphericalHarmonics.prototype.scale = function (scale) {
  71999. this.L00 = this.L00.scale(scale);
  72000. this.L1_1 = this.L1_1.scale(scale);
  72001. this.L10 = this.L10.scale(scale);
  72002. this.L11 = this.L11.scale(scale);
  72003. this.L2_2 = this.L2_2.scale(scale);
  72004. this.L2_1 = this.L2_1.scale(scale);
  72005. this.L20 = this.L20.scale(scale);
  72006. this.L21 = this.L21.scale(scale);
  72007. this.L22 = this.L22.scale(scale);
  72008. };
  72009. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  72010. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  72011. //
  72012. // E_lm = A_l * L_lm
  72013. //
  72014. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  72015. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  72016. // the scaling factors are given in equation 9.
  72017. // Constant (Band 0)
  72018. this.L00 = this.L00.scale(3.141593);
  72019. // Linear (Band 1)
  72020. this.L1_1 = this.L1_1.scale(2.094395);
  72021. this.L10 = this.L10.scale(2.094395);
  72022. this.L11 = this.L11.scale(2.094395);
  72023. // Quadratic (Band 2)
  72024. this.L2_2 = this.L2_2.scale(0.785398);
  72025. this.L2_1 = this.L2_1.scale(0.785398);
  72026. this.L20 = this.L20.scale(0.785398);
  72027. this.L21 = this.L21.scale(0.785398);
  72028. this.L22 = this.L22.scale(0.785398);
  72029. };
  72030. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  72031. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  72032. // L = (1/pi) * E * rho
  72033. //
  72034. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  72035. this.scale(1.0 / Math.PI);
  72036. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  72037. // (The pixel shader must apply albedo after texture fetches, etc).
  72038. };
  72039. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  72040. var result = new SphericalHarmonics();
  72041. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  72042. result.L1_1 = polynomial.y.scale(0.977204);
  72043. result.L10 = polynomial.z.scale(0.977204);
  72044. result.L11 = polynomial.x.scale(0.977204);
  72045. result.L2_2 = polynomial.xy.scale(1.16538);
  72046. result.L2_1 = polynomial.yz.scale(1.16538);
  72047. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  72048. result.L21 = polynomial.zx.scale(1.16538);
  72049. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  72050. result.scale(Math.PI);
  72051. return result;
  72052. };
  72053. return SphericalHarmonics;
  72054. }());
  72055. BABYLON.SphericalHarmonics = SphericalHarmonics;
  72056. })(BABYLON || (BABYLON = {}));
  72057. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  72058. var BABYLON;
  72059. (function (BABYLON) {
  72060. var FileFaceOrientation = /** @class */ (function () {
  72061. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  72062. this.name = name;
  72063. this.worldAxisForNormal = worldAxisForNormal;
  72064. this.worldAxisForFileX = worldAxisForFileX;
  72065. this.worldAxisForFileY = worldAxisForFileY;
  72066. }
  72067. return FileFaceOrientation;
  72068. }());
  72069. ;
  72070. /**
  72071. * Helper class dealing with the extraction of spherical polynomial dataArray
  72072. * from a cube map.
  72073. */
  72074. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  72075. function CubeMapToSphericalPolynomialTools() {
  72076. }
  72077. /**
  72078. * Converts a texture to the according Spherical Polynomial data.
  72079. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72080. *
  72081. * @param texture The texture to extract the information from.
  72082. * @return The Spherical Polynomial data.
  72083. */
  72084. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  72085. if (!texture.isCube) {
  72086. // Only supports cube Textures currently.
  72087. return null;
  72088. }
  72089. var size = texture.getSize().width;
  72090. var right = texture.readPixels(0);
  72091. var left = texture.readPixels(1);
  72092. var up;
  72093. var down;
  72094. if (texture.isRenderTarget) {
  72095. up = texture.readPixels(3);
  72096. down = texture.readPixels(2);
  72097. }
  72098. else {
  72099. up = texture.readPixels(2);
  72100. down = texture.readPixels(3);
  72101. }
  72102. var front = texture.readPixels(4);
  72103. var back = texture.readPixels(5);
  72104. var gammaSpace = texture.gammaSpace;
  72105. // Always read as RGBA.
  72106. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  72107. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72108. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72109. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72110. }
  72111. var cubeInfo = {
  72112. size: size,
  72113. right: right,
  72114. left: left,
  72115. up: up,
  72116. down: down,
  72117. front: front,
  72118. back: back,
  72119. format: format,
  72120. type: type,
  72121. gammaSpace: gammaSpace,
  72122. };
  72123. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  72124. };
  72125. /**
  72126. * Converts a cubemap to the according Spherical Polynomial data.
  72127. * This extracts the first 3 orders only as they are the only one used in the lighting.
  72128. *
  72129. * @param cubeInfo The Cube map to extract the information from.
  72130. * @return The Spherical Polynomial data.
  72131. */
  72132. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  72133. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  72134. var totalSolidAngle = 0.0;
  72135. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  72136. var du = 2.0 / cubeInfo.size;
  72137. var dv = du;
  72138. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  72139. var minUV = du * 0.5 - 1.0;
  72140. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72141. var fileFace = this.FileFaces[faceIndex];
  72142. var dataArray = cubeInfo[fileFace.name];
  72143. var v = minUV;
  72144. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  72145. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  72146. // Because SP is still linear, so summation is fine in that basis.
  72147. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  72148. for (var y = 0; y < cubeInfo.size; y++) {
  72149. var u = minUV;
  72150. for (var x = 0; x < cubeInfo.size; x++) {
  72151. // World direction (not normalised)
  72152. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  72153. worldDirection.normalize();
  72154. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  72155. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  72156. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  72157. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  72158. // Handle Integer types.
  72159. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72160. r /= 255;
  72161. g /= 255;
  72162. b /= 255;
  72163. }
  72164. // Handle Gamma space textures.
  72165. if (cubeInfo.gammaSpace) {
  72166. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  72167. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  72168. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  72169. }
  72170. var color = new BABYLON.Color3(r, g, b);
  72171. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  72172. totalSolidAngle += deltaSolidAngle;
  72173. u += du;
  72174. }
  72175. v += dv;
  72176. }
  72177. }
  72178. // Solid angle for entire sphere is 4*pi
  72179. var sphereSolidAngle = 4.0 * Math.PI;
  72180. // Adjust the solid angle to allow for how many faces we processed.
  72181. var facesProcessed = 6.0;
  72182. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  72183. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  72184. // This is needed because the numerical integration over the cube uses a
  72185. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  72186. // and also to compensate for accumulative error due to float precision in the summation.
  72187. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  72188. sphericalHarmonics.scale(correctionFactor);
  72189. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  72190. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  72191. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  72192. };
  72193. CubeMapToSphericalPolynomialTools.FileFaces = [
  72194. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  72195. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  72196. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  72197. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  72198. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  72199. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  72200. ];
  72201. return CubeMapToSphericalPolynomialTools;
  72202. }());
  72203. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  72204. })(BABYLON || (BABYLON = {}));
  72205. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  72206. var BABYLON;
  72207. (function (BABYLON) {
  72208. /**
  72209. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  72210. */
  72211. var PanoramaToCubeMapTools = /** @class */ (function () {
  72212. function PanoramaToCubeMapTools() {
  72213. }
  72214. /**
  72215. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  72216. *
  72217. * @param float32Array The source data.
  72218. * @param inputWidth The width of the input panorama.
  72219. * @param inputhHeight The height of the input panorama.
  72220. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72221. * @return The cubemap data
  72222. */
  72223. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72224. if (!float32Array) {
  72225. throw "ConvertPanoramaToCubemap: input cannot be null";
  72226. }
  72227. if (float32Array.length != inputWidth * inputHeight * 3) {
  72228. throw "ConvertPanoramaToCubemap: input size is wrong";
  72229. }
  72230. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72231. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72232. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72233. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72234. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72235. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72236. return {
  72237. front: textureFront,
  72238. back: textureBack,
  72239. left: textureLeft,
  72240. right: textureRight,
  72241. up: textureUp,
  72242. down: textureDown,
  72243. size: size,
  72244. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72245. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72246. gammaSpace: false,
  72247. };
  72248. };
  72249. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72250. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72251. var textureArray = new Float32Array(buffer);
  72252. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72253. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72254. var dy = 1 / texSize;
  72255. var fy = 0;
  72256. for (var y = 0; y < texSize; y++) {
  72257. var xv1 = faceData[0];
  72258. var xv2 = faceData[2];
  72259. for (var x = 0; x < texSize; x++) {
  72260. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72261. v.normalize();
  72262. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72263. // 3 channels per pixels
  72264. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72265. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72266. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72267. xv1 = xv1.add(rotDX1);
  72268. xv2 = xv2.add(rotDX2);
  72269. }
  72270. fy += dy;
  72271. }
  72272. return textureArray;
  72273. };
  72274. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72275. var theta = Math.atan2(vDir.z, vDir.x);
  72276. var phi = Math.acos(vDir.y);
  72277. while (theta < -Math.PI)
  72278. theta += 2 * Math.PI;
  72279. while (theta > Math.PI)
  72280. theta -= 2 * Math.PI;
  72281. var dx = theta / Math.PI;
  72282. var dy = phi / Math.PI;
  72283. // recenter.
  72284. dx = dx * 0.5 + 0.5;
  72285. var px = Math.round(dx * inputWidth);
  72286. if (px < 0)
  72287. px = 0;
  72288. else if (px >= inputWidth)
  72289. px = inputWidth - 1;
  72290. var py = Math.round(dy * inputHeight);
  72291. if (py < 0)
  72292. py = 0;
  72293. else if (py >= inputHeight)
  72294. py = inputHeight - 1;
  72295. var inputY = (inputHeight - py - 1);
  72296. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72297. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72298. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72299. return {
  72300. r: r,
  72301. g: g,
  72302. b: b
  72303. };
  72304. };
  72305. PanoramaToCubeMapTools.FACE_FRONT = [
  72306. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72307. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72308. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72309. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72310. ];
  72311. PanoramaToCubeMapTools.FACE_BACK = [
  72312. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72313. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72314. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72315. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72316. ];
  72317. PanoramaToCubeMapTools.FACE_RIGHT = [
  72318. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72319. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72320. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72321. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72322. ];
  72323. PanoramaToCubeMapTools.FACE_LEFT = [
  72324. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72325. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72326. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72327. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72328. ];
  72329. PanoramaToCubeMapTools.FACE_DOWN = [
  72330. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72331. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72332. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72333. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72334. ];
  72335. PanoramaToCubeMapTools.FACE_UP = [
  72336. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72337. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72338. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72339. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72340. ];
  72341. return PanoramaToCubeMapTools;
  72342. }());
  72343. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72344. })(BABYLON || (BABYLON = {}));
  72345. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72346. var BABYLON;
  72347. (function (BABYLON) {
  72348. ;
  72349. /**
  72350. * This groups tools to convert HDR texture to native colors array.
  72351. */
  72352. var HDRTools = /** @class */ (function () {
  72353. function HDRTools() {
  72354. }
  72355. HDRTools.Ldexp = function (mantissa, exponent) {
  72356. if (exponent > 1023) {
  72357. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72358. }
  72359. if (exponent < -1074) {
  72360. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72361. }
  72362. return mantissa * Math.pow(2, exponent);
  72363. };
  72364. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72365. if (exponent > 0) {
  72366. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72367. float32array[index + 0] = red * exponent;
  72368. float32array[index + 1] = green * exponent;
  72369. float32array[index + 2] = blue * exponent;
  72370. }
  72371. else {
  72372. float32array[index + 0] = 0;
  72373. float32array[index + 1] = 0;
  72374. float32array[index + 2] = 0;
  72375. }
  72376. };
  72377. HDRTools.readStringLine = function (uint8array, startIndex) {
  72378. var line = "";
  72379. var character = "";
  72380. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72381. character = String.fromCharCode(uint8array[i]);
  72382. if (character == "\n") {
  72383. break;
  72384. }
  72385. line += character;
  72386. }
  72387. return line;
  72388. };
  72389. /**
  72390. * Reads header information from an RGBE texture stored in a native array.
  72391. * More information on this format are available here:
  72392. * https://en.wikipedia.org/wiki/RGBE_image_format
  72393. *
  72394. * @param uint8array The binary file stored in native array.
  72395. * @return The header information.
  72396. */
  72397. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72398. var height = 0;
  72399. var width = 0;
  72400. var line = this.readStringLine(uint8array, 0);
  72401. if (line[0] != '#' || line[1] != '?') {
  72402. throw "Bad HDR Format.";
  72403. }
  72404. var endOfHeader = false;
  72405. var findFormat = false;
  72406. var lineIndex = 0;
  72407. do {
  72408. lineIndex += (line.length + 1);
  72409. line = this.readStringLine(uint8array, lineIndex);
  72410. if (line == "FORMAT=32-bit_rle_rgbe") {
  72411. findFormat = true;
  72412. }
  72413. else if (line.length == 0) {
  72414. endOfHeader = true;
  72415. }
  72416. } while (!endOfHeader);
  72417. if (!findFormat) {
  72418. throw "HDR Bad header format, unsupported FORMAT";
  72419. }
  72420. lineIndex += (line.length + 1);
  72421. line = this.readStringLine(uint8array, lineIndex);
  72422. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72423. var match = sizeRegexp.exec(line);
  72424. // TODO. Support +Y and -X if needed.
  72425. if (!match || match.length < 3) {
  72426. throw "HDR Bad header format, no size";
  72427. }
  72428. width = parseInt(match[2]);
  72429. height = parseInt(match[1]);
  72430. if (width < 8 || width > 0x7fff) {
  72431. throw "HDR Bad header format, unsupported size";
  72432. }
  72433. lineIndex += (line.length + 1);
  72434. return {
  72435. height: height,
  72436. width: width,
  72437. dataPosition: lineIndex
  72438. };
  72439. };
  72440. /**
  72441. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72442. * This RGBE texture needs to store the information as a panorama.
  72443. *
  72444. * More information on this format are available here:
  72445. * https://en.wikipedia.org/wiki/RGBE_image_format
  72446. *
  72447. * @param buffer The binary file stored in an array buffer.
  72448. * @param size The expected size of the extracted cubemap.
  72449. * @return The Cube Map information.
  72450. */
  72451. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72452. var uint8array = new Uint8Array(buffer);
  72453. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72454. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72455. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72456. return cubeMapData;
  72457. };
  72458. /**
  72459. * Returns the pixels data extracted from an RGBE texture.
  72460. * This pixels will be stored left to right up to down in the R G B order in one array.
  72461. *
  72462. * More information on this format are available here:
  72463. * https://en.wikipedia.org/wiki/RGBE_image_format
  72464. *
  72465. * @param uint8array The binary file stored in an array buffer.
  72466. * @param hdrInfo The header information of the file.
  72467. * @return The pixels data in RGB right to left up to down order.
  72468. */
  72469. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72470. // Keep for multi format supports.
  72471. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72472. };
  72473. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72474. var num_scanlines = hdrInfo.height;
  72475. var scanline_width = hdrInfo.width;
  72476. var a, b, c, d, count;
  72477. var dataIndex = hdrInfo.dataPosition;
  72478. var index = 0, endIndex = 0, i = 0;
  72479. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72480. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72481. // 3 channels of 4 bytes per pixel in float.
  72482. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72483. var resultArray = new Float32Array(resultBuffer);
  72484. // read in each successive scanline
  72485. while (num_scanlines > 0) {
  72486. a = uint8array[dataIndex++];
  72487. b = uint8array[dataIndex++];
  72488. c = uint8array[dataIndex++];
  72489. d = uint8array[dataIndex++];
  72490. if (a != 2 || b != 2 || (c & 0x80)) {
  72491. // this file is not run length encoded
  72492. throw "HDR Bad header format, not RLE";
  72493. }
  72494. if (((c << 8) | d) != scanline_width) {
  72495. throw "HDR Bad header format, wrong scan line width";
  72496. }
  72497. index = 0;
  72498. // read each of the four channels for the scanline into the buffer
  72499. for (i = 0; i < 4; i++) {
  72500. endIndex = (i + 1) * scanline_width;
  72501. while (index < endIndex) {
  72502. a = uint8array[dataIndex++];
  72503. b = uint8array[dataIndex++];
  72504. if (a > 128) {
  72505. // a run of the same value
  72506. count = a - 128;
  72507. if ((count == 0) || (count > endIndex - index)) {
  72508. throw "HDR Bad Format, bad scanline data (run)";
  72509. }
  72510. while (count-- > 0) {
  72511. scanLineArray[index++] = b;
  72512. }
  72513. }
  72514. else {
  72515. // a non-run
  72516. count = a;
  72517. if ((count == 0) || (count > endIndex - index)) {
  72518. throw "HDR Bad Format, bad scanline data (non-run)";
  72519. }
  72520. scanLineArray[index++] = b;
  72521. if (--count > 0) {
  72522. for (var j = 0; j < count; j++) {
  72523. scanLineArray[index++] = uint8array[dataIndex++];
  72524. }
  72525. }
  72526. }
  72527. }
  72528. }
  72529. // now convert data from buffer into floats
  72530. for (i = 0; i < scanline_width; i++) {
  72531. a = scanLineArray[i];
  72532. b = scanLineArray[i + scanline_width];
  72533. c = scanLineArray[i + 2 * scanline_width];
  72534. d = scanLineArray[i + 3 * scanline_width];
  72535. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72536. }
  72537. num_scanlines--;
  72538. }
  72539. return resultArray;
  72540. };
  72541. return HDRTools;
  72542. }());
  72543. BABYLON.HDRTools = HDRTools;
  72544. })(BABYLON || (BABYLON = {}));
  72545. //# sourceMappingURL=babylon.hdr.js.map
  72546. var BABYLON;
  72547. (function (BABYLON) {
  72548. /**
  72549. * This represents a texture coming from an HDR input.
  72550. *
  72551. * The only supported format is currently panorama picture stored in RGBE format.
  72552. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72553. */
  72554. var HDRCubeTexture = /** @class */ (function (_super) {
  72555. __extends(HDRCubeTexture, _super);
  72556. /**
  72557. * Instantiates an HDRTexture from the following parameters.
  72558. *
  72559. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72560. * @param scene The scene the texture will be used in
  72561. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  72562. * @param noMipmap Forces to not generate the mipmap if true
  72563. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72564. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  72565. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72566. */
  72567. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72568. if (noMipmap === void 0) { noMipmap = false; }
  72569. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72570. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72571. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72572. if (onLoad === void 0) { onLoad = null; }
  72573. if (onError === void 0) { onError = null; }
  72574. var _this = _super.call(this, scene) || this;
  72575. _this._useInGammaSpace = false;
  72576. _this._generateHarmonics = true;
  72577. _this._isBABYLONPreprocessed = false;
  72578. _this._onLoad = null;
  72579. _this._onError = null;
  72580. /**
  72581. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72582. */
  72583. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72584. /**
  72585. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72586. * This is usefull at run time to apply the good shader.
  72587. */
  72588. _this.isPMREM = false;
  72589. _this._isBlocking = true;
  72590. /**
  72591. * Gets or sets the center of the bounding box associated with the cube texture
  72592. * It must define where the camera used to render the texture was set
  72593. */
  72594. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72595. if (!url) {
  72596. return _this;
  72597. }
  72598. _this.name = url;
  72599. _this.url = url;
  72600. _this.hasAlpha = false;
  72601. _this.isCube = true;
  72602. _this._textureMatrix = BABYLON.Matrix.Identity();
  72603. _this._onLoad = onLoad;
  72604. _this._onError = onError;
  72605. _this.gammaSpace = false;
  72606. var caps = scene.getEngine().getCaps();
  72607. if (size) {
  72608. _this._isBABYLONPreprocessed = false;
  72609. _this._noMipmap = noMipmap;
  72610. _this._size = size;
  72611. _this._useInGammaSpace = useInGammaSpace;
  72612. _this._usePMREMGenerator = usePMREMGenerator &&
  72613. caps.textureLOD &&
  72614. caps.textureFloat &&
  72615. !_this._useInGammaSpace;
  72616. }
  72617. else {
  72618. _this._isBABYLONPreprocessed = true;
  72619. _this._noMipmap = false;
  72620. _this._useInGammaSpace = false;
  72621. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72622. !_this._useInGammaSpace;
  72623. }
  72624. _this.isPMREM = _this._usePMREMGenerator;
  72625. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72626. if (!_this._texture) {
  72627. if (!scene.useDelayedTextureLoading) {
  72628. _this.loadTexture();
  72629. }
  72630. else {
  72631. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72632. }
  72633. }
  72634. return _this;
  72635. }
  72636. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72637. /**
  72638. * Gets wether or not the texture is blocking during loading.
  72639. */
  72640. get: function () {
  72641. return this._isBlocking;
  72642. },
  72643. /**
  72644. * Sets wether or not the texture is blocking during loading.
  72645. */
  72646. set: function (value) {
  72647. this._isBlocking = value;
  72648. },
  72649. enumerable: true,
  72650. configurable: true
  72651. });
  72652. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72653. get: function () {
  72654. return this._boundingBoxSize;
  72655. },
  72656. /**
  72657. * Gets or sets the size of the bounding box associated with the cube texture
  72658. * When defined, the cubemap will switch to local mode
  72659. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72660. * @example https://www.babylonjs-playground.com/#RNASML
  72661. */
  72662. set: function (value) {
  72663. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72664. return;
  72665. }
  72666. this._boundingBoxSize = value;
  72667. var scene = this.getScene();
  72668. if (scene) {
  72669. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72670. }
  72671. },
  72672. enumerable: true,
  72673. configurable: true
  72674. });
  72675. /**
  72676. * Occurs when the file is a preprocessed .babylon.hdr file.
  72677. */
  72678. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72679. var _this = this;
  72680. var mipLevels = 0;
  72681. var floatArrayView = null;
  72682. var scene = this.getScene();
  72683. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72684. var mips = new Array();
  72685. if (!floatArrayView) {
  72686. return mips;
  72687. }
  72688. var startIndex = 30;
  72689. for (var level = 0; level < mipLevels; level++) {
  72690. mips.push([]);
  72691. // Fill each pixel of the mip level.
  72692. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72693. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72694. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72695. mips[level].push(faceData);
  72696. startIndex += faceSize;
  72697. }
  72698. }
  72699. return mips;
  72700. } : null;
  72701. var callback = function (buffer) {
  72702. var scene = _this.getScene();
  72703. if (!scene) {
  72704. return null;
  72705. }
  72706. // Create Native Array Views
  72707. var intArrayView = new Int32Array(buffer);
  72708. floatArrayView = new Float32Array(buffer);
  72709. // Fill header.
  72710. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72711. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72712. // Update Texture Information.
  72713. if (!_this._texture) {
  72714. return null;
  72715. }
  72716. _this._texture.updateSize(_this._size, _this._size);
  72717. // Fill polynomial information.
  72718. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72719. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72720. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72721. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72722. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72723. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72724. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72725. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72726. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72727. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72728. _this.sphericalPolynomial = sphericalPolynomial;
  72729. // Fill pixel data.
  72730. mipLevels = intArrayView[29]; // Number of mip levels.
  72731. var startIndex = 30;
  72732. var data = [];
  72733. var faceSize = Math.pow(_this._size, 2) * 3;
  72734. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72735. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72736. startIndex += faceSize;
  72737. }
  72738. var results = [];
  72739. var byteArray = null;
  72740. // Push each faces.
  72741. for (var k = 0; k < 6; k++) {
  72742. var dataFace = null;
  72743. // To be deprecated.
  72744. if (version === 1) {
  72745. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72746. dataFace = data[j];
  72747. }
  72748. // If special cases.
  72749. if (!mipmapGenerator && dataFace) {
  72750. if (!scene.getEngine().getCaps().textureFloat) {
  72751. // 3 channels of 1 bytes per pixel in bytes.
  72752. var byteBuffer = new ArrayBuffer(faceSize);
  72753. byteArray = new Uint8Array(byteBuffer);
  72754. }
  72755. for (var i = 0; i < _this._size * _this._size; i++) {
  72756. // Put in gamma space if requested.
  72757. if (_this._useInGammaSpace) {
  72758. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72759. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72760. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72761. }
  72762. // Convert to int texture for fallback.
  72763. if (byteArray) {
  72764. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72765. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72766. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72767. // May use luminance instead if the result is not accurate.
  72768. var max = Math.max(Math.max(r, g), b);
  72769. if (max > 255) {
  72770. var scale = 255 / max;
  72771. r *= scale;
  72772. g *= scale;
  72773. b *= scale;
  72774. }
  72775. byteArray[(i * 3) + 0] = r;
  72776. byteArray[(i * 3) + 1] = g;
  72777. byteArray[(i * 3) + 2] = b;
  72778. }
  72779. }
  72780. }
  72781. // Fill the array accordingly.
  72782. if (byteArray) {
  72783. results.push(byteArray);
  72784. }
  72785. else {
  72786. results.push(dataFace);
  72787. }
  72788. }
  72789. return results;
  72790. };
  72791. if (scene) {
  72792. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  72793. }
  72794. };
  72795. /**
  72796. * Occurs when the file is raw .hdr file.
  72797. */
  72798. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72799. var _this = this;
  72800. var callback = function (buffer) {
  72801. var scene = _this.getScene();
  72802. if (!scene) {
  72803. return null;
  72804. }
  72805. // Extract the raw linear data.
  72806. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72807. // Generate harmonics if needed.
  72808. if (_this._generateHarmonics) {
  72809. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72810. _this.sphericalPolynomial = sphericalPolynomial;
  72811. }
  72812. var results = [];
  72813. var byteArray = null;
  72814. // Push each faces.
  72815. for (var j = 0; j < 6; j++) {
  72816. // Create uintarray fallback.
  72817. if (!scene.getEngine().getCaps().textureFloat) {
  72818. // 3 channels of 1 bytes per pixel in bytes.
  72819. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72820. byteArray = new Uint8Array(byteBuffer);
  72821. }
  72822. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72823. // If special cases.
  72824. if (_this._useInGammaSpace || byteArray) {
  72825. for (var i = 0; i < _this._size * _this._size; i++) {
  72826. // Put in gamma space if requested.
  72827. if (_this._useInGammaSpace) {
  72828. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72829. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72830. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72831. }
  72832. // Convert to int texture for fallback.
  72833. if (byteArray) {
  72834. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72835. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72836. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72837. // May use luminance instead if the result is not accurate.
  72838. var max = Math.max(Math.max(r, g), b);
  72839. if (max > 255) {
  72840. var scale = 255 / max;
  72841. r *= scale;
  72842. g *= scale;
  72843. b *= scale;
  72844. }
  72845. byteArray[(i * 3) + 0] = r;
  72846. byteArray[(i * 3) + 1] = g;
  72847. byteArray[(i * 3) + 2] = b;
  72848. }
  72849. }
  72850. }
  72851. if (byteArray) {
  72852. results.push(byteArray);
  72853. }
  72854. else {
  72855. results.push(dataFace);
  72856. }
  72857. }
  72858. return results;
  72859. };
  72860. var mipmapGenerator = null;
  72861. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72862. // if (!this._noMipmap &&
  72863. // this._usePMREMGenerator) {
  72864. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72865. // // Custom setup of the generator matching with the PBR shader values.
  72866. // var generator = new BABYLON.PMREMGenerator(data,
  72867. // this._size,
  72868. // this._size,
  72869. // 0,
  72870. // 3,
  72871. // this.getScene().getEngine().getCaps().textureFloat,
  72872. // 2048,
  72873. // 0.25,
  72874. // false,
  72875. // true);
  72876. // return generator.filterCubeMap();
  72877. // };
  72878. // }
  72879. var scene = this.getScene();
  72880. if (scene) {
  72881. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  72882. }
  72883. };
  72884. /**
  72885. * Starts the loading process of the texture.
  72886. */
  72887. HDRCubeTexture.prototype.loadTexture = function () {
  72888. if (this._isBABYLONPreprocessed) {
  72889. this.loadBabylonTexture();
  72890. }
  72891. else {
  72892. this.loadHDRTexture();
  72893. }
  72894. };
  72895. HDRCubeTexture.prototype.clone = function () {
  72896. var scene = this.getScene();
  72897. if (!scene) {
  72898. return this;
  72899. }
  72900. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72901. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72902. // Base texture
  72903. newTexture.level = this.level;
  72904. newTexture.wrapU = this.wrapU;
  72905. newTexture.wrapV = this.wrapV;
  72906. newTexture.coordinatesIndex = this.coordinatesIndex;
  72907. newTexture.coordinatesMode = this.coordinatesMode;
  72908. return newTexture;
  72909. };
  72910. // Methods
  72911. HDRCubeTexture.prototype.delayLoad = function () {
  72912. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72913. return;
  72914. }
  72915. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72916. this._texture = this._getFromCache(this.url, this._noMipmap);
  72917. if (!this._texture) {
  72918. this.loadTexture();
  72919. }
  72920. };
  72921. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72922. return this._textureMatrix;
  72923. };
  72924. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72925. this._textureMatrix = value;
  72926. };
  72927. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72928. var texture = null;
  72929. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72930. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72931. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72932. texture.name = parsedTexture.name;
  72933. texture.hasAlpha = parsedTexture.hasAlpha;
  72934. texture.level = parsedTexture.level;
  72935. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72936. texture.isBlocking = parsedTexture.isBlocking;
  72937. }
  72938. if (texture) {
  72939. if (parsedTexture.boundingBoxPosition) {
  72940. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72941. }
  72942. if (parsedTexture.boundingBoxSize) {
  72943. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72944. }
  72945. }
  72946. return texture;
  72947. };
  72948. HDRCubeTexture.prototype.serialize = function () {
  72949. if (!this.name) {
  72950. return null;
  72951. }
  72952. var serializationObject = {};
  72953. serializationObject.name = this.name;
  72954. serializationObject.hasAlpha = this.hasAlpha;
  72955. serializationObject.isCube = true;
  72956. serializationObject.level = this.level;
  72957. serializationObject.size = this._size;
  72958. serializationObject.coordinatesMode = this.coordinatesMode;
  72959. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72960. serializationObject.generateHarmonics = this._generateHarmonics;
  72961. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72962. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72963. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72964. serializationObject.noMipmap = this._noMipmap;
  72965. serializationObject.isBlocking = this._isBlocking;
  72966. return serializationObject;
  72967. };
  72968. /**
  72969. * Saves as a file the data contained in the texture in a binary format.
  72970. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72971. * as the spherical used in the lighting.
  72972. * @param url The HDR file url.
  72973. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72974. * @param onError Method called if any error happens during download.
  72975. * @return The packed binary data.
  72976. */
  72977. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72978. if (onError === void 0) { onError = null; }
  72979. var callback = function (buffer) {
  72980. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72981. // Returns a URL you can use as a href.
  72982. var objUrl = window.URL.createObjectURL(data);
  72983. // Simulates a link to it and click to dowload.
  72984. var a = document.createElement("a");
  72985. document.body.appendChild(a);
  72986. a.style.display = "none";
  72987. a.href = objUrl;
  72988. a.download = "envmap.babylon.hdr";
  72989. a.click();
  72990. };
  72991. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72992. };
  72993. /**
  72994. * Serializes the data contained in the texture in a binary format.
  72995. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72996. * as the spherical used in the lighting.
  72997. * @param url The HDR file url.
  72998. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72999. * @param onError Method called if any error happens during download.
  73000. * @return The packed binary data.
  73001. */
  73002. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  73003. if (onError === void 0) { onError = null; }
  73004. // Needs the url tho create the texture.
  73005. if (!url) {
  73006. return;
  73007. }
  73008. // Check Power of two size.
  73009. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  73010. return;
  73011. }
  73012. // Coming Back in 3.x.
  73013. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  73014. };
  73015. HDRCubeTexture._facesMapping = [
  73016. "right",
  73017. "left",
  73018. "up",
  73019. "down",
  73020. "front",
  73021. "back"
  73022. ];
  73023. return HDRCubeTexture;
  73024. }(BABYLON.BaseTexture));
  73025. BABYLON.HDRCubeTexture = HDRCubeTexture;
  73026. })(BABYLON || (BABYLON = {}));
  73027. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  73028. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  73029. // Huge respect for a such great lib.
  73030. // Earcut license:
  73031. // Copyright (c) 2016, Mapbox
  73032. //
  73033. // Permission to use, copy, modify, and/or distribute this software for any purpose
  73034. // with or without fee is hereby granted, provided that the above copyright notice
  73035. // and this permission notice appear in all copies.
  73036. //
  73037. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  73038. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  73039. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  73040. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  73041. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  73042. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  73043. // THIS SOFTWARE.
  73044. var Earcut;
  73045. (function (Earcut) {
  73046. /**
  73047. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  73048. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  73049. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  73050. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  73051. */
  73052. function earcut(data, holeIndices, dim) {
  73053. dim = dim || 2;
  73054. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  73055. if (!outerNode)
  73056. return triangles;
  73057. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  73058. if (hasHoles)
  73059. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  73060. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  73061. if (data.length > 80 * dim) {
  73062. minX = maxX = data[0];
  73063. minY = maxY = data[1];
  73064. for (var i = dim; i < outerLen; i += dim) {
  73065. x = data[i];
  73066. y = data[i + 1];
  73067. if (x < minX)
  73068. minX = x;
  73069. if (y < minY)
  73070. minY = y;
  73071. if (x > maxX)
  73072. maxX = x;
  73073. if (y > maxY)
  73074. maxY = y;
  73075. }
  73076. // minX, minY and size are later used to transform coords into integers for z-order calculation
  73077. size = Math.max(maxX - minX, maxY - minY);
  73078. }
  73079. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  73080. return triangles;
  73081. }
  73082. Earcut.earcut = earcut;
  73083. var Node = /** @class */ (function () {
  73084. function Node(i, x, y) {
  73085. this.i = i;
  73086. this.x = x;
  73087. this.y = y;
  73088. this.prev = null;
  73089. this.next = null;
  73090. this.z = null;
  73091. this.prevZ = null;
  73092. this.nextZ = null;
  73093. this.steiner = false;
  73094. }
  73095. return Node;
  73096. }());
  73097. // create a circular doubly linked list from polygon points in the specified winding order
  73098. function linkedList(data, start, end, dim, clockwise) {
  73099. var i, last = null;
  73100. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  73101. for (i = start; i < end; i += dim)
  73102. last = insertNode(i, data[i], data[i + 1], last);
  73103. }
  73104. else {
  73105. for (i = end - dim; i >= start; i -= dim)
  73106. last = insertNode(i, data[i], data[i + 1], last);
  73107. }
  73108. if (last && equals(last, last.next)) {
  73109. removeNode(last);
  73110. last = last.next;
  73111. }
  73112. return last;
  73113. }
  73114. // eliminate colinear or duplicate points
  73115. function filterPoints(start, end) {
  73116. if (!start)
  73117. return start;
  73118. if (!end)
  73119. end = start;
  73120. var p = start, again;
  73121. do {
  73122. again = false;
  73123. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  73124. removeNode(p);
  73125. p = end = p.prev;
  73126. if (p === p.next)
  73127. return undefined;
  73128. again = true;
  73129. }
  73130. else {
  73131. p = p.next;
  73132. }
  73133. } while (again || p !== end);
  73134. return end;
  73135. }
  73136. // main ear slicing loop which triangulates a polygon (given as a linked list)
  73137. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  73138. if (!ear)
  73139. return;
  73140. // interlink polygon nodes in z-order
  73141. if (!pass && size)
  73142. indexCurve(ear, minX, minY, size);
  73143. var stop = ear, prev, next;
  73144. // iterate through ears, slicing them one by one
  73145. while (ear.prev !== ear.next) {
  73146. prev = ear.prev;
  73147. next = ear.next;
  73148. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73149. // cut off the triangle
  73150. triangles.push(prev.i / dim);
  73151. triangles.push(ear.i / dim);
  73152. triangles.push(next.i / dim);
  73153. removeNode(ear);
  73154. // skipping the next vertice leads to less sliver triangles
  73155. ear = next.next;
  73156. stop = next.next;
  73157. continue;
  73158. }
  73159. ear = next;
  73160. // if we looped through the whole remaining polygon and can't find any more ears
  73161. if (ear === stop) {
  73162. // try filtering points and slicing again
  73163. if (!pass) {
  73164. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  73165. // if this didn't work, try curing all small self-intersections locally
  73166. }
  73167. else if (pass === 1) {
  73168. ear = cureLocalIntersections(ear, triangles, dim);
  73169. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  73170. // as a last resort, try splitting the remaining polygon into two
  73171. }
  73172. else if (pass === 2) {
  73173. splitEarcut(ear, triangles, dim, minX, minY, size);
  73174. }
  73175. break;
  73176. }
  73177. }
  73178. }
  73179. // check whether a polygon node forms a valid ear with adjacent nodes
  73180. function isEar(ear) {
  73181. var a = ear.prev, b = ear, c = ear.next;
  73182. if (area(a, b, c) >= 0)
  73183. return false; // reflex, can't be an ear
  73184. // now make sure we don't have other points inside the potential ear
  73185. var p = ear.next.next;
  73186. while (p !== ear.prev) {
  73187. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73188. area(p.prev, p, p.next) >= 0)
  73189. return false;
  73190. p = p.next;
  73191. }
  73192. return true;
  73193. }
  73194. function isEarHashed(ear, minX, minY, size) {
  73195. var a = ear.prev, b = ear, c = ear.next;
  73196. if (area(a, b, c) >= 0)
  73197. return false; // reflex, can't be an ear
  73198. // triangle bbox; min & max are calculated like this for speed
  73199. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  73200. // z-order range for the current triangle bbox;
  73201. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  73202. // first look for points inside the triangle in increasing z-order
  73203. var p = ear.nextZ;
  73204. while (p && p.z <= maxZ) {
  73205. if (p !== ear.prev &&
  73206. p !== ear.next &&
  73207. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73208. area(p.prev, p, p.next) >= 0)
  73209. return false;
  73210. p = p.nextZ;
  73211. }
  73212. // then look for points in decreasing z-order
  73213. p = ear.prevZ;
  73214. while (p && p.z >= minZ) {
  73215. if (p !== ear.prev &&
  73216. p !== ear.next &&
  73217. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  73218. area(p.prev, p, p.next) >= 0)
  73219. return false;
  73220. p = p.prevZ;
  73221. }
  73222. return true;
  73223. }
  73224. // go through all polygon nodes and cure small local self-intersections
  73225. function cureLocalIntersections(start, triangles, dim) {
  73226. var p = start;
  73227. do {
  73228. var a = p.prev, b = p.next.next;
  73229. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73230. triangles.push(a.i / dim);
  73231. triangles.push(p.i / dim);
  73232. triangles.push(b.i / dim);
  73233. // remove two nodes involved
  73234. removeNode(p);
  73235. removeNode(p.next);
  73236. p = start = b;
  73237. }
  73238. p = p.next;
  73239. } while (p !== start);
  73240. return p;
  73241. }
  73242. // try splitting polygon into two and triangulate them independently
  73243. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73244. // look for a valid diagonal that divides the polygon into two
  73245. var a = start;
  73246. do {
  73247. var b = a.next.next;
  73248. while (b !== a.prev) {
  73249. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73250. // split the polygon in two by the diagonal
  73251. var c = splitPolygon(a, b);
  73252. // filter colinear points around the cuts
  73253. a = filterPoints(a, a.next);
  73254. c = filterPoints(c, c.next);
  73255. // run earcut on each half
  73256. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73257. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73258. return;
  73259. }
  73260. b = b.next;
  73261. }
  73262. a = a.next;
  73263. } while (a !== start);
  73264. }
  73265. // link every hole into the outer loop, producing a single-ring polygon without holes
  73266. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73267. var queue = [], i, len, start, end, list;
  73268. for (i = 0, len = holeIndices.length; i < len; i++) {
  73269. start = holeIndices[i] * dim;
  73270. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73271. list = linkedList(data, start, end, dim, false);
  73272. if (list === list.next)
  73273. list.steiner = true;
  73274. queue.push(getLeftmost(list));
  73275. }
  73276. queue.sort(compareX);
  73277. // process holes from left to right
  73278. for (i = 0; i < queue.length; i++) {
  73279. eliminateHole(queue[i], outerNode);
  73280. outerNode = filterPoints(outerNode, outerNode.next);
  73281. }
  73282. return outerNode;
  73283. }
  73284. function compareX(a, b) {
  73285. return a.x - b.x;
  73286. }
  73287. // find a bridge between vertices that connects hole with an outer ring and and link it
  73288. function eliminateHole(hole, outerNode) {
  73289. outerNode = findHoleBridge(hole, outerNode);
  73290. if (outerNode) {
  73291. var b = splitPolygon(outerNode, hole);
  73292. filterPoints(b, b.next);
  73293. }
  73294. }
  73295. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73296. function findHoleBridge(hole, outerNode) {
  73297. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73298. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73299. // segment's endpoint with lesser x will be potential connection point
  73300. do {
  73301. if (hy <= p.y && hy >= p.next.y) {
  73302. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73303. if (x <= hx && x > qx) {
  73304. qx = x;
  73305. if (x === hx) {
  73306. if (hy === p.y)
  73307. return p;
  73308. if (hy === p.next.y)
  73309. return p.next;
  73310. }
  73311. m = p.x < p.next.x ? p : p.next;
  73312. }
  73313. }
  73314. p = p.next;
  73315. } while (p !== outerNode);
  73316. if (!m)
  73317. return null;
  73318. if (hx === qx)
  73319. return m.prev; // hole touches outer segment; pick lower endpoint
  73320. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73321. // if there are no points found, we have a valid connection;
  73322. // otherwise choose the point of the minimum angle with the ray as connection point
  73323. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73324. p = m.next;
  73325. while (p !== stop) {
  73326. if (hx >= p.x &&
  73327. p.x >= mx &&
  73328. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73329. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73330. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73331. m = p;
  73332. tanMin = tan;
  73333. }
  73334. }
  73335. p = p.next;
  73336. }
  73337. return m;
  73338. }
  73339. // interlink polygon nodes in z-order
  73340. function indexCurve(start, minX, minY, size) {
  73341. var p = start;
  73342. do {
  73343. if (p.z === null)
  73344. p.z = zOrder(p.x, p.y, minX, minY, size);
  73345. p.prevZ = p.prev;
  73346. p.nextZ = p.next;
  73347. p = p.next;
  73348. } while (p !== start);
  73349. p.prevZ.nextZ = null;
  73350. p.prevZ = null;
  73351. sortLinked(p);
  73352. }
  73353. // Simon Tatham's linked list merge sort algorithm
  73354. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73355. function sortLinked(list) {
  73356. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73357. do {
  73358. p = list;
  73359. list = null;
  73360. tail = null;
  73361. numMerges = 0;
  73362. while (p) {
  73363. numMerges++;
  73364. q = p;
  73365. pSize = 0;
  73366. for (i = 0; i < inSize; i++) {
  73367. pSize++;
  73368. q = q.nextZ;
  73369. if (!q)
  73370. break;
  73371. }
  73372. qSize = inSize;
  73373. while (pSize > 0 || (qSize > 0 && q)) {
  73374. if (pSize === 0) {
  73375. e = q;
  73376. q = q.nextZ;
  73377. qSize--;
  73378. }
  73379. else if (qSize === 0 || !q) {
  73380. e = p;
  73381. p = p.nextZ;
  73382. pSize--;
  73383. }
  73384. else if (p.z <= q.z) {
  73385. e = p;
  73386. p = p.nextZ;
  73387. pSize--;
  73388. }
  73389. else {
  73390. e = q;
  73391. q = q.nextZ;
  73392. qSize--;
  73393. }
  73394. if (tail)
  73395. tail.nextZ = e;
  73396. else
  73397. list = e;
  73398. e.prevZ = tail;
  73399. tail = e;
  73400. }
  73401. p = q;
  73402. }
  73403. tail.nextZ = null;
  73404. inSize *= 2;
  73405. } while (numMerges > 1);
  73406. return list;
  73407. }
  73408. // z-order of a point given coords and size of the data bounding box
  73409. function zOrder(x, y, minX, minY, size) {
  73410. // coords are transformed into non-negative 15-bit integer range
  73411. x = 32767 * (x - minX) / size;
  73412. y = 32767 * (y - minY) / size;
  73413. x = (x | (x << 8)) & 0x00FF00FF;
  73414. x = (x | (x << 4)) & 0x0F0F0F0F;
  73415. x = (x | (x << 2)) & 0x33333333;
  73416. x = (x | (x << 1)) & 0x55555555;
  73417. y = (y | (y << 8)) & 0x00FF00FF;
  73418. y = (y | (y << 4)) & 0x0F0F0F0F;
  73419. y = (y | (y << 2)) & 0x33333333;
  73420. y = (y | (y << 1)) & 0x55555555;
  73421. return x | (y << 1);
  73422. }
  73423. // find the leftmost node of a polygon ring
  73424. function getLeftmost(start) {
  73425. var p = start, leftmost = start;
  73426. do {
  73427. if (p.x < leftmost.x)
  73428. leftmost = p;
  73429. p = p.next;
  73430. } while (p !== start);
  73431. return leftmost;
  73432. }
  73433. // check if a point lies within a convex triangle
  73434. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73435. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73436. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73437. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73438. }
  73439. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73440. function isValidDiagonal(a, b) {
  73441. return a.next.i !== b.i &&
  73442. a.prev.i !== b.i &&
  73443. !intersectsPolygon(a, b) &&
  73444. locallyInside(a, b) &&
  73445. locallyInside(b, a) &&
  73446. middleInside(a, b);
  73447. }
  73448. // signed area of a triangle
  73449. function area(p, q, r) {
  73450. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73451. }
  73452. // check if two points are equal
  73453. function equals(p1, p2) {
  73454. return p1.x === p2.x && p1.y === p2.y;
  73455. }
  73456. // check if two segments intersect
  73457. function intersects(p1, q1, p2, q2) {
  73458. if ((equals(p1, q1) && equals(p2, q2)) ||
  73459. (equals(p1, q2) && equals(p2, q1)))
  73460. return true;
  73461. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73462. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73463. }
  73464. // check if a polygon diagonal intersects any polygon segments
  73465. function intersectsPolygon(a, b) {
  73466. var p = a;
  73467. do {
  73468. if (p.i !== a.i &&
  73469. p.next.i !== a.i &&
  73470. p.i !== b.i &&
  73471. p.next.i !== b.i &&
  73472. intersects(p, p.next, a, b))
  73473. return true;
  73474. p = p.next;
  73475. } while (p !== a);
  73476. return false;
  73477. }
  73478. // check if a polygon diagonal is locally inside the polygon
  73479. function locallyInside(a, b) {
  73480. return area(a.prev, a, a.next) < 0
  73481. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73482. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73483. }
  73484. // check if the middle point of a polygon diagonal is inside the polygon
  73485. function middleInside(a, b) {
  73486. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73487. do {
  73488. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73489. inside = !inside;
  73490. p = p.next;
  73491. } while (p !== a);
  73492. return inside;
  73493. }
  73494. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73495. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73496. function splitPolygon(a, b) {
  73497. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  73498. a.next = b;
  73499. b.prev = a;
  73500. a2.next = an;
  73501. an.prev = a2;
  73502. b2.next = a2;
  73503. a2.prev = b2;
  73504. bp.next = b2;
  73505. b2.prev = bp;
  73506. return b2;
  73507. }
  73508. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73509. function insertNode(i, x, y, last) {
  73510. var p = new Node(i, x, y);
  73511. if (!last) {
  73512. p.prev = p;
  73513. p.next = p;
  73514. }
  73515. else {
  73516. p.next = last.next;
  73517. p.prev = last;
  73518. last.next.prev = p;
  73519. last.next = p;
  73520. }
  73521. return p;
  73522. }
  73523. function removeNode(p) {
  73524. p.next.prev = p.prev;
  73525. p.prev.next = p.next;
  73526. if (p.prevZ)
  73527. p.prevZ.nextZ = p.nextZ;
  73528. if (p.nextZ)
  73529. p.nextZ.prevZ = p.prevZ;
  73530. }
  73531. /**
  73532. * return a percentage difference between the polygon area and its triangulation area;
  73533. * used to verify correctness of triangulation
  73534. */
  73535. function deviation(data, holeIndices, dim, triangles) {
  73536. var hasHoles = holeIndices && holeIndices.length;
  73537. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73538. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73539. if (hasHoles) {
  73540. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73541. var start = holeIndices[i] * dim;
  73542. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73543. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73544. }
  73545. }
  73546. var trianglesArea = 0;
  73547. for (i = 0; i < triangles.length; i += 3) {
  73548. var a = triangles[i] * dim;
  73549. var b = triangles[i + 1] * dim;
  73550. var c = triangles[i + 2] * dim;
  73551. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73552. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73553. }
  73554. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73555. }
  73556. Earcut.deviation = deviation;
  73557. ;
  73558. function signedArea(data, start, end, dim) {
  73559. var sum = 0;
  73560. for (var i = start, j = end - dim; i < end; i += dim) {
  73561. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73562. j = i;
  73563. }
  73564. return sum;
  73565. }
  73566. /**
  73567. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73568. */
  73569. function flatten(data) {
  73570. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73571. for (var i = 0; i < data.length; i++) {
  73572. for (var j = 0; j < data[i].length; j++) {
  73573. for (var d = 0; d < dim; d++)
  73574. result.vertices.push(data[i][j][d]);
  73575. }
  73576. if (i > 0) {
  73577. holeIndex += data[i - 1].length;
  73578. result.holes.push(holeIndex);
  73579. }
  73580. }
  73581. return result;
  73582. }
  73583. Earcut.flatten = flatten;
  73584. ;
  73585. })(Earcut || (Earcut = {}));
  73586. //# sourceMappingURL=babylon.earcut.js.map
  73587. var BABYLON;
  73588. (function (BABYLON) {
  73589. var IndexedVector2 = /** @class */ (function (_super) {
  73590. __extends(IndexedVector2, _super);
  73591. function IndexedVector2(original, index) {
  73592. var _this = _super.call(this, original.x, original.y) || this;
  73593. _this.index = index;
  73594. return _this;
  73595. }
  73596. return IndexedVector2;
  73597. }(BABYLON.Vector2));
  73598. var PolygonPoints = /** @class */ (function () {
  73599. function PolygonPoints() {
  73600. this.elements = new Array();
  73601. }
  73602. PolygonPoints.prototype.add = function (originalPoints) {
  73603. var _this = this;
  73604. var result = new Array();
  73605. originalPoints.forEach(function (point) {
  73606. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73607. var newPoint = new IndexedVector2(point, _this.elements.length);
  73608. result.push(newPoint);
  73609. _this.elements.push(newPoint);
  73610. }
  73611. });
  73612. return result;
  73613. };
  73614. PolygonPoints.prototype.computeBounds = function () {
  73615. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73616. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73617. this.elements.forEach(function (point) {
  73618. // x
  73619. if (point.x < lmin.x) {
  73620. lmin.x = point.x;
  73621. }
  73622. else if (point.x > lmax.x) {
  73623. lmax.x = point.x;
  73624. }
  73625. // y
  73626. if (point.y < lmin.y) {
  73627. lmin.y = point.y;
  73628. }
  73629. else if (point.y > lmax.y) {
  73630. lmax.y = point.y;
  73631. }
  73632. });
  73633. return {
  73634. min: lmin,
  73635. max: lmax,
  73636. width: lmax.x - lmin.x,
  73637. height: lmax.y - lmin.y
  73638. };
  73639. };
  73640. return PolygonPoints;
  73641. }());
  73642. var Polygon = /** @class */ (function () {
  73643. function Polygon() {
  73644. }
  73645. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73646. return [
  73647. new BABYLON.Vector2(xmin, ymin),
  73648. new BABYLON.Vector2(xmax, ymin),
  73649. new BABYLON.Vector2(xmax, ymax),
  73650. new BABYLON.Vector2(xmin, ymax)
  73651. ];
  73652. };
  73653. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73654. if (cx === void 0) { cx = 0; }
  73655. if (cy === void 0) { cy = 0; }
  73656. if (numberOfSides === void 0) { numberOfSides = 32; }
  73657. var result = new Array();
  73658. var angle = 0;
  73659. var increment = (Math.PI * 2) / numberOfSides;
  73660. for (var i = 0; i < numberOfSides; i++) {
  73661. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73662. angle -= increment;
  73663. }
  73664. return result;
  73665. };
  73666. Polygon.Parse = function (input) {
  73667. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73668. var i, result = [];
  73669. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73670. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73671. }
  73672. return result;
  73673. };
  73674. Polygon.StartingAt = function (x, y) {
  73675. return BABYLON.Path2.StartingAt(x, y);
  73676. };
  73677. return Polygon;
  73678. }());
  73679. BABYLON.Polygon = Polygon;
  73680. var PolygonMeshBuilder = /** @class */ (function () {
  73681. function PolygonMeshBuilder(name, contours, scene) {
  73682. this._points = new PolygonPoints();
  73683. this._outlinepoints = new PolygonPoints();
  73684. this._holes = new Array();
  73685. this._epoints = new Array();
  73686. this._eholes = new Array();
  73687. this._name = name;
  73688. this._scene = scene;
  73689. var points;
  73690. if (contours instanceof BABYLON.Path2) {
  73691. points = contours.getPoints();
  73692. }
  73693. else {
  73694. points = contours;
  73695. }
  73696. this._addToepoint(points);
  73697. this._points.add(points);
  73698. this._outlinepoints.add(points);
  73699. }
  73700. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73701. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73702. var p = points_1[_i];
  73703. this._epoints.push(p.x, p.y);
  73704. }
  73705. };
  73706. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73707. this._points.add(hole);
  73708. var holepoints = new PolygonPoints();
  73709. holepoints.add(hole);
  73710. this._holes.push(holepoints);
  73711. this._eholes.push(this._epoints.length / 2);
  73712. this._addToepoint(hole);
  73713. return this;
  73714. };
  73715. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73716. var _this = this;
  73717. if (updatable === void 0) { updatable = false; }
  73718. if (depth === void 0) { depth = 0; }
  73719. var result = new BABYLON.Mesh(this._name, this._scene);
  73720. var normals = new Array();
  73721. var positions = new Array();
  73722. var uvs = new Array();
  73723. var bounds = this._points.computeBounds();
  73724. this._points.elements.forEach(function (p) {
  73725. normals.push(0, 1.0, 0);
  73726. positions.push(p.x, 0, p.y);
  73727. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73728. });
  73729. var indices = new Array();
  73730. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73731. for (var i = 0; i < res.length; i++) {
  73732. indices.push(res[i]);
  73733. }
  73734. if (depth > 0) {
  73735. var positionscount = (positions.length / 3); //get the current pointcount
  73736. this._points.elements.forEach(function (p) {
  73737. normals.push(0, -1.0, 0);
  73738. positions.push(p.x, -depth, p.y);
  73739. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73740. });
  73741. var totalCount = indices.length;
  73742. for (var i = 0; i < totalCount; i += 3) {
  73743. var i0 = indices[i + 0];
  73744. var i1 = indices[i + 1];
  73745. var i2 = indices[i + 2];
  73746. indices.push(i2 + positionscount);
  73747. indices.push(i1 + positionscount);
  73748. indices.push(i0 + positionscount);
  73749. }
  73750. //Add the sides
  73751. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73752. this._holes.forEach(function (hole) {
  73753. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73754. });
  73755. }
  73756. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73757. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73758. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73759. result.setIndices(indices);
  73760. return result;
  73761. };
  73762. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73763. var StartIndex = positions.length / 3;
  73764. var ulength = 0;
  73765. for (var i = 0; i < points.elements.length; i++) {
  73766. var p = points.elements[i];
  73767. var p1;
  73768. if ((i + 1) > points.elements.length - 1) {
  73769. p1 = points.elements[0];
  73770. }
  73771. else {
  73772. p1 = points.elements[i + 1];
  73773. }
  73774. positions.push(p.x, 0, p.y);
  73775. positions.push(p.x, -depth, p.y);
  73776. positions.push(p1.x, 0, p1.y);
  73777. positions.push(p1.x, -depth, p1.y);
  73778. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73779. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73780. var v3 = v2.subtract(v1);
  73781. var v4 = new BABYLON.Vector3(0, 1, 0);
  73782. var vn = BABYLON.Vector3.Cross(v3, v4);
  73783. vn = vn.normalize();
  73784. uvs.push(ulength / bounds.width, 0);
  73785. uvs.push(ulength / bounds.width, 1);
  73786. ulength += v3.length();
  73787. uvs.push((ulength / bounds.width), 0);
  73788. uvs.push((ulength / bounds.width), 1);
  73789. if (!flip) {
  73790. normals.push(-vn.x, -vn.y, -vn.z);
  73791. normals.push(-vn.x, -vn.y, -vn.z);
  73792. normals.push(-vn.x, -vn.y, -vn.z);
  73793. normals.push(-vn.x, -vn.y, -vn.z);
  73794. indices.push(StartIndex);
  73795. indices.push(StartIndex + 1);
  73796. indices.push(StartIndex + 2);
  73797. indices.push(StartIndex + 1);
  73798. indices.push(StartIndex + 3);
  73799. indices.push(StartIndex + 2);
  73800. }
  73801. else {
  73802. normals.push(vn.x, vn.y, vn.z);
  73803. normals.push(vn.x, vn.y, vn.z);
  73804. normals.push(vn.x, vn.y, vn.z);
  73805. normals.push(vn.x, vn.y, vn.z);
  73806. indices.push(StartIndex);
  73807. indices.push(StartIndex + 2);
  73808. indices.push(StartIndex + 1);
  73809. indices.push(StartIndex + 1);
  73810. indices.push(StartIndex + 2);
  73811. indices.push(StartIndex + 3);
  73812. }
  73813. StartIndex += 4;
  73814. }
  73815. ;
  73816. };
  73817. return PolygonMeshBuilder;
  73818. }());
  73819. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73820. })(BABYLON || (BABYLON = {}));
  73821. //# sourceMappingURL=babylon.polygonMesh.js.map
  73822. var BABYLON;
  73823. (function (BABYLON) {
  73824. // Unique ID when we import meshes from Babylon to CSG
  73825. var currentCSGMeshId = 0;
  73826. // # class Vertex
  73827. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73828. // one to provide additional features like texture coordinates and vertex
  73829. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73830. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73831. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73832. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73833. // is not used anywhere else.
  73834. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73835. var Vertex = /** @class */ (function () {
  73836. function Vertex(pos, normal, uv) {
  73837. this.pos = pos;
  73838. this.normal = normal;
  73839. this.uv = uv;
  73840. }
  73841. Vertex.prototype.clone = function () {
  73842. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73843. };
  73844. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73845. // orientation of a polygon is flipped.
  73846. Vertex.prototype.flip = function () {
  73847. this.normal = this.normal.scale(-1);
  73848. };
  73849. // Create a new vertex between this vertex and `other` by linearly
  73850. // interpolating all properties using a parameter of `t`. Subclasses should
  73851. // override this to interpolate additional properties.
  73852. Vertex.prototype.interpolate = function (other, t) {
  73853. 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));
  73854. };
  73855. return Vertex;
  73856. }());
  73857. // # class Plane
  73858. // Represents a plane in 3D space.
  73859. var Plane = /** @class */ (function () {
  73860. function Plane(normal, w) {
  73861. this.normal = normal;
  73862. this.w = w;
  73863. }
  73864. Plane.FromPoints = function (a, b, c) {
  73865. var v0 = c.subtract(a);
  73866. var v1 = b.subtract(a);
  73867. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73868. return null;
  73869. }
  73870. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73871. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73872. };
  73873. Plane.prototype.clone = function () {
  73874. return new Plane(this.normal.clone(), this.w);
  73875. };
  73876. Plane.prototype.flip = function () {
  73877. this.normal.scaleInPlace(-1);
  73878. this.w = -this.w;
  73879. };
  73880. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73881. // fragments in the appropriate lists. Coplanar polygons go into either
  73882. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73883. // respect to this plane. Polygons in front or in back of this plane go into
  73884. // either `front` or `back`.
  73885. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73886. var COPLANAR = 0;
  73887. var FRONT = 1;
  73888. var BACK = 2;
  73889. var SPANNING = 3;
  73890. // Classify each point as well as the entire polygon into one of the above
  73891. // four classes.
  73892. var polygonType = 0;
  73893. var types = [];
  73894. var i;
  73895. var t;
  73896. for (i = 0; i < polygon.vertices.length; i++) {
  73897. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73898. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73899. polygonType |= type;
  73900. types.push(type);
  73901. }
  73902. // Put the polygon in the correct list, splitting it when necessary.
  73903. switch (polygonType) {
  73904. case COPLANAR:
  73905. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73906. break;
  73907. case FRONT:
  73908. front.push(polygon);
  73909. break;
  73910. case BACK:
  73911. back.push(polygon);
  73912. break;
  73913. case SPANNING:
  73914. var f = [], b = [];
  73915. for (i = 0; i < polygon.vertices.length; i++) {
  73916. var j = (i + 1) % polygon.vertices.length;
  73917. var ti = types[i], tj = types[j];
  73918. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73919. if (ti !== BACK)
  73920. f.push(vi);
  73921. if (ti !== FRONT)
  73922. b.push(ti !== BACK ? vi.clone() : vi);
  73923. if ((ti | tj) === SPANNING) {
  73924. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73925. var v = vi.interpolate(vj, t);
  73926. f.push(v);
  73927. b.push(v.clone());
  73928. }
  73929. }
  73930. var poly;
  73931. if (f.length >= 3) {
  73932. poly = new Polygon(f, polygon.shared);
  73933. if (poly.plane)
  73934. front.push(poly);
  73935. }
  73936. if (b.length >= 3) {
  73937. poly = new Polygon(b, polygon.shared);
  73938. if (poly.plane)
  73939. back.push(poly);
  73940. }
  73941. break;
  73942. }
  73943. };
  73944. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73945. // point is on the plane.
  73946. Plane.EPSILON = 1e-5;
  73947. return Plane;
  73948. }());
  73949. // # class Polygon
  73950. // Represents a convex polygon. The vertices used to initialize a polygon must
  73951. // be coplanar and form a convex loop.
  73952. //
  73953. // Each convex polygon has a `shared` property, which is shared between all
  73954. // polygons that are clones of each other or were split from the same polygon.
  73955. // This can be used to define per-polygon properties (such as surface color).
  73956. var Polygon = /** @class */ (function () {
  73957. function Polygon(vertices, shared) {
  73958. this.vertices = vertices;
  73959. this.shared = shared;
  73960. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73961. }
  73962. Polygon.prototype.clone = function () {
  73963. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73964. return new Polygon(vertices, this.shared);
  73965. };
  73966. Polygon.prototype.flip = function () {
  73967. this.vertices.reverse().map(function (v) { v.flip(); });
  73968. this.plane.flip();
  73969. };
  73970. return Polygon;
  73971. }());
  73972. // # class Node
  73973. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73974. // by picking a polygon to split along. That polygon (and all other coplanar
  73975. // polygons) are added directly to that node and the other polygons are added to
  73976. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73977. // no distinction between internal and leaf nodes.
  73978. var Node = /** @class */ (function () {
  73979. function Node(polygons) {
  73980. this.plane = null;
  73981. this.front = null;
  73982. this.back = null;
  73983. this.polygons = new Array();
  73984. if (polygons) {
  73985. this.build(polygons);
  73986. }
  73987. }
  73988. Node.prototype.clone = function () {
  73989. var node = new Node();
  73990. node.plane = this.plane && this.plane.clone();
  73991. node.front = this.front && this.front.clone();
  73992. node.back = this.back && this.back.clone();
  73993. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73994. return node;
  73995. };
  73996. // Convert solid space to empty space and empty space to solid space.
  73997. Node.prototype.invert = function () {
  73998. for (var i = 0; i < this.polygons.length; i++) {
  73999. this.polygons[i].flip();
  74000. }
  74001. if (this.plane) {
  74002. this.plane.flip();
  74003. }
  74004. if (this.front) {
  74005. this.front.invert();
  74006. }
  74007. if (this.back) {
  74008. this.back.invert();
  74009. }
  74010. var temp = this.front;
  74011. this.front = this.back;
  74012. this.back = temp;
  74013. };
  74014. // Recursively remove all polygons in `polygons` that are inside this BSP
  74015. // tree.
  74016. Node.prototype.clipPolygons = function (polygons) {
  74017. if (!this.plane)
  74018. return polygons.slice();
  74019. var front = new Array(), back = new Array();
  74020. for (var i = 0; i < polygons.length; i++) {
  74021. this.plane.splitPolygon(polygons[i], front, back, front, back);
  74022. }
  74023. if (this.front) {
  74024. front = this.front.clipPolygons(front);
  74025. }
  74026. if (this.back) {
  74027. back = this.back.clipPolygons(back);
  74028. }
  74029. else {
  74030. back = [];
  74031. }
  74032. return front.concat(back);
  74033. };
  74034. // Remove all polygons in this BSP tree that are inside the other BSP tree
  74035. // `bsp`.
  74036. Node.prototype.clipTo = function (bsp) {
  74037. this.polygons = bsp.clipPolygons(this.polygons);
  74038. if (this.front)
  74039. this.front.clipTo(bsp);
  74040. if (this.back)
  74041. this.back.clipTo(bsp);
  74042. };
  74043. // Return a list of all polygons in this BSP tree.
  74044. Node.prototype.allPolygons = function () {
  74045. var polygons = this.polygons.slice();
  74046. if (this.front)
  74047. polygons = polygons.concat(this.front.allPolygons());
  74048. if (this.back)
  74049. polygons = polygons.concat(this.back.allPolygons());
  74050. return polygons;
  74051. };
  74052. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  74053. // new polygons are filtered down to the bottom of the tree and become new
  74054. // nodes there. Each set of polygons is partitioned using the first polygon
  74055. // (no heuristic is used to pick a good split).
  74056. Node.prototype.build = function (polygons) {
  74057. if (!polygons.length)
  74058. return;
  74059. if (!this.plane)
  74060. this.plane = polygons[0].plane.clone();
  74061. var front = new Array(), back = new Array();
  74062. for (var i = 0; i < polygons.length; i++) {
  74063. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  74064. }
  74065. if (front.length) {
  74066. if (!this.front)
  74067. this.front = new Node();
  74068. this.front.build(front);
  74069. }
  74070. if (back.length) {
  74071. if (!this.back)
  74072. this.back = new Node();
  74073. this.back.build(back);
  74074. }
  74075. };
  74076. return Node;
  74077. }());
  74078. var CSG = /** @class */ (function () {
  74079. function CSG() {
  74080. this.polygons = new Array();
  74081. }
  74082. // Convert BABYLON.Mesh to BABYLON.CSG
  74083. CSG.FromMesh = function (mesh) {
  74084. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  74085. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  74086. if (mesh instanceof BABYLON.Mesh) {
  74087. mesh.computeWorldMatrix(true);
  74088. matrix = mesh.getWorldMatrix();
  74089. meshPosition = mesh.position.clone();
  74090. meshRotation = mesh.rotation.clone();
  74091. if (mesh.rotationQuaternion) {
  74092. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  74093. }
  74094. meshScaling = mesh.scaling.clone();
  74095. }
  74096. else {
  74097. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  74098. }
  74099. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74100. var subMeshes = mesh.subMeshes;
  74101. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  74102. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  74103. vertices = [];
  74104. for (var j = 0; j < 3; j++) {
  74105. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  74106. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  74107. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  74108. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  74109. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  74110. vertex = new Vertex(position, normal, uv);
  74111. vertices.push(vertex);
  74112. }
  74113. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  74114. // To handle the case of degenerated triangle
  74115. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  74116. if (polygon.plane)
  74117. polygons.push(polygon);
  74118. }
  74119. }
  74120. var csg = CSG.FromPolygons(polygons);
  74121. csg.matrix = matrix;
  74122. csg.position = meshPosition;
  74123. csg.rotation = meshRotation;
  74124. csg.scaling = meshScaling;
  74125. csg.rotationQuaternion = meshRotationQuaternion;
  74126. currentCSGMeshId++;
  74127. return csg;
  74128. };
  74129. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  74130. CSG.FromPolygons = function (polygons) {
  74131. var csg = new CSG();
  74132. csg.polygons = polygons;
  74133. return csg;
  74134. };
  74135. CSG.prototype.clone = function () {
  74136. var csg = new CSG();
  74137. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  74138. csg.copyTransformAttributes(this);
  74139. return csg;
  74140. };
  74141. CSG.prototype.union = function (csg) {
  74142. var a = new Node(this.clone().polygons);
  74143. var b = new Node(csg.clone().polygons);
  74144. a.clipTo(b);
  74145. b.clipTo(a);
  74146. b.invert();
  74147. b.clipTo(a);
  74148. b.invert();
  74149. a.build(b.allPolygons());
  74150. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74151. };
  74152. CSG.prototype.unionInPlace = function (csg) {
  74153. var a = new Node(this.polygons);
  74154. var b = new Node(csg.polygons);
  74155. a.clipTo(b);
  74156. b.clipTo(a);
  74157. b.invert();
  74158. b.clipTo(a);
  74159. b.invert();
  74160. a.build(b.allPolygons());
  74161. this.polygons = a.allPolygons();
  74162. };
  74163. CSG.prototype.subtract = function (csg) {
  74164. var a = new Node(this.clone().polygons);
  74165. var b = new Node(csg.clone().polygons);
  74166. a.invert();
  74167. a.clipTo(b);
  74168. b.clipTo(a);
  74169. b.invert();
  74170. b.clipTo(a);
  74171. b.invert();
  74172. a.build(b.allPolygons());
  74173. a.invert();
  74174. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74175. };
  74176. CSG.prototype.subtractInPlace = function (csg) {
  74177. var a = new Node(this.polygons);
  74178. var b = new Node(csg.polygons);
  74179. a.invert();
  74180. a.clipTo(b);
  74181. b.clipTo(a);
  74182. b.invert();
  74183. b.clipTo(a);
  74184. b.invert();
  74185. a.build(b.allPolygons());
  74186. a.invert();
  74187. this.polygons = a.allPolygons();
  74188. };
  74189. CSG.prototype.intersect = function (csg) {
  74190. var a = new Node(this.clone().polygons);
  74191. var b = new Node(csg.clone().polygons);
  74192. a.invert();
  74193. b.clipTo(a);
  74194. b.invert();
  74195. a.clipTo(b);
  74196. b.clipTo(a);
  74197. a.build(b.allPolygons());
  74198. a.invert();
  74199. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  74200. };
  74201. CSG.prototype.intersectInPlace = function (csg) {
  74202. var a = new Node(this.polygons);
  74203. var b = new Node(csg.polygons);
  74204. a.invert();
  74205. b.clipTo(a);
  74206. b.invert();
  74207. a.clipTo(b);
  74208. b.clipTo(a);
  74209. a.build(b.allPolygons());
  74210. a.invert();
  74211. this.polygons = a.allPolygons();
  74212. };
  74213. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  74214. // not modified.
  74215. CSG.prototype.inverse = function () {
  74216. var csg = this.clone();
  74217. csg.inverseInPlace();
  74218. return csg;
  74219. };
  74220. CSG.prototype.inverseInPlace = function () {
  74221. this.polygons.map(function (p) { p.flip(); });
  74222. };
  74223. // This is used to keep meshes transformations so they can be restored
  74224. // when we build back a Babylon Mesh
  74225. // NB : All CSG operations are performed in world coordinates
  74226. CSG.prototype.copyTransformAttributes = function (csg) {
  74227. this.matrix = csg.matrix;
  74228. this.position = csg.position;
  74229. this.rotation = csg.rotation;
  74230. this.scaling = csg.scaling;
  74231. this.rotationQuaternion = csg.rotationQuaternion;
  74232. return this;
  74233. };
  74234. // Build Raw mesh from CSG
  74235. // Coordinates here are in world space
  74236. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74237. var matrix = this.matrix.clone();
  74238. matrix.invert();
  74239. 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;
  74240. if (keepSubMeshes) {
  74241. // Sort Polygons, since subMeshes are indices range
  74242. polygons.sort(function (a, b) {
  74243. if (a.shared.meshId === b.shared.meshId) {
  74244. return a.shared.subMeshId - b.shared.subMeshId;
  74245. }
  74246. else {
  74247. return a.shared.meshId - b.shared.meshId;
  74248. }
  74249. });
  74250. }
  74251. for (var i = 0, il = polygons.length; i < il; i++) {
  74252. polygon = polygons[i];
  74253. // Building SubMeshes
  74254. if (!subMesh_dict[polygon.shared.meshId]) {
  74255. subMesh_dict[polygon.shared.meshId] = {};
  74256. }
  74257. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74258. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74259. indexStart: +Infinity,
  74260. indexEnd: -Infinity,
  74261. materialIndex: polygon.shared.materialIndex
  74262. };
  74263. }
  74264. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74265. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74266. polygonIndices[0] = 0;
  74267. polygonIndices[1] = j - 1;
  74268. polygonIndices[2] = j;
  74269. for (var k = 0; k < 3; k++) {
  74270. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74271. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74272. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74273. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74274. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74275. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74276. // Check if 2 points can be merged
  74277. if (!(typeof vertex_idx !== 'undefined' &&
  74278. normals[vertex_idx * 3] === localNormal.x &&
  74279. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74280. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74281. uvs[vertex_idx * 2] === uv.x &&
  74282. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74283. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74284. uvs.push(uv.x, uv.y);
  74285. normals.push(normal.x, normal.y, normal.z);
  74286. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74287. }
  74288. indices.push(vertex_idx);
  74289. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74290. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74291. currentIndex++;
  74292. }
  74293. }
  74294. }
  74295. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74296. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74297. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74298. mesh.setIndices(indices, null);
  74299. if (keepSubMeshes) {
  74300. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74301. var materialIndexOffset = 0, materialMaxIndex;
  74302. mesh.subMeshes = new Array();
  74303. for (var m in subMesh_dict) {
  74304. materialMaxIndex = -1;
  74305. for (var sm in subMesh_dict[m]) {
  74306. subMesh_obj = subMesh_dict[m][sm];
  74307. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74308. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74309. }
  74310. materialIndexOffset += ++materialMaxIndex;
  74311. }
  74312. }
  74313. return mesh;
  74314. };
  74315. // Build Mesh from CSG taking material and transforms into account
  74316. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74317. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74318. mesh.material = material;
  74319. mesh.position.copyFrom(this.position);
  74320. mesh.rotation.copyFrom(this.rotation);
  74321. if (this.rotationQuaternion) {
  74322. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74323. }
  74324. mesh.scaling.copyFrom(this.scaling);
  74325. mesh.computeWorldMatrix(true);
  74326. return mesh;
  74327. };
  74328. return CSG;
  74329. }());
  74330. BABYLON.CSG = CSG;
  74331. })(BABYLON || (BABYLON = {}));
  74332. //# sourceMappingURL=babylon.csg.js.map
  74333. var BABYLON;
  74334. (function (BABYLON) {
  74335. var LensFlare = /** @class */ (function () {
  74336. function LensFlare(size, position, color, imgUrl, system) {
  74337. this.size = size;
  74338. this.position = position;
  74339. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74340. this.color = color || new BABYLON.Color3(1, 1, 1);
  74341. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74342. this._system = system;
  74343. system.lensFlares.push(this);
  74344. }
  74345. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74346. return new LensFlare(size, position, color, imgUrl, system);
  74347. };
  74348. LensFlare.prototype.dispose = function () {
  74349. if (this.texture) {
  74350. this.texture.dispose();
  74351. }
  74352. // Remove from scene
  74353. var index = this._system.lensFlares.indexOf(this);
  74354. this._system.lensFlares.splice(index, 1);
  74355. };
  74356. ;
  74357. return LensFlare;
  74358. }());
  74359. BABYLON.LensFlare = LensFlare;
  74360. })(BABYLON || (BABYLON = {}));
  74361. //# sourceMappingURL=babylon.lensFlare.js.map
  74362. var BABYLON;
  74363. (function (BABYLON) {
  74364. var LensFlareSystem = /** @class */ (function () {
  74365. function LensFlareSystem(name, emitter, scene) {
  74366. this.name = name;
  74367. this.lensFlares = new Array();
  74368. this.borderLimit = 300;
  74369. this.viewportBorder = 0;
  74370. this.layerMask = 0x0FFFFFFF;
  74371. this._vertexBuffers = {};
  74372. this._isEnabled = true;
  74373. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74374. this._emitter = emitter;
  74375. this.id = name;
  74376. scene.lensFlareSystems.push(this);
  74377. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74378. var engine = scene.getEngine();
  74379. // VBO
  74380. var vertices = [];
  74381. vertices.push(1, 1);
  74382. vertices.push(-1, 1);
  74383. vertices.push(-1, -1);
  74384. vertices.push(1, -1);
  74385. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74386. // Indices
  74387. var indices = [];
  74388. indices.push(0);
  74389. indices.push(1);
  74390. indices.push(2);
  74391. indices.push(0);
  74392. indices.push(2);
  74393. indices.push(3);
  74394. this._indexBuffer = engine.createIndexBuffer(indices);
  74395. // Effects
  74396. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74397. }
  74398. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74399. get: function () {
  74400. return this._isEnabled;
  74401. },
  74402. set: function (value) {
  74403. this._isEnabled = value;
  74404. },
  74405. enumerable: true,
  74406. configurable: true
  74407. });
  74408. LensFlareSystem.prototype.getScene = function () {
  74409. return this._scene;
  74410. };
  74411. LensFlareSystem.prototype.getEmitter = function () {
  74412. return this._emitter;
  74413. };
  74414. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74415. this._emitter = newEmitter;
  74416. };
  74417. LensFlareSystem.prototype.getEmitterPosition = function () {
  74418. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74419. };
  74420. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74421. var position = this.getEmitterPosition();
  74422. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74423. this._positionX = position.x;
  74424. this._positionY = position.y;
  74425. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74426. if (this.viewportBorder > 0) {
  74427. globalViewport.x -= this.viewportBorder;
  74428. globalViewport.y -= this.viewportBorder;
  74429. globalViewport.width += this.viewportBorder * 2;
  74430. globalViewport.height += this.viewportBorder * 2;
  74431. position.x += this.viewportBorder;
  74432. position.y += this.viewportBorder;
  74433. this._positionX += this.viewportBorder;
  74434. this._positionY += this.viewportBorder;
  74435. }
  74436. if (position.z > 0) {
  74437. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74438. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74439. return true;
  74440. }
  74441. return true;
  74442. }
  74443. return false;
  74444. };
  74445. LensFlareSystem.prototype._isVisible = function () {
  74446. if (!this._isEnabled || !this._scene.activeCamera) {
  74447. return false;
  74448. }
  74449. var emitterPosition = this.getEmitterPosition();
  74450. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74451. var distance = direction.length();
  74452. direction.normalize();
  74453. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74454. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74455. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74456. };
  74457. LensFlareSystem.prototype.render = function () {
  74458. if (!this._effect.isReady() || !this._scene.activeCamera)
  74459. return false;
  74460. var engine = this._scene.getEngine();
  74461. var viewport = this._scene.activeCamera.viewport;
  74462. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74463. // Position
  74464. if (!this.computeEffectivePosition(globalViewport)) {
  74465. return false;
  74466. }
  74467. // Visibility
  74468. if (!this._isVisible()) {
  74469. return false;
  74470. }
  74471. // Intensity
  74472. var awayX;
  74473. var awayY;
  74474. if (this._positionX < this.borderLimit + globalViewport.x) {
  74475. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74476. }
  74477. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74478. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74479. }
  74480. else {
  74481. awayX = 0;
  74482. }
  74483. if (this._positionY < this.borderLimit + globalViewport.y) {
  74484. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74485. }
  74486. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74487. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74488. }
  74489. else {
  74490. awayY = 0;
  74491. }
  74492. var away = (awayX > awayY) ? awayX : awayY;
  74493. away -= this.viewportBorder;
  74494. if (away > this.borderLimit) {
  74495. away = this.borderLimit;
  74496. }
  74497. var intensity = 1.0 - (away / this.borderLimit);
  74498. if (intensity < 0) {
  74499. return false;
  74500. }
  74501. if (intensity > 1.0) {
  74502. intensity = 1.0;
  74503. }
  74504. if (this.viewportBorder > 0) {
  74505. globalViewport.x += this.viewportBorder;
  74506. globalViewport.y += this.viewportBorder;
  74507. globalViewport.width -= this.viewportBorder * 2;
  74508. globalViewport.height -= this.viewportBorder * 2;
  74509. this._positionX -= this.viewportBorder;
  74510. this._positionY -= this.viewportBorder;
  74511. }
  74512. // Position
  74513. var centerX = globalViewport.x + globalViewport.width / 2;
  74514. var centerY = globalViewport.y + globalViewport.height / 2;
  74515. var distX = centerX - this._positionX;
  74516. var distY = centerY - this._positionY;
  74517. // Effects
  74518. engine.enableEffect(this._effect);
  74519. engine.setState(false);
  74520. engine.setDepthBuffer(false);
  74521. // VBOs
  74522. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74523. // Flares
  74524. for (var index = 0; index < this.lensFlares.length; index++) {
  74525. var flare = this.lensFlares[index];
  74526. engine.setAlphaMode(flare.alphaMode);
  74527. var x = centerX - (distX * flare.position);
  74528. var y = centerY - (distY * flare.position);
  74529. var cw = flare.size;
  74530. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74531. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74532. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74533. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74534. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74535. // Texture
  74536. this._effect.setTexture("textureSampler", flare.texture);
  74537. // Color
  74538. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74539. // Draw order
  74540. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74541. }
  74542. engine.setDepthBuffer(true);
  74543. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74544. return true;
  74545. };
  74546. LensFlareSystem.prototype.dispose = function () {
  74547. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74548. if (vertexBuffer) {
  74549. vertexBuffer.dispose();
  74550. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74551. }
  74552. if (this._indexBuffer) {
  74553. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74554. this._indexBuffer = null;
  74555. }
  74556. while (this.lensFlares.length) {
  74557. this.lensFlares[0].dispose();
  74558. }
  74559. // Remove from scene
  74560. var index = this._scene.lensFlareSystems.indexOf(this);
  74561. this._scene.lensFlareSystems.splice(index, 1);
  74562. };
  74563. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74564. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74565. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74566. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74567. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74568. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74569. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74570. var parsedFlare = parsedLensFlareSystem.flares[index];
  74571. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74572. }
  74573. return lensFlareSystem;
  74574. };
  74575. LensFlareSystem.prototype.serialize = function () {
  74576. var serializationObject = {};
  74577. serializationObject.id = this.id;
  74578. serializationObject.name = this.name;
  74579. serializationObject.emitterId = this.getEmitter().id;
  74580. serializationObject.borderLimit = this.borderLimit;
  74581. serializationObject.flares = [];
  74582. for (var index = 0; index < this.lensFlares.length; index++) {
  74583. var flare = this.lensFlares[index];
  74584. serializationObject.flares.push({
  74585. size: flare.size,
  74586. position: flare.position,
  74587. color: flare.color.asArray(),
  74588. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74589. });
  74590. }
  74591. return serializationObject;
  74592. };
  74593. return LensFlareSystem;
  74594. }());
  74595. BABYLON.LensFlareSystem = LensFlareSystem;
  74596. })(BABYLON || (BABYLON = {}));
  74597. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74598. var BABYLON;
  74599. (function (BABYLON) {
  74600. /**
  74601. * This is a holder class for the physics joint created by the physics plugin.
  74602. * It holds a set of functions to control the underlying joint.
  74603. */
  74604. var PhysicsJoint = /** @class */ (function () {
  74605. function PhysicsJoint(type, jointData) {
  74606. this.type = type;
  74607. this.jointData = jointData;
  74608. jointData.nativeParams = jointData.nativeParams || {};
  74609. }
  74610. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74611. get: function () {
  74612. return this._physicsJoint;
  74613. },
  74614. set: function (newJoint) {
  74615. if (this._physicsJoint) {
  74616. //remove from the wolrd
  74617. }
  74618. this._physicsJoint = newJoint;
  74619. },
  74620. enumerable: true,
  74621. configurable: true
  74622. });
  74623. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74624. set: function (physicsPlugin) {
  74625. this._physicsPlugin = physicsPlugin;
  74626. },
  74627. enumerable: true,
  74628. configurable: true
  74629. });
  74630. /**
  74631. * Execute a function that is physics-plugin specific.
  74632. * @param {Function} func the function that will be executed.
  74633. * It accepts two parameters: the physics world and the physics joint.
  74634. */
  74635. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74636. func(this._physicsPlugin.world, this._physicsJoint);
  74637. };
  74638. //TODO check if the native joints are the same
  74639. //Joint Types
  74640. PhysicsJoint.DistanceJoint = 0;
  74641. PhysicsJoint.HingeJoint = 1;
  74642. PhysicsJoint.BallAndSocketJoint = 2;
  74643. PhysicsJoint.WheelJoint = 3;
  74644. PhysicsJoint.SliderJoint = 4;
  74645. //OIMO
  74646. PhysicsJoint.PrismaticJoint = 5;
  74647. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74648. PhysicsJoint.UniversalJoint = 6;
  74649. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74650. //Cannon
  74651. //Similar to a Ball-Joint. Different in params
  74652. PhysicsJoint.PointToPointJoint = 8;
  74653. //Cannon only at the moment
  74654. PhysicsJoint.SpringJoint = 9;
  74655. PhysicsJoint.LockJoint = 10;
  74656. return PhysicsJoint;
  74657. }());
  74658. BABYLON.PhysicsJoint = PhysicsJoint;
  74659. /**
  74660. * A class representing a physics distance joint.
  74661. */
  74662. var DistanceJoint = /** @class */ (function (_super) {
  74663. __extends(DistanceJoint, _super);
  74664. function DistanceJoint(jointData) {
  74665. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74666. }
  74667. /**
  74668. * Update the predefined distance.
  74669. */
  74670. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74671. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74672. };
  74673. return DistanceJoint;
  74674. }(PhysicsJoint));
  74675. BABYLON.DistanceJoint = DistanceJoint;
  74676. var MotorEnabledJoint = /** @class */ (function (_super) {
  74677. __extends(MotorEnabledJoint, _super);
  74678. function MotorEnabledJoint(type, jointData) {
  74679. return _super.call(this, type, jointData) || this;
  74680. }
  74681. /**
  74682. * Set the motor values.
  74683. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74684. * @param {number} force the force to apply
  74685. * @param {number} maxForce max force for this motor.
  74686. */
  74687. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74688. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74689. };
  74690. /**
  74691. * Set the motor's limits.
  74692. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74693. */
  74694. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74695. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74696. };
  74697. return MotorEnabledJoint;
  74698. }(PhysicsJoint));
  74699. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74700. /**
  74701. * This class represents a single hinge physics joint
  74702. */
  74703. var HingeJoint = /** @class */ (function (_super) {
  74704. __extends(HingeJoint, _super);
  74705. function HingeJoint(jointData) {
  74706. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74707. }
  74708. /**
  74709. * Set the motor values.
  74710. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74711. * @param {number} force the force to apply
  74712. * @param {number} maxForce max force for this motor.
  74713. */
  74714. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74715. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74716. };
  74717. /**
  74718. * Set the motor's limits.
  74719. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74720. */
  74721. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74722. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74723. };
  74724. return HingeJoint;
  74725. }(MotorEnabledJoint));
  74726. BABYLON.HingeJoint = HingeJoint;
  74727. /**
  74728. * This class represents a dual hinge physics joint (same as wheel joint)
  74729. */
  74730. var Hinge2Joint = /** @class */ (function (_super) {
  74731. __extends(Hinge2Joint, _super);
  74732. function Hinge2Joint(jointData) {
  74733. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74734. }
  74735. /**
  74736. * Set the motor values.
  74737. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74738. * @param {number} force the force to apply
  74739. * @param {number} maxForce max force for this motor.
  74740. * @param {motorIndex} the motor's index, 0 or 1.
  74741. */
  74742. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74743. if (motorIndex === void 0) { motorIndex = 0; }
  74744. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74745. };
  74746. /**
  74747. * Set the motor limits.
  74748. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74749. * @param {number} upperLimit the upper limit
  74750. * @param {number} lowerLimit lower limit
  74751. * @param {motorIndex} the motor's index, 0 or 1.
  74752. */
  74753. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74754. if (motorIndex === void 0) { motorIndex = 0; }
  74755. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74756. };
  74757. return Hinge2Joint;
  74758. }(MotorEnabledJoint));
  74759. BABYLON.Hinge2Joint = Hinge2Joint;
  74760. })(BABYLON || (BABYLON = {}));
  74761. //# sourceMappingURL=babylon.physicsJoint.js.map
  74762. var BABYLON;
  74763. (function (BABYLON) {
  74764. var PhysicsImpostor = /** @class */ (function () {
  74765. function PhysicsImpostor(object, type, _options, _scene) {
  74766. if (_options === void 0) { _options = { mass: 0 }; }
  74767. var _this = this;
  74768. this.object = object;
  74769. this.type = type;
  74770. this._options = _options;
  74771. this._scene = _scene;
  74772. this._bodyUpdateRequired = false;
  74773. this._onBeforePhysicsStepCallbacks = new Array();
  74774. this._onAfterPhysicsStepCallbacks = new Array();
  74775. this._onPhysicsCollideCallbacks = [];
  74776. this._deltaPosition = BABYLON.Vector3.Zero();
  74777. this._isDisposed = false;
  74778. //temp variables for parent rotation calculations
  74779. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74780. this._tmpQuat = new BABYLON.Quaternion();
  74781. this._tmpQuat2 = new BABYLON.Quaternion();
  74782. /**
  74783. * this function is executed by the physics engine.
  74784. */
  74785. this.beforeStep = function () {
  74786. if (!_this._physicsEngine) {
  74787. return;
  74788. }
  74789. _this.object.translate(_this._deltaPosition, -1);
  74790. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74791. _this.object.computeWorldMatrix(false);
  74792. if (_this.object.parent && _this.object.rotationQuaternion) {
  74793. _this.getParentsRotation();
  74794. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74795. }
  74796. else {
  74797. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74798. }
  74799. if (!_this._options.disableBidirectionalTransformation) {
  74800. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74801. }
  74802. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74803. func(_this);
  74804. });
  74805. };
  74806. /**
  74807. * this function is executed by the physics engine.
  74808. */
  74809. this.afterStep = function () {
  74810. if (!_this._physicsEngine) {
  74811. return;
  74812. }
  74813. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74814. func(_this);
  74815. });
  74816. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74817. // object has now its world rotation. needs to be converted to local.
  74818. if (_this.object.parent && _this.object.rotationQuaternion) {
  74819. _this.getParentsRotation();
  74820. _this._tmpQuat.conjugateInPlace();
  74821. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74822. }
  74823. // take the position set and make it the absolute position of this object.
  74824. _this.object.setAbsolutePosition(_this.object.position);
  74825. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74826. _this.object.translate(_this._deltaPosition, 1);
  74827. };
  74828. /**
  74829. * Legacy collision detection event support
  74830. */
  74831. this.onCollideEvent = null;
  74832. //event and body object due to cannon's event-based architecture.
  74833. this.onCollide = function (e) {
  74834. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74835. return;
  74836. }
  74837. if (!_this._physicsEngine) {
  74838. return;
  74839. }
  74840. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74841. if (otherImpostor) {
  74842. // Legacy collision detection event support
  74843. if (_this.onCollideEvent) {
  74844. _this.onCollideEvent(_this, otherImpostor);
  74845. }
  74846. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74847. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74848. }).forEach(function (obj) {
  74849. obj.callback(_this, otherImpostor);
  74850. });
  74851. }
  74852. };
  74853. //sanity check!
  74854. if (!this.object) {
  74855. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74856. return;
  74857. }
  74858. //legacy support for old syntax.
  74859. if (!this._scene && object.getScene) {
  74860. this._scene = object.getScene();
  74861. }
  74862. if (!this._scene) {
  74863. return;
  74864. }
  74865. this._physicsEngine = this._scene.getPhysicsEngine();
  74866. if (!this._physicsEngine) {
  74867. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74868. }
  74869. else {
  74870. //set the object's quaternion, if not set
  74871. if (!this.object.rotationQuaternion) {
  74872. if (this.object.rotation) {
  74873. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74874. }
  74875. else {
  74876. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74877. }
  74878. }
  74879. //default options params
  74880. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74881. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74882. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74883. this._joints = [];
  74884. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74885. if (!this.object.parent || this._options.ignoreParent) {
  74886. this._init();
  74887. }
  74888. else if (this.object.parent.physicsImpostor) {
  74889. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74890. }
  74891. }
  74892. }
  74893. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74894. get: function () {
  74895. return this._isDisposed;
  74896. },
  74897. enumerable: true,
  74898. configurable: true
  74899. });
  74900. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74901. get: function () {
  74902. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74903. },
  74904. set: function (value) {
  74905. this.setMass(value);
  74906. },
  74907. enumerable: true,
  74908. configurable: true
  74909. });
  74910. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74911. get: function () {
  74912. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74913. },
  74914. set: function (value) {
  74915. if (!this._physicsEngine) {
  74916. return;
  74917. }
  74918. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74919. },
  74920. enumerable: true,
  74921. configurable: true
  74922. });
  74923. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74924. get: function () {
  74925. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74926. },
  74927. set: function (value) {
  74928. if (!this._physicsEngine) {
  74929. return;
  74930. }
  74931. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74932. },
  74933. enumerable: true,
  74934. configurable: true
  74935. });
  74936. /**
  74937. * This function will completly initialize this impostor.
  74938. * It will create a new body - but only if this mesh has no parent.
  74939. * If it has, this impostor will not be used other than to define the impostor
  74940. * of the child mesh.
  74941. */
  74942. PhysicsImpostor.prototype._init = function () {
  74943. if (!this._physicsEngine) {
  74944. return;
  74945. }
  74946. this._physicsEngine.removeImpostor(this);
  74947. this.physicsBody = null;
  74948. this._parent = this._parent || this._getPhysicsParent();
  74949. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74950. this._physicsEngine.addImpostor(this);
  74951. }
  74952. };
  74953. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74954. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74955. var parentMesh = this.object.parent;
  74956. return parentMesh.physicsImpostor;
  74957. }
  74958. return null;
  74959. };
  74960. /**
  74961. * Should a new body be generated.
  74962. */
  74963. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74964. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74965. };
  74966. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74967. this.forceUpdate();
  74968. };
  74969. /**
  74970. * Force a regeneration of this or the parent's impostor's body.
  74971. * Use under cautious - This will remove all joints already implemented.
  74972. */
  74973. PhysicsImpostor.prototype.forceUpdate = function () {
  74974. this._init();
  74975. if (this.parent && !this._options.ignoreParent) {
  74976. this.parent.forceUpdate();
  74977. }
  74978. };
  74979. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74980. /*public get mesh(): AbstractMesh {
  74981. return this._mesh;
  74982. }*/
  74983. /**
  74984. * Gets the body that holds this impostor. Either its own, or its parent.
  74985. */
  74986. get: function () {
  74987. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74988. },
  74989. /**
  74990. * Set the physics body. Used mainly by the physics engine/plugin
  74991. */
  74992. set: function (physicsBody) {
  74993. if (this._physicsBody && this._physicsEngine) {
  74994. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74995. }
  74996. this._physicsBody = physicsBody;
  74997. this.resetUpdateFlags();
  74998. },
  74999. enumerable: true,
  75000. configurable: true
  75001. });
  75002. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  75003. get: function () {
  75004. return !this._options.ignoreParent && this._parent ? this._parent : null;
  75005. },
  75006. set: function (value) {
  75007. this._parent = value;
  75008. },
  75009. enumerable: true,
  75010. configurable: true
  75011. });
  75012. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  75013. this._bodyUpdateRequired = false;
  75014. };
  75015. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  75016. if (this.object.getBoundingInfo) {
  75017. var q = this.object.rotationQuaternion;
  75018. //reset rotation
  75019. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  75020. //calculate the world matrix with no rotation
  75021. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75022. var boundingInfo = this.object.getBoundingInfo();
  75023. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  75024. //bring back the rotation
  75025. this.object.rotationQuaternion = q;
  75026. //calculate the world matrix with the new rotation
  75027. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  75028. return size;
  75029. }
  75030. else {
  75031. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  75032. }
  75033. };
  75034. PhysicsImpostor.prototype.getObjectCenter = function () {
  75035. if (this.object.getBoundingInfo) {
  75036. var boundingInfo = this.object.getBoundingInfo();
  75037. return boundingInfo.boundingBox.centerWorld;
  75038. }
  75039. else {
  75040. return this.object.position;
  75041. }
  75042. };
  75043. /**
  75044. * Get a specific parametes from the options parameter.
  75045. */
  75046. PhysicsImpostor.prototype.getParam = function (paramName) {
  75047. return this._options[paramName];
  75048. };
  75049. /**
  75050. * Sets a specific parameter in the options given to the physics plugin
  75051. */
  75052. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  75053. this._options[paramName] = value;
  75054. this._bodyUpdateRequired = true;
  75055. };
  75056. /**
  75057. * Specifically change the body's mass option. Won't recreate the physics body object
  75058. */
  75059. PhysicsImpostor.prototype.setMass = function (mass) {
  75060. if (this.getParam("mass") !== mass) {
  75061. this.setParam("mass", mass);
  75062. }
  75063. if (this._physicsEngine) {
  75064. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  75065. }
  75066. };
  75067. PhysicsImpostor.prototype.getLinearVelocity = function () {
  75068. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  75069. };
  75070. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  75071. if (this._physicsEngine) {
  75072. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  75073. }
  75074. };
  75075. PhysicsImpostor.prototype.getAngularVelocity = function () {
  75076. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  75077. };
  75078. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  75079. if (this._physicsEngine) {
  75080. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  75081. }
  75082. };
  75083. /**
  75084. * Execute a function with the physics plugin native code.
  75085. * Provide a function the will have two variables - the world object and the physics body object.
  75086. */
  75087. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  75088. if (this._physicsEngine) {
  75089. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  75090. }
  75091. };
  75092. /**
  75093. * Register a function that will be executed before the physics world is stepping forward.
  75094. */
  75095. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  75096. this._onBeforePhysicsStepCallbacks.push(func);
  75097. };
  75098. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  75099. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  75100. if (index > -1) {
  75101. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  75102. }
  75103. else {
  75104. BABYLON.Tools.Warn("Function to remove was not found");
  75105. }
  75106. };
  75107. /**
  75108. * Register a function that will be executed after the physics step
  75109. */
  75110. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  75111. this._onAfterPhysicsStepCallbacks.push(func);
  75112. };
  75113. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  75114. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  75115. if (index > -1) {
  75116. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  75117. }
  75118. else {
  75119. BABYLON.Tools.Warn("Function to remove was not found");
  75120. }
  75121. };
  75122. /**
  75123. * register a function that will be executed when this impostor collides against a different body.
  75124. */
  75125. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  75126. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75127. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  75128. };
  75129. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  75130. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  75131. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  75132. if (index > -1) {
  75133. this._onPhysicsCollideCallbacks.splice(index, 1);
  75134. }
  75135. else {
  75136. BABYLON.Tools.Warn("Function to remove was not found");
  75137. }
  75138. };
  75139. PhysicsImpostor.prototype.getParentsRotation = function () {
  75140. var parent = this.object.parent;
  75141. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  75142. while (parent) {
  75143. if (parent.rotationQuaternion) {
  75144. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  75145. }
  75146. else {
  75147. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  75148. }
  75149. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  75150. parent = parent.parent;
  75151. }
  75152. return this._tmpQuat;
  75153. };
  75154. /**
  75155. * Apply a force
  75156. */
  75157. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  75158. if (this._physicsEngine) {
  75159. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  75160. }
  75161. return this;
  75162. };
  75163. /**
  75164. * Apply an impulse
  75165. */
  75166. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  75167. if (this._physicsEngine) {
  75168. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  75169. }
  75170. return this;
  75171. };
  75172. /**
  75173. * A help function to create a joint.
  75174. */
  75175. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  75176. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  75177. this.addJoint(otherImpostor, joint);
  75178. return this;
  75179. };
  75180. /**
  75181. * Add a joint to this impostor with a different impostor.
  75182. */
  75183. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  75184. this._joints.push({
  75185. otherImpostor: otherImpostor,
  75186. joint: joint
  75187. });
  75188. if (this._physicsEngine) {
  75189. this._physicsEngine.addJoint(this, otherImpostor, joint);
  75190. }
  75191. return this;
  75192. };
  75193. /**
  75194. * Will keep this body still, in a sleep mode.
  75195. */
  75196. PhysicsImpostor.prototype.sleep = function () {
  75197. if (this._physicsEngine) {
  75198. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  75199. }
  75200. return this;
  75201. };
  75202. /**
  75203. * Wake the body up.
  75204. */
  75205. PhysicsImpostor.prototype.wakeUp = function () {
  75206. if (this._physicsEngine) {
  75207. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  75208. }
  75209. return this;
  75210. };
  75211. PhysicsImpostor.prototype.clone = function (newObject) {
  75212. if (!newObject)
  75213. return null;
  75214. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  75215. };
  75216. PhysicsImpostor.prototype.dispose = function () {
  75217. var _this = this;
  75218. //no dispose if no physics engine is available.
  75219. if (!this._physicsEngine) {
  75220. return;
  75221. }
  75222. this._joints.forEach(function (j) {
  75223. if (_this._physicsEngine) {
  75224. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75225. }
  75226. });
  75227. //dispose the physics body
  75228. this._physicsEngine.removeImpostor(this);
  75229. if (this.parent) {
  75230. this.parent.forceUpdate();
  75231. }
  75232. else {
  75233. /*this._object.getChildMeshes().forEach(function(mesh) {
  75234. if (mesh.physicsImpostor) {
  75235. if (disposeChildren) {
  75236. mesh.physicsImpostor.dispose();
  75237. mesh.physicsImpostor = null;
  75238. }
  75239. }
  75240. })*/
  75241. }
  75242. this._isDisposed = true;
  75243. };
  75244. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75245. this._deltaPosition.copyFrom(position);
  75246. };
  75247. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75248. if (!this._deltaRotation) {
  75249. this._deltaRotation = new BABYLON.Quaternion();
  75250. }
  75251. this._deltaRotation.copyFrom(rotation);
  75252. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75253. };
  75254. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75255. if (this._physicsEngine) {
  75256. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75257. }
  75258. return this;
  75259. };
  75260. PhysicsImpostor.prototype.getRadius = function () {
  75261. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75262. };
  75263. /**
  75264. * Sync a bone with this impostor
  75265. * @param bone The bone to sync to the impostor.
  75266. * @param boneMesh The mesh that the bone is influencing.
  75267. * @param jointPivot The pivot of the joint / bone in local space.
  75268. * @param distToJoint Optional distance from the impostor to the joint.
  75269. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75270. */
  75271. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75272. var tempVec = PhysicsImpostor._tmpVecs[0];
  75273. var mesh = this.object;
  75274. if (mesh.rotationQuaternion) {
  75275. if (adjustRotation) {
  75276. var tempQuat = PhysicsImpostor._tmpQuat;
  75277. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75278. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75279. }
  75280. else {
  75281. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75282. }
  75283. }
  75284. tempVec.x = 0;
  75285. tempVec.y = 0;
  75286. tempVec.z = 0;
  75287. if (jointPivot) {
  75288. tempVec.x = jointPivot.x;
  75289. tempVec.y = jointPivot.y;
  75290. tempVec.z = jointPivot.z;
  75291. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75292. if (distToJoint === undefined || distToJoint === null) {
  75293. distToJoint = jointPivot.length();
  75294. }
  75295. tempVec.x *= distToJoint;
  75296. tempVec.y *= distToJoint;
  75297. tempVec.z *= distToJoint;
  75298. }
  75299. if (bone.getParent()) {
  75300. tempVec.addInPlace(mesh.getAbsolutePosition());
  75301. bone.setAbsolutePosition(tempVec, boneMesh);
  75302. }
  75303. else {
  75304. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75305. boneMesh.position.x -= tempVec.x;
  75306. boneMesh.position.y -= tempVec.y;
  75307. boneMesh.position.z -= tempVec.z;
  75308. }
  75309. };
  75310. /**
  75311. * Sync impostor to a bone
  75312. * @param bone The bone that the impostor will be synced to.
  75313. * @param boneMesh The mesh that the bone is influencing.
  75314. * @param jointPivot The pivot of the joint / bone in local space.
  75315. * @param distToJoint Optional distance from the impostor to the joint.
  75316. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75317. * @param boneAxis Optional vector3 axis the bone is aligned with
  75318. */
  75319. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75320. var mesh = this.object;
  75321. if (mesh.rotationQuaternion) {
  75322. if (adjustRotation) {
  75323. var tempQuat = PhysicsImpostor._tmpQuat;
  75324. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75325. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75326. }
  75327. else {
  75328. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75329. }
  75330. }
  75331. var pos = PhysicsImpostor._tmpVecs[0];
  75332. var boneDir = PhysicsImpostor._tmpVecs[1];
  75333. if (!boneAxis) {
  75334. boneAxis = PhysicsImpostor._tmpVecs[2];
  75335. boneAxis.x = 0;
  75336. boneAxis.y = 1;
  75337. boneAxis.z = 0;
  75338. }
  75339. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75340. bone.getAbsolutePositionToRef(boneMesh, pos);
  75341. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75342. distToJoint = jointPivot.length();
  75343. }
  75344. if (distToJoint !== undefined && distToJoint !== null) {
  75345. pos.x += boneDir.x * distToJoint;
  75346. pos.y += boneDir.y * distToJoint;
  75347. pos.z += boneDir.z * distToJoint;
  75348. }
  75349. mesh.setAbsolutePosition(pos);
  75350. };
  75351. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75352. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75353. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75354. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75355. //Impostor types
  75356. PhysicsImpostor.NoImpostor = 0;
  75357. PhysicsImpostor.SphereImpostor = 1;
  75358. PhysicsImpostor.BoxImpostor = 2;
  75359. PhysicsImpostor.PlaneImpostor = 3;
  75360. PhysicsImpostor.MeshImpostor = 4;
  75361. PhysicsImpostor.CylinderImpostor = 7;
  75362. PhysicsImpostor.ParticleImpostor = 8;
  75363. PhysicsImpostor.HeightmapImpostor = 9;
  75364. return PhysicsImpostor;
  75365. }());
  75366. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75367. })(BABYLON || (BABYLON = {}));
  75368. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75369. var BABYLON;
  75370. (function (BABYLON) {
  75371. var PhysicsEngine = /** @class */ (function () {
  75372. function PhysicsEngine(gravity, _physicsPlugin) {
  75373. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75374. this._physicsPlugin = _physicsPlugin;
  75375. //new methods and parameters
  75376. this._impostors = [];
  75377. this._joints = [];
  75378. if (!this._physicsPlugin.isSupported()) {
  75379. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75380. + "Please make sure it is included.");
  75381. }
  75382. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75383. this.setGravity(gravity);
  75384. this.setTimeStep();
  75385. }
  75386. PhysicsEngine.prototype.setGravity = function (gravity) {
  75387. this.gravity = gravity;
  75388. this._physicsPlugin.setGravity(this.gravity);
  75389. };
  75390. /**
  75391. * Set the time step of the physics engine.
  75392. * default is 1/60.
  75393. * To slow it down, enter 1/600 for example.
  75394. * To speed it up, 1/30
  75395. * @param {number} newTimeStep the new timestep to apply to this world.
  75396. */
  75397. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75398. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75399. this._physicsPlugin.setTimeStep(newTimeStep);
  75400. };
  75401. /**
  75402. * Get the time step of the physics engine.
  75403. */
  75404. PhysicsEngine.prototype.getTimeStep = function () {
  75405. return this._physicsPlugin.getTimeStep();
  75406. };
  75407. PhysicsEngine.prototype.dispose = function () {
  75408. this._impostors.forEach(function (impostor) {
  75409. impostor.dispose();
  75410. });
  75411. this._physicsPlugin.dispose();
  75412. };
  75413. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75414. return this._physicsPlugin.name;
  75415. };
  75416. /**
  75417. * Adding a new impostor for the impostor tracking.
  75418. * This will be done by the impostor itself.
  75419. * @param {PhysicsImpostor} impostor the impostor to add
  75420. */
  75421. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75422. impostor.uniqueId = this._impostors.push(impostor);
  75423. //if no parent, generate the body
  75424. if (!impostor.parent) {
  75425. this._physicsPlugin.generatePhysicsBody(impostor);
  75426. }
  75427. };
  75428. /**
  75429. * Remove an impostor from the engine.
  75430. * This impostor and its mesh will not longer be updated by the physics engine.
  75431. * @param {PhysicsImpostor} impostor the impostor to remove
  75432. */
  75433. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75434. var index = this._impostors.indexOf(impostor);
  75435. if (index > -1) {
  75436. var removed = this._impostors.splice(index, 1);
  75437. //Is it needed?
  75438. if (removed.length) {
  75439. //this will also remove it from the world.
  75440. removed[0].physicsBody = null;
  75441. }
  75442. }
  75443. };
  75444. /**
  75445. * Add a joint to the physics engine
  75446. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75447. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75448. * @param {PhysicsJoint} the joint that will connect both impostors.
  75449. */
  75450. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75451. var impostorJoint = {
  75452. mainImpostor: mainImpostor,
  75453. connectedImpostor: connectedImpostor,
  75454. joint: joint
  75455. };
  75456. joint.physicsPlugin = this._physicsPlugin;
  75457. this._joints.push(impostorJoint);
  75458. this._physicsPlugin.generateJoint(impostorJoint);
  75459. };
  75460. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75461. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75462. return (impostorJoint.connectedImpostor === connectedImpostor
  75463. && impostorJoint.joint === joint
  75464. && impostorJoint.mainImpostor === mainImpostor);
  75465. });
  75466. if (matchingJoints.length) {
  75467. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75468. //TODO remove it from the list as well
  75469. }
  75470. };
  75471. /**
  75472. * Called by the scene. no need to call it.
  75473. */
  75474. PhysicsEngine.prototype._step = function (delta) {
  75475. var _this = this;
  75476. //check if any mesh has no body / requires an update
  75477. this._impostors.forEach(function (impostor) {
  75478. if (impostor.isBodyInitRequired()) {
  75479. _this._physicsPlugin.generatePhysicsBody(impostor);
  75480. }
  75481. });
  75482. if (delta > 0.1) {
  75483. delta = 0.1;
  75484. }
  75485. else if (delta <= 0) {
  75486. delta = 1.0 / 60.0;
  75487. }
  75488. this._physicsPlugin.executeStep(delta, this._impostors);
  75489. };
  75490. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75491. return this._physicsPlugin;
  75492. };
  75493. PhysicsEngine.prototype.getImpostors = function () {
  75494. return this._impostors;
  75495. };
  75496. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75497. for (var i = 0; i < this._impostors.length; ++i) {
  75498. if (this._impostors[i].object === object) {
  75499. return this._impostors[i];
  75500. }
  75501. }
  75502. return null;
  75503. };
  75504. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75505. for (var i = 0; i < this._impostors.length; ++i) {
  75506. if (this._impostors[i].physicsBody === body) {
  75507. return this._impostors[i];
  75508. }
  75509. }
  75510. return null;
  75511. };
  75512. // Statics
  75513. PhysicsEngine.Epsilon = 0.001;
  75514. return PhysicsEngine;
  75515. }());
  75516. BABYLON.PhysicsEngine = PhysicsEngine;
  75517. })(BABYLON || (BABYLON = {}));
  75518. //# sourceMappingURL=babylon.physicsEngine.js.map
  75519. var BABYLON;
  75520. (function (BABYLON) {
  75521. var PhysicsHelper = /** @class */ (function () {
  75522. function PhysicsHelper(scene) {
  75523. this._scene = scene;
  75524. this._physicsEngine = this._scene.getPhysicsEngine();
  75525. if (!this._physicsEngine) {
  75526. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75527. }
  75528. }
  75529. /**
  75530. * @param {Vector3} origin the origin of the explosion
  75531. * @param {number} radius the explosion radius
  75532. * @param {number} strength the explosion strength
  75533. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75534. */
  75535. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75536. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75537. if (!this._physicsEngine) {
  75538. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75539. return null;
  75540. }
  75541. var impostors = this._physicsEngine.getImpostors();
  75542. if (impostors.length === 0) {
  75543. return null;
  75544. }
  75545. var event = new PhysicsRadialExplosionEvent(this._scene);
  75546. impostors.forEach(function (impostor) {
  75547. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75548. if (!impostorForceAndContactPoint) {
  75549. return;
  75550. }
  75551. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75552. });
  75553. event.dispose(false);
  75554. return event;
  75555. };
  75556. /**
  75557. * @param {Vector3} origin the origin of the explosion
  75558. * @param {number} radius the explosion radius
  75559. * @param {number} strength the explosion strength
  75560. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75561. */
  75562. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75563. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75564. if (!this._physicsEngine) {
  75565. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75566. return null;
  75567. }
  75568. var impostors = this._physicsEngine.getImpostors();
  75569. if (impostors.length === 0) {
  75570. return null;
  75571. }
  75572. var event = new PhysicsRadialExplosionEvent(this._scene);
  75573. impostors.forEach(function (impostor) {
  75574. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75575. if (!impostorForceAndContactPoint) {
  75576. return;
  75577. }
  75578. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75579. });
  75580. event.dispose(false);
  75581. return event;
  75582. };
  75583. /**
  75584. * @param {Vector3} origin the origin of the explosion
  75585. * @param {number} radius the explosion radius
  75586. * @param {number} strength the explosion strength
  75587. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75588. */
  75589. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75590. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75591. if (!this._physicsEngine) {
  75592. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75593. return null;
  75594. }
  75595. var impostors = this._physicsEngine.getImpostors();
  75596. if (impostors.length === 0) {
  75597. return null;
  75598. }
  75599. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75600. event.dispose(false);
  75601. return event;
  75602. };
  75603. /**
  75604. * @param {Vector3} origin the origin of the updraft
  75605. * @param {number} radius the radius of the updraft
  75606. * @param {number} strength the strength of the updraft
  75607. * @param {number} height the height of the updraft
  75608. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75609. */
  75610. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75611. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75612. if (!this._physicsEngine) {
  75613. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75614. return null;
  75615. }
  75616. if (this._physicsEngine.getImpostors().length === 0) {
  75617. return null;
  75618. }
  75619. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75620. event.dispose(false);
  75621. return event;
  75622. };
  75623. /**
  75624. * @param {Vector3} origin the of the vortex
  75625. * @param {number} radius the radius of the vortex
  75626. * @param {number} strength the strength of the vortex
  75627. * @param {number} height the height of the vortex
  75628. */
  75629. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75630. if (!this._physicsEngine) {
  75631. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75632. return null;
  75633. }
  75634. if (this._physicsEngine.getImpostors().length === 0) {
  75635. return null;
  75636. }
  75637. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75638. event.dispose(false);
  75639. return event;
  75640. };
  75641. return PhysicsHelper;
  75642. }());
  75643. BABYLON.PhysicsHelper = PhysicsHelper;
  75644. /***** Radial explosion *****/
  75645. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75646. function PhysicsRadialExplosionEvent(scene) {
  75647. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75648. this._rays = [];
  75649. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75650. this._scene = scene;
  75651. }
  75652. /**
  75653. * Returns the data related to the radial explosion event (sphere & rays).
  75654. * @returns {PhysicsRadialExplosionEventData}
  75655. */
  75656. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75657. this._dataFetched = true;
  75658. return {
  75659. sphere: this._sphere,
  75660. rays: this._rays,
  75661. };
  75662. };
  75663. /**
  75664. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75665. * @param impostor
  75666. * @param {Vector3} origin the origin of the explosion
  75667. * @param {number} radius the explosion radius
  75668. * @param {number} strength the explosion strength
  75669. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75670. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75671. */
  75672. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75673. if (impostor.mass === 0) {
  75674. return null;
  75675. }
  75676. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75677. return null;
  75678. }
  75679. if (impostor.object.getClassName() !== 'Mesh') {
  75680. return null;
  75681. }
  75682. var impostorObject = impostor.object;
  75683. var impostorObjectCenter = impostor.getObjectCenter();
  75684. var direction = impostorObjectCenter.subtract(origin);
  75685. var ray = new BABYLON.Ray(origin, direction, radius);
  75686. this._rays.push(ray);
  75687. var hit = ray.intersectsMesh(impostorObject);
  75688. var contactPoint = hit.pickedPoint;
  75689. if (!contactPoint) {
  75690. return null;
  75691. }
  75692. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75693. if (distanceFromOrigin > radius) {
  75694. return null;
  75695. }
  75696. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75697. ? strength
  75698. : strength * (1 - (distanceFromOrigin / radius));
  75699. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75700. return { force: force, contactPoint: contactPoint };
  75701. };
  75702. /**
  75703. * Disposes the sphere.
  75704. * @param {bolean} force
  75705. */
  75706. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75707. var _this = this;
  75708. if (force === void 0) { force = true; }
  75709. if (force) {
  75710. this._sphere.dispose();
  75711. }
  75712. else {
  75713. setTimeout(function () {
  75714. if (!_this._dataFetched) {
  75715. _this._sphere.dispose();
  75716. }
  75717. }, 0);
  75718. }
  75719. };
  75720. /*** Helpers ***/
  75721. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75722. if (!this._sphere) {
  75723. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75724. this._sphere.isVisible = false;
  75725. }
  75726. };
  75727. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75728. var impostorObject = impostor.object;
  75729. this._prepareSphere();
  75730. this._sphere.position = origin;
  75731. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75732. this._sphere._updateBoundingInfo();
  75733. this._sphere.computeWorldMatrix(true);
  75734. return this._sphere.intersectsMesh(impostorObject, true);
  75735. };
  75736. return PhysicsRadialExplosionEvent;
  75737. }());
  75738. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75739. /***** Gravitational Field *****/
  75740. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75741. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75742. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75743. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75744. this._physicsHelper = physicsHelper;
  75745. this._scene = scene;
  75746. this._origin = origin;
  75747. this._radius = radius;
  75748. this._strength = strength;
  75749. this._falloff = falloff;
  75750. this._tickCallback = this._tick.bind(this);
  75751. }
  75752. /**
  75753. * Returns the data related to the gravitational field event (sphere).
  75754. * @returns {PhysicsGravitationalFieldEventData}
  75755. */
  75756. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75757. this._dataFetched = true;
  75758. return {
  75759. sphere: this._sphere,
  75760. };
  75761. };
  75762. /**
  75763. * Enables the gravitational field.
  75764. */
  75765. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75766. this._tickCallback.call(this);
  75767. this._scene.registerBeforeRender(this._tickCallback);
  75768. };
  75769. /**
  75770. * Disables the gravitational field.
  75771. */
  75772. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75773. this._scene.unregisterBeforeRender(this._tickCallback);
  75774. };
  75775. /**
  75776. * Disposes the sphere.
  75777. * @param {bolean} force
  75778. */
  75779. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75780. var _this = this;
  75781. if (force === void 0) { force = true; }
  75782. if (force) {
  75783. this._sphere.dispose();
  75784. }
  75785. else {
  75786. setTimeout(function () {
  75787. if (!_this._dataFetched) {
  75788. _this._sphere.dispose();
  75789. }
  75790. }, 0);
  75791. }
  75792. };
  75793. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75794. // Since the params won't change, we fetch the event only once
  75795. if (this._sphere) {
  75796. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75797. }
  75798. else {
  75799. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75800. if (radialExplosionEvent) {
  75801. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75802. }
  75803. }
  75804. };
  75805. return PhysicsGravitationalFieldEvent;
  75806. }());
  75807. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75808. /***** Updraft *****/
  75809. var PhysicsUpdraftEvent = /** @class */ (function () {
  75810. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75811. this._scene = _scene;
  75812. this._origin = _origin;
  75813. this._radius = _radius;
  75814. this._strength = _strength;
  75815. this._height = _height;
  75816. this._updraftMode = _updraftMode;
  75817. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75818. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75819. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75820. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75821. this._physicsEngine = this._scene.getPhysicsEngine();
  75822. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75823. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75824. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75825. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75826. }
  75827. this._tickCallback = this._tick.bind(this);
  75828. }
  75829. /**
  75830. * Returns the data related to the updraft event (cylinder).
  75831. * @returns {PhysicsUpdraftEventData}
  75832. */
  75833. PhysicsUpdraftEvent.prototype.getData = function () {
  75834. this._dataFetched = true;
  75835. return {
  75836. cylinder: this._cylinder,
  75837. };
  75838. };
  75839. /**
  75840. * Enables the updraft.
  75841. */
  75842. PhysicsUpdraftEvent.prototype.enable = function () {
  75843. this._tickCallback.call(this);
  75844. this._scene.registerBeforeRender(this._tickCallback);
  75845. };
  75846. /**
  75847. * Disables the cortex.
  75848. */
  75849. PhysicsUpdraftEvent.prototype.disable = function () {
  75850. this._scene.unregisterBeforeRender(this._tickCallback);
  75851. };
  75852. /**
  75853. * Disposes the sphere.
  75854. * @param {bolean} force
  75855. */
  75856. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75857. var _this = this;
  75858. if (force === void 0) { force = true; }
  75859. if (force) {
  75860. this._cylinder.dispose();
  75861. }
  75862. else {
  75863. setTimeout(function () {
  75864. if (!_this._dataFetched) {
  75865. _this._cylinder.dispose();
  75866. }
  75867. }, 0);
  75868. }
  75869. };
  75870. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75871. if (impostor.mass === 0) {
  75872. return null;
  75873. }
  75874. if (!this._intersectsWithCylinder(impostor)) {
  75875. return null;
  75876. }
  75877. var impostorObjectCenter = impostor.getObjectCenter();
  75878. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75879. var direction = this._originDirection;
  75880. }
  75881. else {
  75882. var direction = impostorObjectCenter.subtract(this._originTop);
  75883. }
  75884. var multiplier = this._strength * -1;
  75885. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75886. return { force: force, contactPoint: impostorObjectCenter };
  75887. };
  75888. PhysicsUpdraftEvent.prototype._tick = function () {
  75889. var _this = this;
  75890. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75891. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75892. if (!impostorForceAndContactPoint) {
  75893. return;
  75894. }
  75895. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75896. });
  75897. };
  75898. /*** Helpers ***/
  75899. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75900. if (!this._cylinder) {
  75901. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75902. height: this._height,
  75903. diameter: this._radius * 2,
  75904. }, this._scene);
  75905. this._cylinder.isVisible = false;
  75906. }
  75907. };
  75908. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75909. var impostorObject = impostor.object;
  75910. this._prepareCylinder();
  75911. this._cylinder.position = this._cylinderPosition;
  75912. return this._cylinder.intersectsMesh(impostorObject, true);
  75913. };
  75914. return PhysicsUpdraftEvent;
  75915. }());
  75916. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75917. /***** Vortex *****/
  75918. var PhysicsVortexEvent = /** @class */ (function () {
  75919. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75920. this._scene = _scene;
  75921. this._origin = _origin;
  75922. this._radius = _radius;
  75923. this._strength = _strength;
  75924. this._height = _height;
  75925. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75926. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75927. this._updraftMultiplier = 0.02;
  75928. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75929. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75930. this._physicsEngine = this._scene.getPhysicsEngine();
  75931. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75932. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75933. this._tickCallback = this._tick.bind(this);
  75934. }
  75935. /**
  75936. * Returns the data related to the vortex event (cylinder).
  75937. * @returns {PhysicsVortexEventData}
  75938. */
  75939. PhysicsVortexEvent.prototype.getData = function () {
  75940. this._dataFetched = true;
  75941. return {
  75942. cylinder: this._cylinder,
  75943. };
  75944. };
  75945. /**
  75946. * Enables the vortex.
  75947. */
  75948. PhysicsVortexEvent.prototype.enable = function () {
  75949. this._tickCallback.call(this);
  75950. this._scene.registerBeforeRender(this._tickCallback);
  75951. };
  75952. /**
  75953. * Disables the cortex.
  75954. */
  75955. PhysicsVortexEvent.prototype.disable = function () {
  75956. this._scene.unregisterBeforeRender(this._tickCallback);
  75957. };
  75958. /**
  75959. * Disposes the sphere.
  75960. * @param {bolean} force
  75961. */
  75962. PhysicsVortexEvent.prototype.dispose = function (force) {
  75963. var _this = this;
  75964. if (force === void 0) { force = true; }
  75965. if (force) {
  75966. this._cylinder.dispose();
  75967. }
  75968. else {
  75969. setTimeout(function () {
  75970. if (!_this._dataFetched) {
  75971. _this._cylinder.dispose();
  75972. }
  75973. }, 0);
  75974. }
  75975. };
  75976. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75977. if (impostor.mass === 0) {
  75978. return null;
  75979. }
  75980. if (!this._intersectsWithCylinder(impostor)) {
  75981. return null;
  75982. }
  75983. if (impostor.object.getClassName() !== 'Mesh') {
  75984. return null;
  75985. }
  75986. var impostorObject = impostor.object;
  75987. var impostorObjectCenter = impostor.getObjectCenter();
  75988. 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)
  75989. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75990. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75991. var hit = ray.intersectsMesh(impostorObject);
  75992. var contactPoint = hit.pickedPoint;
  75993. if (!contactPoint) {
  75994. return null;
  75995. }
  75996. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75997. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75998. var directionToOrigin = contactPoint.normalize();
  75999. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76000. directionToOrigin = directionToOrigin.negate();
  76001. }
  76002. // TODO: find a more physically based solution
  76003. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  76004. var forceX = directionToOrigin.x * this._strength / 8;
  76005. var forceY = directionToOrigin.y * this._updraftMultiplier;
  76006. var forceZ = directionToOrigin.z * this._strength / 8;
  76007. }
  76008. else {
  76009. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  76010. var forceY = this._originTop.y * this._updraftMultiplier;
  76011. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  76012. }
  76013. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  76014. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  76015. return { force: force, contactPoint: impostorObjectCenter };
  76016. };
  76017. PhysicsVortexEvent.prototype._tick = function () {
  76018. var _this = this;
  76019. this._physicsEngine.getImpostors().forEach(function (impostor) {
  76020. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  76021. if (!impostorForceAndContactPoint) {
  76022. return;
  76023. }
  76024. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76025. });
  76026. };
  76027. /*** Helpers ***/
  76028. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  76029. if (!this._cylinder) {
  76030. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  76031. height: this._height,
  76032. diameter: this._radius * 2,
  76033. }, this._scene);
  76034. this._cylinder.isVisible = false;
  76035. }
  76036. };
  76037. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  76038. var impostorObject = impostor.object;
  76039. this._prepareCylinder();
  76040. this._cylinder.position = this._cylinderPosition;
  76041. return this._cylinder.intersectsMesh(impostorObject, true);
  76042. };
  76043. return PhysicsVortexEvent;
  76044. }());
  76045. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  76046. /***** Enums *****/
  76047. /**
  76048. * The strenght of the force in correspondence to the distance of the affected object
  76049. */
  76050. var PhysicsRadialImpulseFalloff;
  76051. (function (PhysicsRadialImpulseFalloff) {
  76052. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  76053. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  76054. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  76055. /**
  76056. * The strenght of the force in correspondence to the distance of the affected object
  76057. */
  76058. var PhysicsUpdraftMode;
  76059. (function (PhysicsUpdraftMode) {
  76060. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  76061. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  76062. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  76063. })(BABYLON || (BABYLON = {}));
  76064. //# sourceMappingURL=babylon.physicsHelper.js.map
  76065. var BABYLON;
  76066. (function (BABYLON) {
  76067. var CannonJSPlugin = /** @class */ (function () {
  76068. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  76069. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  76070. if (iterations === void 0) { iterations = 10; }
  76071. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  76072. this.name = "CannonJSPlugin";
  76073. this._physicsMaterials = new Array();
  76074. this._fixedTimeStep = 1 / 60;
  76075. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  76076. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  76077. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  76078. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  76079. this._tmpPosition = BABYLON.Vector3.Zero();
  76080. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  76081. this._tmpUnityRotation = new BABYLON.Quaternion();
  76082. if (!this.isSupported()) {
  76083. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  76084. return;
  76085. }
  76086. this._extendNamespace();
  76087. this.world = new this.BJSCANNON.World();
  76088. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  76089. this.world.solver.iterations = iterations;
  76090. }
  76091. CannonJSPlugin.prototype.setGravity = function (gravity) {
  76092. this.world.gravity.copy(gravity);
  76093. };
  76094. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  76095. this._fixedTimeStep = timeStep;
  76096. };
  76097. CannonJSPlugin.prototype.getTimeStep = function () {
  76098. return this._fixedTimeStep;
  76099. };
  76100. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  76101. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  76102. };
  76103. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76104. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76105. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76106. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  76107. };
  76108. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76109. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  76110. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  76111. impostor.physicsBody.applyForce(impulse, worldPoint);
  76112. };
  76113. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76114. //parent-child relationship. Does this impostor has a parent impostor?
  76115. if (impostor.parent) {
  76116. if (impostor.physicsBody) {
  76117. this.removePhysicsBody(impostor);
  76118. //TODO is that needed?
  76119. impostor.forceUpdate();
  76120. }
  76121. return;
  76122. }
  76123. //should a new body be created for this impostor?
  76124. if (impostor.isBodyInitRequired()) {
  76125. var shape = this._createShape(impostor);
  76126. //unregister events, if body is being changed
  76127. var oldBody = impostor.physicsBody;
  76128. if (oldBody) {
  76129. this.removePhysicsBody(impostor);
  76130. }
  76131. //create the body and material
  76132. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  76133. var bodyCreationObject = {
  76134. mass: impostor.getParam("mass"),
  76135. material: material
  76136. };
  76137. // A simple extend, in case native options were used.
  76138. var nativeOptions = impostor.getParam("nativeOptions");
  76139. for (var key in nativeOptions) {
  76140. if (nativeOptions.hasOwnProperty(key)) {
  76141. bodyCreationObject[key] = nativeOptions[key];
  76142. }
  76143. }
  76144. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  76145. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  76146. this.world.addEventListener("preStep", impostor.beforeStep);
  76147. this.world.addEventListener("postStep", impostor.afterStep);
  76148. impostor.physicsBody.addShape(shape);
  76149. this.world.add(impostor.physicsBody);
  76150. //try to keep the body moving in the right direction by taking old properties.
  76151. //Should be tested!
  76152. if (oldBody) {
  76153. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  76154. impostor.physicsBody[param].copy(oldBody[param]);
  76155. });
  76156. }
  76157. this._processChildMeshes(impostor);
  76158. }
  76159. //now update the body's transformation
  76160. this._updatePhysicsBodyTransformation(impostor);
  76161. };
  76162. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  76163. var _this = this;
  76164. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  76165. var currentRotation = mainImpostor.object.rotationQuaternion;
  76166. if (meshChildren.length) {
  76167. var processMesh = function (localPosition, mesh) {
  76168. if (!currentRotation || !mesh.rotationQuaternion) {
  76169. return;
  76170. }
  76171. var childImpostor = mesh.getPhysicsImpostor();
  76172. if (childImpostor) {
  76173. var parent = childImpostor.parent;
  76174. if (parent !== mainImpostor) {
  76175. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  76176. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  76177. if (childImpostor.physicsBody) {
  76178. _this.removePhysicsBody(childImpostor);
  76179. childImpostor.physicsBody = null;
  76180. }
  76181. childImpostor.parent = mainImpostor;
  76182. childImpostor.resetUpdateFlags();
  76183. 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));
  76184. //Add the mass of the children.
  76185. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  76186. }
  76187. }
  76188. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  76189. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  76190. };
  76191. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  76192. }
  76193. };
  76194. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76195. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  76196. this.world.removeEventListener("preStep", impostor.beforeStep);
  76197. this.world.removeEventListener("postStep", impostor.afterStep);
  76198. this.world.remove(impostor.physicsBody);
  76199. };
  76200. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76201. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76202. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76203. if (!mainBody || !connectedBody) {
  76204. return;
  76205. }
  76206. var constraint;
  76207. var jointData = impostorJoint.joint.jointData;
  76208. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  76209. var constraintData = {
  76210. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  76211. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  76212. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  76213. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  76214. maxForce: jointData.nativeParams.maxForce,
  76215. collideConnected: !!jointData.collision
  76216. };
  76217. switch (impostorJoint.joint.type) {
  76218. case BABYLON.PhysicsJoint.HingeJoint:
  76219. case BABYLON.PhysicsJoint.Hinge2Joint:
  76220. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76221. break;
  76222. case BABYLON.PhysicsJoint.DistanceJoint:
  76223. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76224. break;
  76225. case BABYLON.PhysicsJoint.SpringJoint:
  76226. var springData = jointData;
  76227. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76228. restLength: springData.length,
  76229. stiffness: springData.stiffness,
  76230. damping: springData.damping,
  76231. localAnchorA: constraintData.pivotA,
  76232. localAnchorB: constraintData.pivotB
  76233. });
  76234. break;
  76235. case BABYLON.PhysicsJoint.LockJoint:
  76236. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76237. break;
  76238. case BABYLON.PhysicsJoint.PointToPointJoint:
  76239. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76240. default:
  76241. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76242. break;
  76243. }
  76244. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76245. constraint.collideConnected = !!jointData.collision;
  76246. impostorJoint.joint.physicsJoint = constraint;
  76247. //don't add spring as constraint, as it is not one.
  76248. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76249. this.world.addConstraint(constraint);
  76250. }
  76251. else {
  76252. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76253. constraint.applyForce();
  76254. });
  76255. }
  76256. };
  76257. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76258. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76259. };
  76260. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76261. var index;
  76262. var mat;
  76263. for (index = 0; index < this._physicsMaterials.length; index++) {
  76264. mat = this._physicsMaterials[index];
  76265. if (mat.friction === friction && mat.restitution === restitution) {
  76266. return mat;
  76267. }
  76268. }
  76269. var currentMat = new this.BJSCANNON.Material(name);
  76270. currentMat.friction = friction;
  76271. currentMat.restitution = restitution;
  76272. this._physicsMaterials.push(currentMat);
  76273. return currentMat;
  76274. };
  76275. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76276. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76277. };
  76278. CannonJSPlugin.prototype._createShape = function (impostor) {
  76279. var object = impostor.object;
  76280. var returnValue;
  76281. var extendSize = impostor.getObjectExtendSize();
  76282. switch (impostor.type) {
  76283. case BABYLON.PhysicsImpostor.SphereImpostor:
  76284. var radiusX = extendSize.x;
  76285. var radiusY = extendSize.y;
  76286. var radiusZ = extendSize.z;
  76287. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76288. break;
  76289. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76290. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76291. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76292. break;
  76293. case BABYLON.PhysicsImpostor.BoxImpostor:
  76294. var box = extendSize.scale(0.5);
  76295. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76296. break;
  76297. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76298. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76299. returnValue = new this.BJSCANNON.Plane();
  76300. break;
  76301. case BABYLON.PhysicsImpostor.MeshImpostor:
  76302. // should transform the vertex data to world coordinates!!
  76303. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76304. var rawFaces = object.getIndices ? object.getIndices() : [];
  76305. if (!rawVerts)
  76306. return;
  76307. // get only scale! so the object could transform correctly.
  76308. var oldPosition = object.position.clone();
  76309. var oldRotation = object.rotation && object.rotation.clone();
  76310. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76311. object.position.copyFromFloats(0, 0, 0);
  76312. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76313. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76314. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76315. var transform = object.computeWorldMatrix(true);
  76316. // convert rawVerts to object space
  76317. var temp = new Array();
  76318. var index;
  76319. for (index = 0; index < rawVerts.length; index += 3) {
  76320. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76321. }
  76322. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76323. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76324. //now set back the transformation!
  76325. object.position.copyFrom(oldPosition);
  76326. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76327. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76328. break;
  76329. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76330. var oldPosition2 = object.position.clone();
  76331. var oldRotation2 = object.rotation && object.rotation.clone();
  76332. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76333. object.position.copyFromFloats(0, 0, 0);
  76334. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76335. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76336. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76337. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76338. returnValue = this._createHeightmap(object);
  76339. object.position.copyFrom(oldPosition2);
  76340. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76341. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76342. object.computeWorldMatrix(true);
  76343. break;
  76344. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76345. returnValue = new this.BJSCANNON.Particle();
  76346. break;
  76347. }
  76348. return returnValue;
  76349. };
  76350. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76351. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76352. var transform = object.computeWorldMatrix(true);
  76353. // convert rawVerts to object space
  76354. var temp = new Array();
  76355. var index;
  76356. for (index = 0; index < pos.length; index += 3) {
  76357. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76358. }
  76359. pos = temp;
  76360. var matrix = new Array();
  76361. //For now pointDepth will not be used and will be automatically calculated.
  76362. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76363. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76364. var boundingInfo = object.getBoundingInfo();
  76365. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76366. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76367. var elementSize = dim * 2 / arraySize;
  76368. for (var i = 0; i < pos.length; i = i + 3) {
  76369. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76370. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76371. var y = -pos[i + 2] + minY;
  76372. if (!matrix[x]) {
  76373. matrix[x] = [];
  76374. }
  76375. if (!matrix[x][z]) {
  76376. matrix[x][z] = y;
  76377. }
  76378. matrix[x][z] = Math.max(y, matrix[x][z]);
  76379. }
  76380. for (var x = 0; x <= arraySize; ++x) {
  76381. if (!matrix[x]) {
  76382. var loc = 1;
  76383. while (!matrix[(x + loc) % arraySize]) {
  76384. loc++;
  76385. }
  76386. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76387. //console.log("missing x", x);
  76388. }
  76389. for (var z = 0; z <= arraySize; ++z) {
  76390. if (!matrix[x][z]) {
  76391. var loc = 1;
  76392. var newValue;
  76393. while (newValue === undefined) {
  76394. newValue = matrix[x][(z + loc++) % arraySize];
  76395. }
  76396. matrix[x][z] = newValue;
  76397. }
  76398. }
  76399. }
  76400. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76401. elementSize: elementSize
  76402. });
  76403. //For future reference, needed for body transformation
  76404. shape.minY = minY;
  76405. return shape;
  76406. };
  76407. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76408. var object = impostor.object;
  76409. //make sure it is updated...
  76410. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76411. // The delta between the mesh position and the mesh bounding box center
  76412. var bInfo = object.getBoundingInfo();
  76413. if (!bInfo)
  76414. return;
  76415. var center = impostor.getObjectCenter();
  76416. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76417. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76418. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76419. this._tmpPosition.copyFrom(center);
  76420. var quaternion = object.rotationQuaternion;
  76421. if (!quaternion) {
  76422. return;
  76423. }
  76424. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76425. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76426. //-90 DEG in X, precalculated
  76427. quaternion = quaternion.multiply(this._minus90X);
  76428. //Invert! (Precalculated, 90 deg in X)
  76429. //No need to clone. this will never change.
  76430. impostor.setDeltaRotation(this._plus90X);
  76431. }
  76432. //If it is a heightfield, if should be centered.
  76433. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76434. var mesh = object;
  76435. var boundingInfo = mesh.getBoundingInfo();
  76436. //calculate the correct body position:
  76437. var rotationQuaternion = mesh.rotationQuaternion;
  76438. mesh.rotationQuaternion = this._tmpUnityRotation;
  76439. mesh.computeWorldMatrix(true);
  76440. //get original center with no rotation
  76441. var c = center.clone();
  76442. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76443. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76444. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76445. mesh.setPreTransformMatrix(p);
  76446. mesh.computeWorldMatrix(true);
  76447. //calculate the translation
  76448. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76449. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76450. //add it inverted to the delta
  76451. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76452. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76453. //rotation is back
  76454. mesh.rotationQuaternion = rotationQuaternion;
  76455. mesh.setPreTransformMatrix(oldPivot);
  76456. mesh.computeWorldMatrix(true);
  76457. }
  76458. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76459. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76460. //this._tmpPosition.copyFrom(object.position);
  76461. }
  76462. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76463. //Now update the impostor object
  76464. impostor.physicsBody.position.copy(this._tmpPosition);
  76465. impostor.physicsBody.quaternion.copy(quaternion);
  76466. };
  76467. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76468. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76469. if (impostor.object.rotationQuaternion) {
  76470. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76471. }
  76472. };
  76473. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76474. impostor.physicsBody.position.copy(newPosition);
  76475. impostor.physicsBody.quaternion.copy(newRotation);
  76476. };
  76477. CannonJSPlugin.prototype.isSupported = function () {
  76478. return this.BJSCANNON !== undefined;
  76479. };
  76480. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76481. impostor.physicsBody.velocity.copy(velocity);
  76482. };
  76483. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76484. impostor.physicsBody.angularVelocity.copy(velocity);
  76485. };
  76486. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76487. var v = impostor.physicsBody.velocity;
  76488. if (!v) {
  76489. return null;
  76490. }
  76491. return new BABYLON.Vector3(v.x, v.y, v.z);
  76492. };
  76493. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76494. var v = impostor.physicsBody.angularVelocity;
  76495. if (!v) {
  76496. return null;
  76497. }
  76498. return new BABYLON.Vector3(v.x, v.y, v.z);
  76499. };
  76500. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76501. impostor.physicsBody.mass = mass;
  76502. impostor.physicsBody.updateMassProperties();
  76503. };
  76504. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76505. return impostor.physicsBody.mass;
  76506. };
  76507. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76508. return impostor.physicsBody.material.friction;
  76509. };
  76510. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76511. impostor.physicsBody.material.friction = friction;
  76512. };
  76513. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76514. return impostor.physicsBody.material.restitution;
  76515. };
  76516. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76517. impostor.physicsBody.material.restitution = restitution;
  76518. };
  76519. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76520. impostor.physicsBody.sleep();
  76521. };
  76522. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76523. impostor.physicsBody.wakeUp();
  76524. };
  76525. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76526. joint.physicsJoint.distance = maxDistance;
  76527. };
  76528. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76529. // if (!motorIndex) {
  76530. // joint.physicsJoint.enableMotor();
  76531. // }
  76532. // }
  76533. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76534. // if (!motorIndex) {
  76535. // joint.physicsJoint.disableMotor();
  76536. // }
  76537. // }
  76538. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76539. if (!motorIndex) {
  76540. joint.physicsJoint.enableMotor();
  76541. joint.physicsJoint.setMotorSpeed(speed);
  76542. if (maxForce) {
  76543. this.setLimit(joint, maxForce);
  76544. }
  76545. }
  76546. };
  76547. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76548. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76549. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76550. };
  76551. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76552. var body = impostor.physicsBody;
  76553. mesh.position.x = body.position.x;
  76554. mesh.position.y = body.position.y;
  76555. mesh.position.z = body.position.z;
  76556. if (mesh.rotationQuaternion) {
  76557. mesh.rotationQuaternion.x = body.quaternion.x;
  76558. mesh.rotationQuaternion.y = body.quaternion.y;
  76559. mesh.rotationQuaternion.z = body.quaternion.z;
  76560. mesh.rotationQuaternion.w = body.quaternion.w;
  76561. }
  76562. };
  76563. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76564. var shape = impostor.physicsBody.shapes[0];
  76565. return shape.boundingSphereRadius;
  76566. };
  76567. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76568. var shape = impostor.physicsBody.shapes[0];
  76569. result.x = shape.halfExtents.x * 2;
  76570. result.y = shape.halfExtents.y * 2;
  76571. result.z = shape.halfExtents.z * 2;
  76572. };
  76573. CannonJSPlugin.prototype.dispose = function () {
  76574. };
  76575. CannonJSPlugin.prototype._extendNamespace = function () {
  76576. //this will force cannon to execute at least one step when using interpolation
  76577. var step_tmp1 = new this.BJSCANNON.Vec3();
  76578. var Engine = this.BJSCANNON;
  76579. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76580. maxSubSteps = maxSubSteps || 10;
  76581. timeSinceLastCalled = timeSinceLastCalled || 0;
  76582. if (timeSinceLastCalled === 0) {
  76583. this.internalStep(dt);
  76584. this.time += dt;
  76585. }
  76586. else {
  76587. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76588. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76589. var t0 = performance.now();
  76590. for (var i = 0; i !== internalSteps; i++) {
  76591. this.internalStep(dt);
  76592. if (performance.now() - t0 > dt * 1000) {
  76593. break;
  76594. }
  76595. }
  76596. this.time += timeSinceLastCalled;
  76597. var h = this.time % dt;
  76598. var h_div_dt = h / dt;
  76599. var interpvelo = step_tmp1;
  76600. var bodies = this.bodies;
  76601. for (var j = 0; j !== bodies.length; j++) {
  76602. var b = bodies[j];
  76603. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76604. b.position.vsub(b.previousPosition, interpvelo);
  76605. interpvelo.scale(h_div_dt, interpvelo);
  76606. b.position.vadd(interpvelo, b.interpolatedPosition);
  76607. }
  76608. else {
  76609. b.interpolatedPosition.copy(b.position);
  76610. b.interpolatedQuaternion.copy(b.quaternion);
  76611. }
  76612. }
  76613. }
  76614. };
  76615. };
  76616. return CannonJSPlugin;
  76617. }());
  76618. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76619. })(BABYLON || (BABYLON = {}));
  76620. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76621. var BABYLON;
  76622. (function (BABYLON) {
  76623. var OimoJSPlugin = /** @class */ (function () {
  76624. function OimoJSPlugin(iterations) {
  76625. this.name = "OimoJSPlugin";
  76626. this._tmpImpostorsArray = [];
  76627. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76628. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76629. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76630. this.world.worldscale(1);
  76631. this.world.clear();
  76632. //making sure no stats are calculated
  76633. this.world.isNoStat = true;
  76634. }
  76635. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76636. this.world.gravity.copy(gravity);
  76637. };
  76638. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76639. this.world.timeStep = timeStep;
  76640. };
  76641. OimoJSPlugin.prototype.getTimeStep = function () {
  76642. return this.world.timeStep;
  76643. };
  76644. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76645. var _this = this;
  76646. impostors.forEach(function (impostor) {
  76647. impostor.beforeStep();
  76648. });
  76649. this.world.step();
  76650. impostors.forEach(function (impostor) {
  76651. impostor.afterStep();
  76652. //update the ordered impostors array
  76653. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76654. });
  76655. //check for collisions
  76656. var contact = this.world.contacts;
  76657. while (contact !== null) {
  76658. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76659. contact = contact.next;
  76660. continue;
  76661. }
  76662. //is this body colliding with any other? get the impostor
  76663. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76664. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76665. if (!mainImpostor || !collidingImpostor) {
  76666. contact = contact.next;
  76667. continue;
  76668. }
  76669. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76670. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76671. contact = contact.next;
  76672. }
  76673. };
  76674. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76675. var mass = impostor.physicsBody.massInfo.mass;
  76676. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76677. };
  76678. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76679. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76680. this.applyImpulse(impostor, force, contactPoint);
  76681. };
  76682. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76683. var _this = this;
  76684. //parent-child relationship. Does this impostor has a parent impostor?
  76685. if (impostor.parent) {
  76686. if (impostor.physicsBody) {
  76687. this.removePhysicsBody(impostor);
  76688. //TODO is that needed?
  76689. impostor.forceUpdate();
  76690. }
  76691. return;
  76692. }
  76693. if (impostor.isBodyInitRequired()) {
  76694. var bodyConfig = {
  76695. name: impostor.uniqueId,
  76696. //Oimo must have mass, also for static objects.
  76697. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76698. size: [],
  76699. type: [],
  76700. pos: [],
  76701. rot: [],
  76702. move: impostor.getParam("mass") !== 0,
  76703. //Supporting older versions of Oimo
  76704. world: this.world
  76705. };
  76706. var impostors = [impostor];
  76707. var addToArray = function (parent) {
  76708. if (!parent.getChildMeshes)
  76709. return;
  76710. parent.getChildMeshes().forEach(function (m) {
  76711. if (m.physicsImpostor) {
  76712. impostors.push(m.physicsImpostor);
  76713. //m.physicsImpostor._init();
  76714. }
  76715. });
  76716. };
  76717. addToArray(impostor.object);
  76718. var checkWithEpsilon_1 = function (value) {
  76719. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76720. };
  76721. impostors.forEach(function (i) {
  76722. if (!impostor.object.rotationQuaternion) {
  76723. return;
  76724. }
  76725. //get the correct bounding box
  76726. var oldQuaternion = i.object.rotationQuaternion;
  76727. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76728. x: impostor.object.rotationQuaternion.x,
  76729. y: impostor.object.rotationQuaternion.y,
  76730. z: impostor.object.rotationQuaternion.z,
  76731. s: impostor.object.rotationQuaternion.w
  76732. });
  76733. var extendSize = i.getObjectExtendSize();
  76734. if (i === impostor) {
  76735. var center = impostor.getObjectCenter();
  76736. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76737. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76738. //Can also use Array.prototype.push.apply
  76739. bodyConfig.pos.push(center.x);
  76740. bodyConfig.pos.push(center.y);
  76741. bodyConfig.pos.push(center.z);
  76742. //tmp solution
  76743. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76744. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76745. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76746. }
  76747. else {
  76748. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76749. bodyConfig.pos.push(localPosition.x);
  76750. bodyConfig.pos.push(localPosition.y);
  76751. bodyConfig.pos.push(localPosition.z);
  76752. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76753. bodyConfig.rot.push(0);
  76754. bodyConfig.rot.push(0);
  76755. bodyConfig.rot.push(0);
  76756. }
  76757. // register mesh
  76758. switch (i.type) {
  76759. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76760. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76761. case BABYLON.PhysicsImpostor.SphereImpostor:
  76762. var radiusX = extendSize.x;
  76763. var radiusY = extendSize.y;
  76764. var radiusZ = extendSize.z;
  76765. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76766. bodyConfig.type.push('sphere');
  76767. //due to the way oimo works with compounds, add 3 times
  76768. bodyConfig.size.push(size);
  76769. bodyConfig.size.push(size);
  76770. bodyConfig.size.push(size);
  76771. break;
  76772. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76773. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76774. var sizeY = checkWithEpsilon_1(extendSize.y);
  76775. bodyConfig.type.push('cylinder');
  76776. bodyConfig.size.push(sizeX);
  76777. bodyConfig.size.push(sizeY);
  76778. //due to the way oimo works with compounds, add one more value.
  76779. bodyConfig.size.push(sizeY);
  76780. break;
  76781. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76782. case BABYLON.PhysicsImpostor.BoxImpostor:
  76783. default:
  76784. var sizeX = checkWithEpsilon_1(extendSize.x);
  76785. var sizeY = checkWithEpsilon_1(extendSize.y);
  76786. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76787. bodyConfig.type.push('box');
  76788. bodyConfig.size.push(sizeX);
  76789. bodyConfig.size.push(sizeY);
  76790. bodyConfig.size.push(sizeZ);
  76791. break;
  76792. }
  76793. //actually not needed, but hey...
  76794. i.object.rotationQuaternion = oldQuaternion;
  76795. });
  76796. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76797. }
  76798. else {
  76799. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76800. }
  76801. impostor.setDeltaPosition(this._tmpPositionVector);
  76802. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76803. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76804. };
  76805. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76806. //impostor.physicsBody.dispose();
  76807. //Same as : (older oimo versions)
  76808. this.world.removeRigidBody(impostor.physicsBody);
  76809. };
  76810. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76811. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76812. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76813. if (!mainBody || !connectedBody) {
  76814. return;
  76815. }
  76816. var jointData = impostorJoint.joint.jointData;
  76817. var options = jointData.nativeParams || {};
  76818. var type;
  76819. var nativeJointData = {
  76820. body1: mainBody,
  76821. body2: connectedBody,
  76822. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76823. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76824. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76825. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76826. min: options.min,
  76827. max: options.max,
  76828. collision: options.collision || jointData.collision,
  76829. spring: options.spring,
  76830. //supporting older version of Oimo
  76831. world: this.world
  76832. };
  76833. switch (impostorJoint.joint.type) {
  76834. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76835. type = "jointBall";
  76836. break;
  76837. case BABYLON.PhysicsJoint.SpringJoint:
  76838. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76839. var springData = jointData;
  76840. nativeJointData.min = springData.length || nativeJointData.min;
  76841. //Max should also be set, just make sure it is at least min
  76842. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76843. case BABYLON.PhysicsJoint.DistanceJoint:
  76844. type = "jointDistance";
  76845. nativeJointData.max = jointData.maxDistance;
  76846. break;
  76847. case BABYLON.PhysicsJoint.PrismaticJoint:
  76848. type = "jointPrisme";
  76849. break;
  76850. case BABYLON.PhysicsJoint.SliderJoint:
  76851. type = "jointSlide";
  76852. break;
  76853. case BABYLON.PhysicsJoint.WheelJoint:
  76854. type = "jointWheel";
  76855. break;
  76856. case BABYLON.PhysicsJoint.HingeJoint:
  76857. default:
  76858. type = "jointHinge";
  76859. break;
  76860. }
  76861. nativeJointData.type = type;
  76862. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76863. };
  76864. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76865. //Bug in Oimo prevents us from disposing a joint in the playground
  76866. //joint.joint.physicsJoint.dispose();
  76867. //So we will bruteforce it!
  76868. try {
  76869. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76870. }
  76871. catch (e) {
  76872. BABYLON.Tools.Warn(e);
  76873. }
  76874. };
  76875. OimoJSPlugin.prototype.isSupported = function () {
  76876. return this.BJSOIMO !== undefined;
  76877. };
  76878. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76879. if (!impostor.physicsBody.sleeping) {
  76880. //TODO check that
  76881. if (impostor.physicsBody.shapes.next) {
  76882. var parentShape = this._getLastShape(impostor.physicsBody);
  76883. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76884. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76885. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76886. }
  76887. else {
  76888. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76889. }
  76890. if (impostor.object.rotationQuaternion) {
  76891. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76892. impostor.object.rotationQuaternion.normalize();
  76893. }
  76894. }
  76895. };
  76896. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76897. var body = impostor.physicsBody;
  76898. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76899. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76900. body.syncShapes();
  76901. body.awake();
  76902. };
  76903. OimoJSPlugin.prototype._getLastShape = function (body) {
  76904. var lastShape = body.shapes;
  76905. while (lastShape.next) {
  76906. lastShape = lastShape.next;
  76907. }
  76908. return lastShape;
  76909. };
  76910. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76911. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76912. };
  76913. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76914. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76915. };
  76916. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76917. var v = impostor.physicsBody.linearVelocity;
  76918. if (!v) {
  76919. return null;
  76920. }
  76921. return new BABYLON.Vector3(v.x, v.y, v.z);
  76922. };
  76923. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76924. var v = impostor.physicsBody.angularVelocity;
  76925. if (!v) {
  76926. return null;
  76927. }
  76928. return new BABYLON.Vector3(v.x, v.y, v.z);
  76929. };
  76930. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76931. var staticBody = mass === 0;
  76932. //this will actually set the body's density and not its mass.
  76933. //But this is how oimo treats the mass variable.
  76934. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76935. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76936. };
  76937. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76938. return impostor.physicsBody.shapes.density;
  76939. };
  76940. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76941. return impostor.physicsBody.shapes.friction;
  76942. };
  76943. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76944. impostor.physicsBody.shapes.friction = friction;
  76945. };
  76946. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76947. return impostor.physicsBody.shapes.restitution;
  76948. };
  76949. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76950. impostor.physicsBody.shapes.restitution = restitution;
  76951. };
  76952. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76953. impostor.physicsBody.sleep();
  76954. };
  76955. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76956. impostor.physicsBody.awake();
  76957. };
  76958. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76959. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76960. if (minDistance !== void 0) {
  76961. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76962. }
  76963. };
  76964. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76965. //TODO separate rotational and transational motors.
  76966. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76967. if (motor) {
  76968. motor.setMotor(speed, maxForce);
  76969. }
  76970. };
  76971. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76972. //TODO separate rotational and transational motors.
  76973. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76974. if (motor) {
  76975. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76976. }
  76977. };
  76978. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76979. var body = impostor.physicsBody;
  76980. mesh.position.x = body.position.x;
  76981. mesh.position.y = body.position.y;
  76982. mesh.position.z = body.position.z;
  76983. if (mesh.rotationQuaternion) {
  76984. mesh.rotationQuaternion.x = body.orientation.x;
  76985. mesh.rotationQuaternion.y = body.orientation.y;
  76986. mesh.rotationQuaternion.z = body.orientation.z;
  76987. mesh.rotationQuaternion.w = body.orientation.s;
  76988. }
  76989. };
  76990. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76991. return impostor.physicsBody.shapes.radius;
  76992. };
  76993. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76994. var shape = impostor.physicsBody.shapes;
  76995. result.x = shape.halfWidth * 2;
  76996. result.y = shape.halfHeight * 2;
  76997. result.z = shape.halfDepth * 2;
  76998. };
  76999. OimoJSPlugin.prototype.dispose = function () {
  77000. this.world.clear();
  77001. };
  77002. return OimoJSPlugin;
  77003. }());
  77004. BABYLON.OimoJSPlugin = OimoJSPlugin;
  77005. })(BABYLON || (BABYLON = {}));
  77006. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  77007. var BABYLON;
  77008. (function (BABYLON) {
  77009. /*
  77010. * Based on jsTGALoader - Javascript loader for TGA file
  77011. * By Vincent Thibault
  77012. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  77013. */
  77014. var TGATools = /** @class */ (function () {
  77015. function TGATools() {
  77016. }
  77017. TGATools.GetTGAHeader = function (data) {
  77018. var offset = 0;
  77019. var header = {
  77020. id_length: data[offset++],
  77021. colormap_type: data[offset++],
  77022. image_type: data[offset++],
  77023. colormap_index: data[offset++] | data[offset++] << 8,
  77024. colormap_length: data[offset++] | data[offset++] << 8,
  77025. colormap_size: data[offset++],
  77026. origin: [
  77027. data[offset++] | data[offset++] << 8,
  77028. data[offset++] | data[offset++] << 8
  77029. ],
  77030. width: data[offset++] | data[offset++] << 8,
  77031. height: data[offset++] | data[offset++] << 8,
  77032. pixel_size: data[offset++],
  77033. flags: data[offset++]
  77034. };
  77035. return header;
  77036. };
  77037. TGATools.UploadContent = function (gl, data) {
  77038. // Not enough data to contain header ?
  77039. if (data.length < 19) {
  77040. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  77041. return;
  77042. }
  77043. // Read Header
  77044. var offset = 18;
  77045. var header = TGATools.GetTGAHeader(data);
  77046. // Assume it's a valid Targa file.
  77047. if (header.id_length + offset > data.length) {
  77048. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  77049. return;
  77050. }
  77051. // Skip not needed data
  77052. offset += header.id_length;
  77053. var use_rle = false;
  77054. var use_pal = false;
  77055. var use_grey = false;
  77056. // Get some informations.
  77057. switch (header.image_type) {
  77058. case TGATools._TYPE_RLE_INDEXED:
  77059. use_rle = true;
  77060. case TGATools._TYPE_INDEXED:
  77061. use_pal = true;
  77062. break;
  77063. case TGATools._TYPE_RLE_RGB:
  77064. use_rle = true;
  77065. case TGATools._TYPE_RGB:
  77066. // use_rgb = true;
  77067. break;
  77068. case TGATools._TYPE_RLE_GREY:
  77069. use_rle = true;
  77070. case TGATools._TYPE_GREY:
  77071. use_grey = true;
  77072. break;
  77073. }
  77074. var pixel_data;
  77075. // var numAlphaBits = header.flags & 0xf;
  77076. var pixel_size = header.pixel_size >> 3;
  77077. var pixel_total = header.width * header.height * pixel_size;
  77078. // Read palettes
  77079. var palettes;
  77080. if (use_pal) {
  77081. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  77082. }
  77083. // Read LRE
  77084. if (use_rle) {
  77085. pixel_data = new Uint8Array(pixel_total);
  77086. var c, count, i;
  77087. var localOffset = 0;
  77088. var pixels = new Uint8Array(pixel_size);
  77089. while (offset < pixel_total && localOffset < pixel_total) {
  77090. c = data[offset++];
  77091. count = (c & 0x7f) + 1;
  77092. // RLE pixels
  77093. if (c & 0x80) {
  77094. // Bind pixel tmp array
  77095. for (i = 0; i < pixel_size; ++i) {
  77096. pixels[i] = data[offset++];
  77097. }
  77098. // Copy pixel array
  77099. for (i = 0; i < count; ++i) {
  77100. pixel_data.set(pixels, localOffset + i * pixel_size);
  77101. }
  77102. localOffset += pixel_size * count;
  77103. }
  77104. else {
  77105. count *= pixel_size;
  77106. for (i = 0; i < count; ++i) {
  77107. pixel_data[localOffset + i] = data[offset++];
  77108. }
  77109. localOffset += count;
  77110. }
  77111. }
  77112. }
  77113. else {
  77114. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  77115. }
  77116. // Load to texture
  77117. var x_start, y_start, x_step, y_step, y_end, x_end;
  77118. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  77119. default:
  77120. case TGATools._ORIGIN_UL:
  77121. x_start = 0;
  77122. x_step = 1;
  77123. x_end = header.width;
  77124. y_start = 0;
  77125. y_step = 1;
  77126. y_end = header.height;
  77127. break;
  77128. case TGATools._ORIGIN_BL:
  77129. x_start = 0;
  77130. x_step = 1;
  77131. x_end = header.width;
  77132. y_start = header.height - 1;
  77133. y_step = -1;
  77134. y_end = -1;
  77135. break;
  77136. case TGATools._ORIGIN_UR:
  77137. x_start = header.width - 1;
  77138. x_step = -1;
  77139. x_end = -1;
  77140. y_start = 0;
  77141. y_step = 1;
  77142. y_end = header.height;
  77143. break;
  77144. case TGATools._ORIGIN_BR:
  77145. x_start = header.width - 1;
  77146. x_step = -1;
  77147. x_end = -1;
  77148. y_start = header.height - 1;
  77149. y_step = -1;
  77150. y_end = -1;
  77151. break;
  77152. }
  77153. // Load the specify method
  77154. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  77155. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  77156. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  77157. };
  77158. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77159. var image = pixel_data, colormap = palettes;
  77160. var width = header.width, height = header.height;
  77161. var color, i = 0, x, y;
  77162. var imageData = new Uint8Array(width * height * 4);
  77163. for (y = y_start; y !== y_end; y += y_step) {
  77164. for (x = x_start; x !== x_end; x += x_step, i++) {
  77165. color = image[i];
  77166. imageData[(x + width * y) * 4 + 3] = 255;
  77167. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  77168. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  77169. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  77170. }
  77171. }
  77172. return imageData;
  77173. };
  77174. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77175. var image = pixel_data;
  77176. var width = header.width, height = header.height;
  77177. var color, i = 0, x, y;
  77178. var imageData = new Uint8Array(width * height * 4);
  77179. for (y = y_start; y !== y_end; y += y_step) {
  77180. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77181. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  77182. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  77183. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  77184. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  77185. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  77186. }
  77187. }
  77188. return imageData;
  77189. };
  77190. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77191. var image = pixel_data;
  77192. var width = header.width, height = header.height;
  77193. var i = 0, x, y;
  77194. var imageData = new Uint8Array(width * height * 4);
  77195. for (y = y_start; y !== y_end; y += y_step) {
  77196. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  77197. imageData[(x + width * y) * 4 + 3] = 255;
  77198. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77199. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77200. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77201. }
  77202. }
  77203. return imageData;
  77204. };
  77205. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77206. var image = pixel_data;
  77207. var width = header.width, height = header.height;
  77208. var i = 0, x, y;
  77209. var imageData = new Uint8Array(width * height * 4);
  77210. for (y = y_start; y !== y_end; y += y_step) {
  77211. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  77212. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77213. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  77214. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  77215. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  77216. }
  77217. }
  77218. return imageData;
  77219. };
  77220. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77221. var image = pixel_data;
  77222. var width = header.width, height = header.height;
  77223. var color, i = 0, x, y;
  77224. var imageData = new Uint8Array(width * height * 4);
  77225. for (y = y_start; y !== y_end; y += y_step) {
  77226. for (x = x_start; x !== x_end; x += x_step, i++) {
  77227. color = image[i];
  77228. imageData[(x + width * y) * 4 + 0] = color;
  77229. imageData[(x + width * y) * 4 + 1] = color;
  77230. imageData[(x + width * y) * 4 + 2] = color;
  77231. imageData[(x + width * y) * 4 + 3] = 255;
  77232. }
  77233. }
  77234. return imageData;
  77235. };
  77236. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77237. var image = pixel_data;
  77238. var width = header.width, height = header.height;
  77239. var i = 0, x, y;
  77240. var imageData = new Uint8Array(width * height * 4);
  77241. for (y = y_start; y !== y_end; y += y_step) {
  77242. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77243. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77244. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77245. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77246. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77247. }
  77248. }
  77249. return imageData;
  77250. };
  77251. //private static _TYPE_NO_DATA = 0;
  77252. TGATools._TYPE_INDEXED = 1;
  77253. TGATools._TYPE_RGB = 2;
  77254. TGATools._TYPE_GREY = 3;
  77255. TGATools._TYPE_RLE_INDEXED = 9;
  77256. TGATools._TYPE_RLE_RGB = 10;
  77257. TGATools._TYPE_RLE_GREY = 11;
  77258. TGATools._ORIGIN_MASK = 0x30;
  77259. TGATools._ORIGIN_SHIFT = 0x04;
  77260. TGATools._ORIGIN_BL = 0x00;
  77261. TGATools._ORIGIN_BR = 0x01;
  77262. TGATools._ORIGIN_UL = 0x02;
  77263. TGATools._ORIGIN_UR = 0x03;
  77264. return TGATools;
  77265. }());
  77266. BABYLON.TGATools = TGATools;
  77267. })(BABYLON || (BABYLON = {}));
  77268. //# sourceMappingURL=babylon.tga.js.map
  77269. var BABYLON;
  77270. (function (BABYLON) {
  77271. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77272. // All values and structures referenced from:
  77273. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77274. var DDS_MAGIC = 0x20534444;
  77275. var
  77276. //DDSD_CAPS = 0x1,
  77277. //DDSD_HEIGHT = 0x2,
  77278. //DDSD_WIDTH = 0x4,
  77279. //DDSD_PITCH = 0x8,
  77280. //DDSD_PIXELFORMAT = 0x1000,
  77281. DDSD_MIPMAPCOUNT = 0x20000;
  77282. //DDSD_LINEARSIZE = 0x80000,
  77283. //DDSD_DEPTH = 0x800000;
  77284. // var DDSCAPS_COMPLEX = 0x8,
  77285. // DDSCAPS_MIPMAP = 0x400000,
  77286. // DDSCAPS_TEXTURE = 0x1000;
  77287. var DDSCAPS2_CUBEMAP = 0x200;
  77288. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77289. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77290. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77291. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77292. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77293. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77294. // DDSCAPS2_VOLUME = 0x200000;
  77295. var
  77296. //DDPF_ALPHAPIXELS = 0x1,
  77297. //DDPF_ALPHA = 0x2,
  77298. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77299. //DDPF_YUV = 0x200,
  77300. DDPF_LUMINANCE = 0x20000;
  77301. function FourCCToInt32(value) {
  77302. return value.charCodeAt(0) +
  77303. (value.charCodeAt(1) << 8) +
  77304. (value.charCodeAt(2) << 16) +
  77305. (value.charCodeAt(3) << 24);
  77306. }
  77307. function Int32ToFourCC(value) {
  77308. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77309. }
  77310. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77311. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77312. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77313. var FOURCC_DX10 = FourCCToInt32("DX10");
  77314. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77315. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77316. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77317. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77318. var headerLengthInt = 31; // The header length in 32 bit ints
  77319. // Offsets into the header array
  77320. var off_magic = 0;
  77321. var off_size = 1;
  77322. var off_flags = 2;
  77323. var off_height = 3;
  77324. var off_width = 4;
  77325. var off_mipmapCount = 7;
  77326. var off_pfFlags = 20;
  77327. var off_pfFourCC = 21;
  77328. var off_RGBbpp = 22;
  77329. var off_RMask = 23;
  77330. var off_GMask = 24;
  77331. var off_BMask = 25;
  77332. var off_AMask = 26;
  77333. // var off_caps1 = 27;
  77334. var off_caps2 = 28;
  77335. // var off_caps3 = 29;
  77336. // var off_caps4 = 30;
  77337. var off_dxgiFormat = 32;
  77338. ;
  77339. var DDSTools = /** @class */ (function () {
  77340. function DDSTools() {
  77341. }
  77342. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77343. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77344. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77345. var mipmapCount = 1;
  77346. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77347. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77348. }
  77349. var fourCC = header[off_pfFourCC];
  77350. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77351. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77352. switch (fourCC) {
  77353. case FOURCC_D3DFMT_R16G16B16A16F:
  77354. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77355. break;
  77356. case FOURCC_D3DFMT_R32G32B32A32F:
  77357. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77358. break;
  77359. case FOURCC_DX10:
  77360. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77361. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77362. break;
  77363. }
  77364. }
  77365. return {
  77366. width: header[off_width],
  77367. height: header[off_height],
  77368. mipmapCount: mipmapCount,
  77369. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77370. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77371. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77372. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77373. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77374. dxgiFormat: dxgiFormat,
  77375. textureType: textureType
  77376. };
  77377. };
  77378. DDSTools._ToHalfFloat = function (value) {
  77379. if (!DDSTools._FloatView) {
  77380. DDSTools._FloatView = new Float32Array(1);
  77381. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77382. }
  77383. DDSTools._FloatView[0] = value;
  77384. var x = DDSTools._Int32View[0];
  77385. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77386. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77387. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77388. /* If zero, or denormal, or exponent underflows too much for a denormal
  77389. * half, return signed zero. */
  77390. if (e < 103) {
  77391. return bits;
  77392. }
  77393. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77394. if (e > 142) {
  77395. bits |= 0x7c00;
  77396. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77397. * not Inf, so make sure we set one mantissa bit too. */
  77398. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77399. return bits;
  77400. }
  77401. /* If exponent underflows but not too much, return a denormal */
  77402. if (e < 113) {
  77403. m |= 0x0800;
  77404. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77405. * to 1, which is OK. */
  77406. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77407. return bits;
  77408. }
  77409. bits |= ((e - 112) << 10) | (m >> 1);
  77410. bits += m & 1;
  77411. return bits;
  77412. };
  77413. DDSTools._FromHalfFloat = function (value) {
  77414. var s = (value & 0x8000) >> 15;
  77415. var e = (value & 0x7C00) >> 10;
  77416. var f = value & 0x03FF;
  77417. if (e === 0) {
  77418. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77419. }
  77420. else if (e == 0x1F) {
  77421. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77422. }
  77423. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77424. };
  77425. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77426. var destArray = new Float32Array(dataLength);
  77427. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77428. var index = 0;
  77429. for (var y = 0; y < height; y++) {
  77430. for (var x = 0; x < width; x++) {
  77431. var srcPos = (x + y * width) * 4;
  77432. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77433. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77434. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77435. if (DDSTools.StoreLODInAlphaChannel) {
  77436. destArray[index + 3] = lod;
  77437. }
  77438. else {
  77439. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77440. }
  77441. index += 4;
  77442. }
  77443. }
  77444. return destArray;
  77445. };
  77446. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77447. if (DDSTools.StoreLODInAlphaChannel) {
  77448. var destArray = new Uint16Array(dataLength);
  77449. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77450. var index = 0;
  77451. for (var y = 0; y < height; y++) {
  77452. for (var x = 0; x < width; x++) {
  77453. var srcPos = (x + y * width) * 4;
  77454. destArray[index] = srcData[srcPos];
  77455. destArray[index + 1] = srcData[srcPos + 1];
  77456. destArray[index + 2] = srcData[srcPos + 2];
  77457. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77458. index += 4;
  77459. }
  77460. }
  77461. return destArray;
  77462. }
  77463. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77464. };
  77465. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77466. if (DDSTools.StoreLODInAlphaChannel) {
  77467. var destArray = new Float32Array(dataLength);
  77468. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77469. var index = 0;
  77470. for (var y = 0; y < height; y++) {
  77471. for (var x = 0; x < width; x++) {
  77472. var srcPos = (x + y * width) * 4;
  77473. destArray[index] = srcData[srcPos];
  77474. destArray[index + 1] = srcData[srcPos + 1];
  77475. destArray[index + 2] = srcData[srcPos + 2];
  77476. destArray[index + 3] = lod;
  77477. index += 4;
  77478. }
  77479. }
  77480. return destArray;
  77481. }
  77482. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77483. };
  77484. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77485. var destArray = new Uint8Array(dataLength);
  77486. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77487. var index = 0;
  77488. for (var y = 0; y < height; y++) {
  77489. for (var x = 0; x < width; x++) {
  77490. var srcPos = (x + y * width) * 4;
  77491. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77492. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77493. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77494. if (DDSTools.StoreLODInAlphaChannel) {
  77495. destArray[index + 3] = lod;
  77496. }
  77497. else {
  77498. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77499. }
  77500. index += 4;
  77501. }
  77502. }
  77503. return destArray;
  77504. };
  77505. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77506. var destArray = new Uint8Array(dataLength);
  77507. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77508. var index = 0;
  77509. for (var y = 0; y < height; y++) {
  77510. for (var x = 0; x < width; x++) {
  77511. var srcPos = (x + y * width) * 4;
  77512. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77513. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77514. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77515. if (DDSTools.StoreLODInAlphaChannel) {
  77516. destArray[index + 3] = lod;
  77517. }
  77518. else {
  77519. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77520. }
  77521. index += 4;
  77522. }
  77523. }
  77524. return destArray;
  77525. };
  77526. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77527. var byteArray = new Uint8Array(dataLength);
  77528. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77529. var index = 0;
  77530. for (var y = 0; y < height; y++) {
  77531. for (var x = 0; x < width; x++) {
  77532. var srcPos = (x + y * width) * 4;
  77533. byteArray[index] = srcData[srcPos + rOffset];
  77534. byteArray[index + 1] = srcData[srcPos + gOffset];
  77535. byteArray[index + 2] = srcData[srcPos + bOffset];
  77536. byteArray[index + 3] = srcData[srcPos + aOffset];
  77537. index += 4;
  77538. }
  77539. }
  77540. return byteArray;
  77541. };
  77542. DDSTools._ExtractLongWordOrder = function (value) {
  77543. if (value === 0 || value === 255 || value === -16777216) {
  77544. return 0;
  77545. }
  77546. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77547. };
  77548. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77549. var byteArray = new Uint8Array(dataLength);
  77550. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77551. var index = 0;
  77552. for (var y = 0; y < height; y++) {
  77553. for (var x = 0; x < width; x++) {
  77554. var srcPos = (x + y * width) * 3;
  77555. byteArray[index] = srcData[srcPos + rOffset];
  77556. byteArray[index + 1] = srcData[srcPos + gOffset];
  77557. byteArray[index + 2] = srcData[srcPos + bOffset];
  77558. index += 3;
  77559. }
  77560. }
  77561. return byteArray;
  77562. };
  77563. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77564. var byteArray = new Uint8Array(dataLength);
  77565. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77566. var index = 0;
  77567. for (var y = 0; y < height; y++) {
  77568. for (var x = 0; x < width; x++) {
  77569. var srcPos = (x + y * width);
  77570. byteArray[index] = srcData[srcPos];
  77571. index++;
  77572. }
  77573. }
  77574. return byteArray;
  77575. };
  77576. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77577. if (lodIndex === void 0) { lodIndex = -1; }
  77578. var ext = engine.getCaps().s3tc;
  77579. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77580. var fourCC, width, height, dataLength = 0, dataOffset;
  77581. var byteArray, mipmapCount, mip;
  77582. var internalFormat = 0;
  77583. var format = 0;
  77584. var blockBytes = 1;
  77585. if (header[off_magic] !== DDS_MAGIC) {
  77586. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77587. return;
  77588. }
  77589. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77590. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77591. return;
  77592. }
  77593. if (info.isCompressed && !ext) {
  77594. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77595. return;
  77596. }
  77597. var bpp = header[off_RGBbpp];
  77598. dataOffset = header[off_size] + 4;
  77599. var computeFormats = false;
  77600. if (info.isFourCC) {
  77601. fourCC = header[off_pfFourCC];
  77602. switch (fourCC) {
  77603. case FOURCC_DXT1:
  77604. blockBytes = 8;
  77605. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77606. break;
  77607. case FOURCC_DXT3:
  77608. blockBytes = 16;
  77609. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77610. break;
  77611. case FOURCC_DXT5:
  77612. blockBytes = 16;
  77613. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77614. break;
  77615. case FOURCC_D3DFMT_R16G16B16A16F:
  77616. computeFormats = true;
  77617. break;
  77618. case FOURCC_D3DFMT_R32G32B32A32F:
  77619. computeFormats = true;
  77620. break;
  77621. case FOURCC_DX10:
  77622. // There is an additionnal header so dataOffset need to be changed
  77623. dataOffset += 5 * 4; // 5 uints
  77624. var supported = false;
  77625. switch (info.dxgiFormat) {
  77626. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77627. computeFormats = true;
  77628. supported = true;
  77629. break;
  77630. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77631. info.isRGB = true;
  77632. info.isFourCC = false;
  77633. bpp = 32;
  77634. supported = true;
  77635. break;
  77636. }
  77637. if (supported) {
  77638. break;
  77639. }
  77640. default:
  77641. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77642. return;
  77643. }
  77644. }
  77645. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77646. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77647. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77648. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77649. if (computeFormats) {
  77650. format = engine._getWebGLTextureType(info.textureType);
  77651. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77652. }
  77653. mipmapCount = 1;
  77654. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77655. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77656. }
  77657. for (var face = 0; face < faces; face++) {
  77658. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77659. width = header[off_width];
  77660. height = header[off_height];
  77661. for (mip = 0; mip < mipmapCount; ++mip) {
  77662. if (lodIndex === -1 || lodIndex === mip) {
  77663. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77664. var i = (lodIndex === -1) ? mip : 0;
  77665. if (!info.isCompressed && info.isFourCC) {
  77666. dataLength = width * height * 4;
  77667. var floatArray = null;
  77668. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77669. if (bpp === 128) {
  77670. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77671. }
  77672. else if (bpp === 64) {
  77673. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77674. }
  77675. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77676. format = engine._getWebGLTextureType(info.textureType);
  77677. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77678. }
  77679. else {
  77680. if (bpp === 128) {
  77681. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77682. }
  77683. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77684. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77685. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77686. format = engine._getWebGLTextureType(info.textureType);
  77687. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77688. }
  77689. else {
  77690. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77691. }
  77692. }
  77693. if (floatArray) {
  77694. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77695. }
  77696. }
  77697. else if (info.isRGB) {
  77698. if (bpp === 24) {
  77699. dataLength = width * height * 3;
  77700. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77701. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77702. }
  77703. else {
  77704. dataLength = width * height * 4;
  77705. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77706. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77707. }
  77708. }
  77709. else if (info.isLuminance) {
  77710. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77711. var unpaddedRowSize = width;
  77712. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77713. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77714. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77715. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77716. }
  77717. else {
  77718. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77719. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77720. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77721. }
  77722. }
  77723. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77724. width *= 0.5;
  77725. height *= 0.5;
  77726. width = Math.max(1.0, width);
  77727. height = Math.max(1.0, height);
  77728. }
  77729. if (currentFace !== undefined) {
  77730. // Loading a single face
  77731. break;
  77732. }
  77733. }
  77734. };
  77735. DDSTools.StoreLODInAlphaChannel = false;
  77736. return DDSTools;
  77737. }());
  77738. BABYLON.DDSTools = DDSTools;
  77739. })(BABYLON || (BABYLON = {}));
  77740. //# sourceMappingURL=babylon.dds.js.map
  77741. var BABYLON;
  77742. (function (BABYLON) {
  77743. /**
  77744. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77745. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77746. */
  77747. var KhronosTextureContainer = /** @class */ (function () {
  77748. /**
  77749. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77750. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77751. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77752. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77753. */
  77754. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77755. this.arrayBuffer = arrayBuffer;
  77756. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77757. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77758. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77759. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77760. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77761. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77762. BABYLON.Tools.Error("texture missing KTX identifier");
  77763. return;
  77764. }
  77765. // load the reset of the header in native 32 bit int
  77766. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77767. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77768. var oppositeEndianess = header[0] === 0x01020304;
  77769. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77770. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77771. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77772. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77773. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77774. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77775. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77776. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77777. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77778. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77779. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77780. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77781. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77782. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77783. if (this.glType !== 0) {
  77784. BABYLON.Tools.Error("only compressed formats currently supported");
  77785. return;
  77786. }
  77787. else {
  77788. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77789. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77790. }
  77791. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77792. BABYLON.Tools.Error("only 2D textures currently supported");
  77793. return;
  77794. }
  77795. if (this.numberOfArrayElements !== 0) {
  77796. BABYLON.Tools.Error("texture arrays not currently supported");
  77797. return;
  77798. }
  77799. if (this.numberOfFaces !== facesExpected) {
  77800. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77801. return;
  77802. }
  77803. // we now have a completely validated file, so could use existence of loadType as success
  77804. // would need to make this more elaborate & adjust checks above to support more than one load type
  77805. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77806. }
  77807. // not as fast hardware based, but will probably never need to use
  77808. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77809. return ((val & 0xFF) << 24)
  77810. | ((val & 0xFF00) << 8)
  77811. | ((val >> 8) & 0xFF00)
  77812. | ((val >> 24) & 0xFF);
  77813. };
  77814. /**
  77815. * It is assumed that the texture has already been created & is currently bound
  77816. */
  77817. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77818. switch (this.loadType) {
  77819. case KhronosTextureContainer.COMPRESSED_2D:
  77820. this._upload2DCompressedLevels(gl, loadMipmaps);
  77821. break;
  77822. case KhronosTextureContainer.TEX_2D:
  77823. case KhronosTextureContainer.COMPRESSED_3D:
  77824. case KhronosTextureContainer.TEX_3D:
  77825. }
  77826. };
  77827. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77828. // initialize width & height for level 1
  77829. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77830. var width = this.pixelWidth;
  77831. var height = this.pixelHeight;
  77832. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77833. for (var level = 0; level < mipmapCount; level++) {
  77834. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77835. for (var face = 0; face < this.numberOfFaces; face++) {
  77836. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77837. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77838. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77839. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77840. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77841. }
  77842. width = Math.max(1.0, width * 0.5);
  77843. height = Math.max(1.0, height * 0.5);
  77844. }
  77845. };
  77846. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77847. // load types
  77848. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77849. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77850. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77851. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77852. return KhronosTextureContainer;
  77853. }());
  77854. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77855. })(BABYLON || (BABYLON = {}));
  77856. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77857. var BABYLON;
  77858. (function (BABYLON) {
  77859. var Debug = /** @class */ (function () {
  77860. function Debug() {
  77861. }
  77862. Debug.AxesViewer = /** @class */ (function () {
  77863. function AxesViewer(scene, scaleLines) {
  77864. if (scaleLines === void 0) { scaleLines = 1; }
  77865. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77866. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77867. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77868. this.scaleLines = 1;
  77869. this.scaleLines = scaleLines;
  77870. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77871. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77872. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77873. this._xmesh.renderingGroupId = 2;
  77874. this._ymesh.renderingGroupId = 2;
  77875. this._zmesh.renderingGroupId = 2;
  77876. this._xmesh.material.checkReadyOnlyOnce = true;
  77877. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77878. this._ymesh.material.checkReadyOnlyOnce = true;
  77879. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77880. this._zmesh.material.checkReadyOnlyOnce = true;
  77881. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77882. this.scene = scene;
  77883. }
  77884. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77885. var scaleLines = this.scaleLines;
  77886. if (this._xmesh) {
  77887. this._xmesh.position.copyFrom(position);
  77888. }
  77889. if (this._ymesh) {
  77890. this._ymesh.position.copyFrom(position);
  77891. }
  77892. if (this._zmesh) {
  77893. this._zmesh.position.copyFrom(position);
  77894. }
  77895. var point2 = this._xline[1];
  77896. point2.x = xaxis.x * scaleLines;
  77897. point2.y = xaxis.y * scaleLines;
  77898. point2.z = xaxis.z * scaleLines;
  77899. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77900. point2 = this._yline[1];
  77901. point2.x = yaxis.x * scaleLines;
  77902. point2.y = yaxis.y * scaleLines;
  77903. point2.z = yaxis.z * scaleLines;
  77904. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77905. point2 = this._zline[1];
  77906. point2.x = zaxis.x * scaleLines;
  77907. point2.y = zaxis.y * scaleLines;
  77908. point2.z = zaxis.z * scaleLines;
  77909. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77910. };
  77911. AxesViewer.prototype.dispose = function () {
  77912. if (this._xmesh) {
  77913. this._xmesh.dispose();
  77914. }
  77915. if (this._ymesh) {
  77916. this._ymesh.dispose();
  77917. }
  77918. if (this._zmesh) {
  77919. this._zmesh.dispose();
  77920. }
  77921. this._xmesh = null;
  77922. this._ymesh = null;
  77923. this._zmesh = null;
  77924. this.scene = null;
  77925. };
  77926. return AxesViewer;
  77927. }());
  77928. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77929. __extends(BoneAxesViewer, _super);
  77930. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77931. if (scaleLines === void 0) { scaleLines = 1; }
  77932. var _this = _super.call(this, scene, scaleLines) || this;
  77933. _this.pos = BABYLON.Vector3.Zero();
  77934. _this.xaxis = BABYLON.Vector3.Zero();
  77935. _this.yaxis = BABYLON.Vector3.Zero();
  77936. _this.zaxis = BABYLON.Vector3.Zero();
  77937. _this.mesh = mesh;
  77938. _this.bone = bone;
  77939. return _this;
  77940. }
  77941. BoneAxesViewer.prototype.update = function () {
  77942. if (!this.mesh || !this.bone) {
  77943. return;
  77944. }
  77945. var bone = this.bone;
  77946. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77947. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77948. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77949. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77950. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77951. };
  77952. BoneAxesViewer.prototype.dispose = function () {
  77953. if (this.mesh) {
  77954. this.mesh = null;
  77955. this.bone = null;
  77956. _super.prototype.dispose.call(this);
  77957. }
  77958. };
  77959. return BoneAxesViewer;
  77960. }(Debug.AxesViewer));
  77961. Debug.PhysicsViewer = /** @class */ (function () {
  77962. function PhysicsViewer(scene) {
  77963. this._impostors = [];
  77964. this._meshes = [];
  77965. this._numMeshes = 0;
  77966. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77967. var physicEngine = this._scene.getPhysicsEngine();
  77968. if (physicEngine) {
  77969. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77970. }
  77971. }
  77972. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77973. var plugin = this._physicsEnginePlugin;
  77974. for (var i = 0; i < this._numMeshes; i++) {
  77975. var impostor = this._impostors[i];
  77976. if (!impostor) {
  77977. continue;
  77978. }
  77979. if (impostor.isDisposed) {
  77980. this.hideImpostor(this._impostors[i--]);
  77981. }
  77982. else {
  77983. var mesh = this._meshes[i];
  77984. if (mesh && plugin) {
  77985. plugin.syncMeshWithImpostor(mesh, impostor);
  77986. }
  77987. }
  77988. }
  77989. };
  77990. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77991. if (!this._scene) {
  77992. return;
  77993. }
  77994. for (var i = 0; i < this._numMeshes; i++) {
  77995. if (this._impostors[i] == impostor) {
  77996. return;
  77997. }
  77998. }
  77999. var debugMesh = this._getDebugMesh(impostor, this._scene);
  78000. if (debugMesh) {
  78001. this._impostors[this._numMeshes] = impostor;
  78002. this._meshes[this._numMeshes] = debugMesh;
  78003. if (this._numMeshes === 0) {
  78004. this._renderFunction = this._updateDebugMeshes.bind(this);
  78005. this._scene.registerBeforeRender(this._renderFunction);
  78006. }
  78007. this._numMeshes++;
  78008. }
  78009. };
  78010. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  78011. if (!impostor || !this._scene) {
  78012. return;
  78013. }
  78014. var removed = false;
  78015. for (var i = 0; i < this._numMeshes; i++) {
  78016. if (this._impostors[i] == impostor) {
  78017. var mesh = this._meshes[i];
  78018. if (!mesh) {
  78019. continue;
  78020. }
  78021. this._scene.removeMesh(mesh);
  78022. mesh.dispose();
  78023. this._numMeshes--;
  78024. if (this._numMeshes > 0) {
  78025. this._meshes[i] = this._meshes[this._numMeshes];
  78026. this._impostors[i] = this._impostors[this._numMeshes];
  78027. this._meshes[this._numMeshes] = null;
  78028. this._impostors[this._numMeshes] = null;
  78029. }
  78030. else {
  78031. this._meshes[0] = null;
  78032. this._impostors[0] = null;
  78033. }
  78034. removed = true;
  78035. break;
  78036. }
  78037. }
  78038. if (removed && this._numMeshes === 0) {
  78039. this._scene.unregisterBeforeRender(this._renderFunction);
  78040. }
  78041. };
  78042. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  78043. if (!this._debugMaterial) {
  78044. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  78045. this._debugMaterial.wireframe = true;
  78046. }
  78047. return this._debugMaterial;
  78048. };
  78049. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  78050. if (!this._debugBoxMesh) {
  78051. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  78052. this._debugBoxMesh.renderingGroupId = 1;
  78053. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78054. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  78055. scene.removeMesh(this._debugBoxMesh);
  78056. }
  78057. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  78058. };
  78059. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  78060. if (!this._debugSphereMesh) {
  78061. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  78062. this._debugSphereMesh.renderingGroupId = 1;
  78063. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  78064. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  78065. scene.removeMesh(this._debugSphereMesh);
  78066. }
  78067. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  78068. };
  78069. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  78070. var mesh = null;
  78071. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  78072. mesh = this._getDebugBoxMesh(scene);
  78073. impostor.getBoxSizeToRef(mesh.scaling);
  78074. }
  78075. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  78076. mesh = this._getDebugSphereMesh(scene);
  78077. var radius = impostor.getRadius();
  78078. mesh.scaling.x = radius * 2;
  78079. mesh.scaling.y = radius * 2;
  78080. mesh.scaling.z = radius * 2;
  78081. }
  78082. return mesh;
  78083. };
  78084. PhysicsViewer.prototype.dispose = function () {
  78085. for (var i = 0; i < this._numMeshes; i++) {
  78086. this.hideImpostor(this._impostors[i]);
  78087. }
  78088. if (this._debugBoxMesh) {
  78089. this._debugBoxMesh.dispose();
  78090. }
  78091. if (this._debugSphereMesh) {
  78092. this._debugSphereMesh.dispose();
  78093. }
  78094. if (this._debugMaterial) {
  78095. this._debugMaterial.dispose();
  78096. }
  78097. this._impostors.length = 0;
  78098. this._scene = null;
  78099. this._physicsEnginePlugin = null;
  78100. };
  78101. return PhysicsViewer;
  78102. }());
  78103. Debug.SkeletonViewer = /** @class */ (function () {
  78104. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  78105. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  78106. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  78107. this.skeleton = skeleton;
  78108. this.mesh = mesh;
  78109. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  78110. this.renderingGroupId = renderingGroupId;
  78111. this.color = BABYLON.Color3.White();
  78112. this._debugLines = new Array();
  78113. this._isEnabled = false;
  78114. this._scene = scene;
  78115. this.update();
  78116. this._renderFunction = this.update.bind(this);
  78117. }
  78118. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  78119. get: function () {
  78120. return this._isEnabled;
  78121. },
  78122. set: function (value) {
  78123. if (this._isEnabled === value) {
  78124. return;
  78125. }
  78126. this._isEnabled = value;
  78127. if (value) {
  78128. this._scene.registerBeforeRender(this._renderFunction);
  78129. }
  78130. else {
  78131. this._scene.unregisterBeforeRender(this._renderFunction);
  78132. }
  78133. },
  78134. enumerable: true,
  78135. configurable: true
  78136. });
  78137. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  78138. if (x === void 0) { x = 0; }
  78139. if (y === void 0) { y = 0; }
  78140. if (z === void 0) { z = 0; }
  78141. var tmat = BABYLON.Tmp.Matrix[0];
  78142. var parentBone = bone.getParent();
  78143. tmat.copyFrom(bone.getLocalMatrix());
  78144. if (x !== 0 || y !== 0 || z !== 0) {
  78145. var tmat2 = BABYLON.Tmp.Matrix[1];
  78146. BABYLON.Matrix.IdentityToRef(tmat2);
  78147. tmat2.m[12] = x;
  78148. tmat2.m[13] = y;
  78149. tmat2.m[14] = z;
  78150. tmat2.multiplyToRef(tmat, tmat);
  78151. }
  78152. if (parentBone) {
  78153. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  78154. }
  78155. tmat.multiplyToRef(meshMat, tmat);
  78156. position.x = tmat.m[12];
  78157. position.y = tmat.m[13];
  78158. position.z = tmat.m[14];
  78159. };
  78160. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  78161. var len = bones.length;
  78162. var meshPos = this.mesh.position;
  78163. for (var i = 0; i < len; i++) {
  78164. var bone = bones[i];
  78165. var points = this._debugLines[i];
  78166. if (!points) {
  78167. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78168. this._debugLines[i] = points;
  78169. }
  78170. this._getBonePosition(points[0], bone, meshMat);
  78171. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  78172. points[0].subtractInPlace(meshPos);
  78173. points[1].subtractInPlace(meshPos);
  78174. }
  78175. };
  78176. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  78177. var len = bones.length;
  78178. var boneNum = 0;
  78179. var meshPos = this.mesh.position;
  78180. for (var i = len - 1; i >= 0; i--) {
  78181. var childBone = bones[i];
  78182. var parentBone = childBone.getParent();
  78183. if (!parentBone) {
  78184. continue;
  78185. }
  78186. var points = this._debugLines[boneNum];
  78187. if (!points) {
  78188. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78189. this._debugLines[boneNum] = points;
  78190. }
  78191. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  78192. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  78193. points[0].subtractInPlace(meshPos);
  78194. points[1].subtractInPlace(meshPos);
  78195. boneNum++;
  78196. }
  78197. };
  78198. SkeletonViewer.prototype.update = function () {
  78199. if (this.autoUpdateBonesMatrices) {
  78200. this.skeleton.computeAbsoluteTransforms();
  78201. }
  78202. if (this.skeleton.bones[0].length === undefined) {
  78203. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78204. }
  78205. else {
  78206. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  78207. }
  78208. if (!this._debugMesh) {
  78209. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  78210. this._debugMesh.renderingGroupId = this.renderingGroupId;
  78211. }
  78212. else {
  78213. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  78214. }
  78215. this._debugMesh.position.copyFrom(this.mesh.position);
  78216. this._debugMesh.color = this.color;
  78217. };
  78218. SkeletonViewer.prototype.dispose = function () {
  78219. if (this._debugMesh) {
  78220. this.isEnabled = false;
  78221. this._debugMesh.dispose();
  78222. this._debugMesh = null;
  78223. }
  78224. };
  78225. return SkeletonViewer;
  78226. }());
  78227. return Debug;
  78228. }());
  78229. BABYLON.Debug = Debug;
  78230. })(BABYLON || (BABYLON = {}));
  78231. //# sourceMappingURL=babylon.debugModules.js.map
  78232. var BABYLON;
  78233. (function (BABYLON) {
  78234. var RayHelper = /** @class */ (function () {
  78235. function RayHelper(ray) {
  78236. this.ray = ray;
  78237. }
  78238. RayHelper.CreateAndShow = function (ray, scene, color) {
  78239. var helper = new RayHelper(ray);
  78240. helper.show(scene, color);
  78241. return helper;
  78242. };
  78243. RayHelper.prototype.show = function (scene, color) {
  78244. if (!this._renderFunction && this.ray) {
  78245. var ray = this.ray;
  78246. this._renderFunction = this._render.bind(this);
  78247. this._scene = scene;
  78248. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78249. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78250. if (this._renderFunction) {
  78251. this._scene.registerBeforeRender(this._renderFunction);
  78252. }
  78253. }
  78254. if (color && this._renderLine) {
  78255. this._renderLine.color.copyFrom(color);
  78256. }
  78257. };
  78258. RayHelper.prototype.hide = function () {
  78259. if (this._renderFunction && this._scene) {
  78260. this._scene.unregisterBeforeRender(this._renderFunction);
  78261. this._scene = null;
  78262. this._renderFunction = null;
  78263. if (this._renderLine) {
  78264. this._renderLine.dispose();
  78265. this._renderLine = null;
  78266. }
  78267. this._renderPoints = [];
  78268. }
  78269. };
  78270. RayHelper.prototype._render = function () {
  78271. var ray = this.ray;
  78272. if (!ray) {
  78273. return;
  78274. }
  78275. var point = this._renderPoints[1];
  78276. var len = Math.min(ray.length, 1000000);
  78277. point.copyFrom(ray.direction);
  78278. point.scaleInPlace(len);
  78279. point.addInPlace(ray.origin);
  78280. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78281. };
  78282. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78283. this._attachedToMesh = mesh;
  78284. var ray = this.ray;
  78285. if (!ray) {
  78286. return;
  78287. }
  78288. if (!ray.direction) {
  78289. ray.direction = BABYLON.Vector3.Zero();
  78290. }
  78291. if (!ray.origin) {
  78292. ray.origin = BABYLON.Vector3.Zero();
  78293. }
  78294. if (length) {
  78295. ray.length = length;
  78296. }
  78297. if (!meshSpaceOrigin) {
  78298. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78299. }
  78300. if (!meshSpaceDirection) {
  78301. // -1 so that this will work with Mesh.lookAt
  78302. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78303. }
  78304. if (!this._meshSpaceDirection) {
  78305. this._meshSpaceDirection = meshSpaceDirection.clone();
  78306. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78307. }
  78308. else {
  78309. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78310. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78311. }
  78312. if (!this._updateToMeshFunction) {
  78313. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78314. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78315. }
  78316. this._updateToMesh();
  78317. };
  78318. RayHelper.prototype.detachFromMesh = function () {
  78319. if (this._attachedToMesh) {
  78320. if (this._updateToMeshFunction) {
  78321. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78322. }
  78323. this._attachedToMesh = null;
  78324. this._updateToMeshFunction = null;
  78325. }
  78326. };
  78327. RayHelper.prototype._updateToMesh = function () {
  78328. var ray = this.ray;
  78329. if (!this._attachedToMesh || !ray) {
  78330. return;
  78331. }
  78332. if (this._attachedToMesh._isDisposed) {
  78333. this.detachFromMesh();
  78334. return;
  78335. }
  78336. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78337. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78338. };
  78339. RayHelper.prototype.dispose = function () {
  78340. this.hide();
  78341. this.detachFromMesh();
  78342. this.ray = null;
  78343. };
  78344. return RayHelper;
  78345. }());
  78346. BABYLON.RayHelper = RayHelper;
  78347. })(BABYLON || (BABYLON = {}));
  78348. //# sourceMappingURL=babylon.rayHelper.js.map
  78349. var BABYLON;
  78350. (function (BABYLON) {
  78351. // load the inspector using require, if not present in the global namespace.
  78352. var DebugLayer = /** @class */ (function () {
  78353. function DebugLayer(scene) {
  78354. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78355. this._scene = scene;
  78356. // load inspector using require, if it doesn't exist on the global namespace.
  78357. }
  78358. /** Creates the inspector window. */
  78359. DebugLayer.prototype._createInspector = function (config) {
  78360. if (config === void 0) { config = {}; }
  78361. var popup = config.popup || false;
  78362. var initialTab = config.initialTab || 0;
  78363. var parentElement = config.parentElement || null;
  78364. if (!this._inspector) {
  78365. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78366. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78367. } // else nothing to do,; instance is already existing
  78368. };
  78369. DebugLayer.prototype.isVisible = function () {
  78370. if (!this._inspector) {
  78371. return false;
  78372. }
  78373. return true;
  78374. };
  78375. DebugLayer.prototype.hide = function () {
  78376. if (this._inspector) {
  78377. try {
  78378. this._inspector.dispose();
  78379. }
  78380. catch (e) {
  78381. // If the inspector has been removed directly from the inspector tool
  78382. }
  78383. this._inspector = null;
  78384. }
  78385. };
  78386. DebugLayer.prototype.show = function (config) {
  78387. if (config === void 0) { config = {}; }
  78388. if (typeof this.BJSINSPECTOR == 'undefined') {
  78389. // Load inspector and add it to the DOM
  78390. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78391. }
  78392. else {
  78393. // Otherwise creates the inspector
  78394. this._createInspector(config);
  78395. }
  78396. };
  78397. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78398. return DebugLayer;
  78399. }());
  78400. BABYLON.DebugLayer = DebugLayer;
  78401. })(BABYLON || (BABYLON = {}));
  78402. //# sourceMappingURL=babylon.debugLayer.js.map
  78403. var BABYLON;
  78404. (function (BABYLON) {
  78405. var BoundingBoxRenderer = /** @class */ (function () {
  78406. function BoundingBoxRenderer(scene) {
  78407. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78408. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78409. this.showBackLines = true;
  78410. this.renderList = new BABYLON.SmartArray(32);
  78411. this._vertexBuffers = {};
  78412. this._scene = scene;
  78413. }
  78414. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78415. if (this._colorShader) {
  78416. return;
  78417. }
  78418. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78419. attributes: [BABYLON.VertexBuffer.PositionKind],
  78420. uniforms: ["world", "viewProjection", "color"]
  78421. });
  78422. var engine = this._scene.getEngine();
  78423. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78425. this._createIndexBuffer();
  78426. };
  78427. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78428. var engine = this._scene.getEngine();
  78429. 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]);
  78430. };
  78431. BoundingBoxRenderer.prototype._rebuild = function () {
  78432. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78433. if (vb) {
  78434. vb._rebuild();
  78435. }
  78436. this._createIndexBuffer();
  78437. };
  78438. BoundingBoxRenderer.prototype.reset = function () {
  78439. this.renderList.reset();
  78440. };
  78441. BoundingBoxRenderer.prototype.render = function () {
  78442. if (this.renderList.length === 0) {
  78443. return;
  78444. }
  78445. this._prepareRessources();
  78446. if (!this._colorShader.isReady()) {
  78447. return;
  78448. }
  78449. var engine = this._scene.getEngine();
  78450. engine.setDepthWrite(false);
  78451. this._colorShader._preBind();
  78452. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78453. var boundingBox = this.renderList.data[boundingBoxIndex];
  78454. var min = boundingBox.minimum;
  78455. var max = boundingBox.maximum;
  78456. var diff = max.subtract(min);
  78457. var median = min.add(diff.scale(0.5));
  78458. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78459. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78460. .multiply(boundingBox.getWorldMatrix());
  78461. // VBOs
  78462. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78463. if (this.showBackLines) {
  78464. // Back
  78465. engine.setDepthFunctionToGreaterOrEqual();
  78466. this._scene.resetCachedMaterial();
  78467. this._colorShader.setColor4("color", this.backColor.toColor4());
  78468. this._colorShader.bind(worldMatrix);
  78469. // Draw order
  78470. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78471. }
  78472. // Front
  78473. engine.setDepthFunctionToLess();
  78474. this._scene.resetCachedMaterial();
  78475. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78476. this._colorShader.bind(worldMatrix);
  78477. // Draw order
  78478. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78479. }
  78480. this._colorShader.unbind();
  78481. engine.setDepthFunctionToLessOrEqual();
  78482. engine.setDepthWrite(true);
  78483. };
  78484. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78485. this._prepareRessources();
  78486. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78487. return;
  78488. }
  78489. var engine = this._scene.getEngine();
  78490. engine.setDepthWrite(false);
  78491. engine.setColorWrite(false);
  78492. this._colorShader._preBind();
  78493. var boundingBox = mesh._boundingInfo.boundingBox;
  78494. var min = boundingBox.minimum;
  78495. var max = boundingBox.maximum;
  78496. var diff = max.subtract(min);
  78497. var median = min.add(diff.scale(0.5));
  78498. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78499. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78500. .multiply(boundingBox.getWorldMatrix());
  78501. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78502. engine.setDepthFunctionToLess();
  78503. this._scene.resetCachedMaterial();
  78504. this._colorShader.bind(worldMatrix);
  78505. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78506. this._colorShader.unbind();
  78507. engine.setDepthFunctionToLessOrEqual();
  78508. engine.setDepthWrite(true);
  78509. engine.setColorWrite(true);
  78510. };
  78511. BoundingBoxRenderer.prototype.dispose = function () {
  78512. if (!this._colorShader) {
  78513. return;
  78514. }
  78515. this.renderList.dispose();
  78516. this._colorShader.dispose();
  78517. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78518. if (buffer) {
  78519. buffer.dispose();
  78520. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78521. }
  78522. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78523. };
  78524. return BoundingBoxRenderer;
  78525. }());
  78526. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78527. })(BABYLON || (BABYLON = {}));
  78528. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78529. var BABYLON;
  78530. (function (BABYLON) {
  78531. var MorphTarget = /** @class */ (function () {
  78532. function MorphTarget(name, influence) {
  78533. if (influence === void 0) { influence = 0; }
  78534. this.name = name;
  78535. this.animations = new Array();
  78536. this._positions = null;
  78537. this._normals = null;
  78538. this._tangents = null;
  78539. this.onInfluenceChanged = new BABYLON.Observable();
  78540. this.influence = influence;
  78541. }
  78542. Object.defineProperty(MorphTarget.prototype, "influence", {
  78543. get: function () {
  78544. return this._influence;
  78545. },
  78546. set: function (influence) {
  78547. if (this._influence === influence) {
  78548. return;
  78549. }
  78550. var previous = this._influence;
  78551. this._influence = influence;
  78552. if (this.onInfluenceChanged.hasObservers) {
  78553. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78554. }
  78555. },
  78556. enumerable: true,
  78557. configurable: true
  78558. });
  78559. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78560. get: function () {
  78561. return !!this._positions;
  78562. },
  78563. enumerable: true,
  78564. configurable: true
  78565. });
  78566. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78567. get: function () {
  78568. return !!this._normals;
  78569. },
  78570. enumerable: true,
  78571. configurable: true
  78572. });
  78573. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78574. get: function () {
  78575. return !!this._tangents;
  78576. },
  78577. enumerable: true,
  78578. configurable: true
  78579. });
  78580. MorphTarget.prototype.setPositions = function (data) {
  78581. this._positions = data;
  78582. };
  78583. MorphTarget.prototype.getPositions = function () {
  78584. return this._positions;
  78585. };
  78586. MorphTarget.prototype.setNormals = function (data) {
  78587. this._normals = data;
  78588. };
  78589. MorphTarget.prototype.getNormals = function () {
  78590. return this._normals;
  78591. };
  78592. MorphTarget.prototype.setTangents = function (data) {
  78593. this._tangents = data;
  78594. };
  78595. MorphTarget.prototype.getTangents = function () {
  78596. return this._tangents;
  78597. };
  78598. /**
  78599. * Serializes the current target into a Serialization object.
  78600. * Returns the serialized object.
  78601. */
  78602. MorphTarget.prototype.serialize = function () {
  78603. var serializationObject = {};
  78604. serializationObject.name = this.name;
  78605. serializationObject.influence = this.influence;
  78606. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78607. if (this.hasNormals) {
  78608. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78609. }
  78610. if (this.hasTangents) {
  78611. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78612. }
  78613. // Animations
  78614. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78615. return serializationObject;
  78616. };
  78617. // Statics
  78618. MorphTarget.Parse = function (serializationObject) {
  78619. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78620. result.setPositions(serializationObject.positions);
  78621. if (serializationObject.normals) {
  78622. result.setNormals(serializationObject.normals);
  78623. }
  78624. if (serializationObject.tangents) {
  78625. result.setTangents(serializationObject.tangents);
  78626. }
  78627. // Animations
  78628. if (serializationObject.animations) {
  78629. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78630. var parsedAnimation = serializationObject.animations[animationIndex];
  78631. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78632. }
  78633. }
  78634. return result;
  78635. };
  78636. MorphTarget.FromMesh = function (mesh, name, influence) {
  78637. if (!name) {
  78638. name = mesh.name;
  78639. }
  78640. var result = new MorphTarget(name, influence);
  78641. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78642. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78643. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78644. }
  78645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78646. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78647. }
  78648. return result;
  78649. };
  78650. return MorphTarget;
  78651. }());
  78652. BABYLON.MorphTarget = MorphTarget;
  78653. })(BABYLON || (BABYLON = {}));
  78654. //# sourceMappingURL=babylon.morphTarget.js.map
  78655. var BABYLON;
  78656. (function (BABYLON) {
  78657. var MorphTargetManager = /** @class */ (function () {
  78658. function MorphTargetManager(scene) {
  78659. if (scene === void 0) { scene = null; }
  78660. this._targets = new Array();
  78661. this._targetObservable = new Array();
  78662. this._activeTargets = new BABYLON.SmartArray(16);
  78663. this._supportsNormals = false;
  78664. this._supportsTangents = false;
  78665. this._vertexCount = 0;
  78666. this._uniqueId = 0;
  78667. this._tempInfluences = new Array();
  78668. if (!scene) {
  78669. scene = BABYLON.Engine.LastCreatedScene;
  78670. }
  78671. this._scene = scene;
  78672. if (this._scene) {
  78673. this._scene.morphTargetManagers.push(this);
  78674. this._uniqueId = this._scene.getUniqueId();
  78675. }
  78676. }
  78677. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78678. get: function () {
  78679. return this._uniqueId;
  78680. },
  78681. enumerable: true,
  78682. configurable: true
  78683. });
  78684. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78685. get: function () {
  78686. return this._vertexCount;
  78687. },
  78688. enumerable: true,
  78689. configurable: true
  78690. });
  78691. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78692. get: function () {
  78693. return this._supportsNormals;
  78694. },
  78695. enumerable: true,
  78696. configurable: true
  78697. });
  78698. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78699. get: function () {
  78700. return this._supportsTangents;
  78701. },
  78702. enumerable: true,
  78703. configurable: true
  78704. });
  78705. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78706. get: function () {
  78707. return this._targets.length;
  78708. },
  78709. enumerable: true,
  78710. configurable: true
  78711. });
  78712. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78713. get: function () {
  78714. return this._activeTargets.length;
  78715. },
  78716. enumerable: true,
  78717. configurable: true
  78718. });
  78719. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78720. get: function () {
  78721. return this._influences;
  78722. },
  78723. enumerable: true,
  78724. configurable: true
  78725. });
  78726. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78727. return this._activeTargets.data[index];
  78728. };
  78729. MorphTargetManager.prototype.getTarget = function (index) {
  78730. return this._targets[index];
  78731. };
  78732. MorphTargetManager.prototype.addTarget = function (target) {
  78733. var _this = this;
  78734. this._targets.push(target);
  78735. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78736. _this._syncActiveTargets(needUpdate);
  78737. }));
  78738. this._syncActiveTargets(true);
  78739. };
  78740. MorphTargetManager.prototype.removeTarget = function (target) {
  78741. var index = this._targets.indexOf(target);
  78742. if (index >= 0) {
  78743. this._targets.splice(index, 1);
  78744. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78745. this._syncActiveTargets(true);
  78746. }
  78747. };
  78748. /**
  78749. * Serializes the current manager into a Serialization object.
  78750. * Returns the serialized object.
  78751. */
  78752. MorphTargetManager.prototype.serialize = function () {
  78753. var serializationObject = {};
  78754. serializationObject.id = this.uniqueId;
  78755. serializationObject.targets = [];
  78756. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78757. var target = _a[_i];
  78758. serializationObject.targets.push(target.serialize());
  78759. }
  78760. return serializationObject;
  78761. };
  78762. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78763. var influenceCount = 0;
  78764. this._activeTargets.reset();
  78765. this._supportsNormals = true;
  78766. this._supportsTangents = true;
  78767. this._vertexCount = 0;
  78768. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78769. var target = _a[_i];
  78770. this._activeTargets.push(target);
  78771. this._tempInfluences[influenceCount++] = target.influence;
  78772. var positions = target.getPositions();
  78773. if (positions) {
  78774. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78775. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78776. var vertexCount = positions.length / 3;
  78777. if (this._vertexCount === 0) {
  78778. this._vertexCount = vertexCount;
  78779. }
  78780. else if (this._vertexCount !== vertexCount) {
  78781. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78782. return;
  78783. }
  78784. }
  78785. }
  78786. if (!this._influences || this._influences.length !== influenceCount) {
  78787. this._influences = new Float32Array(influenceCount);
  78788. }
  78789. for (var index = 0; index < influenceCount; index++) {
  78790. this._influences[index] = this._tempInfluences[index];
  78791. }
  78792. if (needUpdate && this._scene) {
  78793. // Flag meshes as dirty to resync with the active targets
  78794. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78795. var mesh = _c[_b];
  78796. if (mesh.morphTargetManager === this) {
  78797. mesh._syncGeometryWithMorphTargetManager();
  78798. }
  78799. }
  78800. }
  78801. };
  78802. // Statics
  78803. MorphTargetManager.Parse = function (serializationObject, scene) {
  78804. var result = new MorphTargetManager(scene);
  78805. result._uniqueId = serializationObject.id;
  78806. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78807. var targetData = _a[_i];
  78808. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78809. }
  78810. return result;
  78811. };
  78812. return MorphTargetManager;
  78813. }());
  78814. BABYLON.MorphTargetManager = MorphTargetManager;
  78815. })(BABYLON || (BABYLON = {}));
  78816. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78817. var BABYLON;
  78818. (function (BABYLON) {
  78819. var Octree = /** @class */ (function () {
  78820. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78821. if (maxDepth === void 0) { maxDepth = 2; }
  78822. this.maxDepth = maxDepth;
  78823. this.dynamicContent = new Array();
  78824. this._maxBlockCapacity = maxBlockCapacity || 64;
  78825. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78826. this._creationFunc = creationFunc;
  78827. }
  78828. // Methods
  78829. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78830. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78831. };
  78832. Octree.prototype.addMesh = function (entry) {
  78833. for (var index = 0; index < this.blocks.length; index++) {
  78834. var block = this.blocks[index];
  78835. block.addEntry(entry);
  78836. }
  78837. };
  78838. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78839. this._selectionContent.reset();
  78840. for (var index = 0; index < this.blocks.length; index++) {
  78841. var block = this.blocks[index];
  78842. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78843. }
  78844. if (allowDuplicate) {
  78845. this._selectionContent.concat(this.dynamicContent);
  78846. }
  78847. else {
  78848. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78849. }
  78850. return this._selectionContent;
  78851. };
  78852. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78853. this._selectionContent.reset();
  78854. for (var index = 0; index < this.blocks.length; index++) {
  78855. var block = this.blocks[index];
  78856. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78857. }
  78858. if (allowDuplicate) {
  78859. this._selectionContent.concat(this.dynamicContent);
  78860. }
  78861. else {
  78862. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78863. }
  78864. return this._selectionContent;
  78865. };
  78866. Octree.prototype.intersectsRay = function (ray) {
  78867. this._selectionContent.reset();
  78868. for (var index = 0; index < this.blocks.length; index++) {
  78869. var block = this.blocks[index];
  78870. block.intersectsRay(ray, this._selectionContent);
  78871. }
  78872. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78873. return this._selectionContent;
  78874. };
  78875. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78876. target.blocks = new Array();
  78877. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78878. // Segmenting space
  78879. for (var x = 0; x < 2; x++) {
  78880. for (var y = 0; y < 2; y++) {
  78881. for (var z = 0; z < 2; z++) {
  78882. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78883. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78884. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78885. block.addEntries(entries);
  78886. target.blocks.push(block);
  78887. }
  78888. }
  78889. }
  78890. };
  78891. Octree.CreationFuncForMeshes = function (entry, block) {
  78892. var boundingInfo = entry.getBoundingInfo();
  78893. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78894. block.entries.push(entry);
  78895. }
  78896. };
  78897. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78898. var boundingInfo = entry.getBoundingInfo();
  78899. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78900. block.entries.push(entry);
  78901. }
  78902. };
  78903. return Octree;
  78904. }());
  78905. BABYLON.Octree = Octree;
  78906. })(BABYLON || (BABYLON = {}));
  78907. //# sourceMappingURL=babylon.octree.js.map
  78908. var BABYLON;
  78909. (function (BABYLON) {
  78910. var OctreeBlock = /** @class */ (function () {
  78911. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78912. this.entries = new Array();
  78913. this._boundingVectors = new Array();
  78914. this._capacity = capacity;
  78915. this._depth = depth;
  78916. this._maxDepth = maxDepth;
  78917. this._creationFunc = creationFunc;
  78918. this._minPoint = minPoint;
  78919. this._maxPoint = maxPoint;
  78920. this._boundingVectors.push(minPoint.clone());
  78921. this._boundingVectors.push(maxPoint.clone());
  78922. this._boundingVectors.push(minPoint.clone());
  78923. this._boundingVectors[2].x = maxPoint.x;
  78924. this._boundingVectors.push(minPoint.clone());
  78925. this._boundingVectors[3].y = maxPoint.y;
  78926. this._boundingVectors.push(minPoint.clone());
  78927. this._boundingVectors[4].z = maxPoint.z;
  78928. this._boundingVectors.push(maxPoint.clone());
  78929. this._boundingVectors[5].z = minPoint.z;
  78930. this._boundingVectors.push(maxPoint.clone());
  78931. this._boundingVectors[6].x = minPoint.x;
  78932. this._boundingVectors.push(maxPoint.clone());
  78933. this._boundingVectors[7].y = minPoint.y;
  78934. }
  78935. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78936. // Property
  78937. get: function () {
  78938. return this._capacity;
  78939. },
  78940. enumerable: true,
  78941. configurable: true
  78942. });
  78943. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78944. get: function () {
  78945. return this._minPoint;
  78946. },
  78947. enumerable: true,
  78948. configurable: true
  78949. });
  78950. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78951. get: function () {
  78952. return this._maxPoint;
  78953. },
  78954. enumerable: true,
  78955. configurable: true
  78956. });
  78957. // Methods
  78958. OctreeBlock.prototype.addEntry = function (entry) {
  78959. if (this.blocks) {
  78960. for (var index = 0; index < this.blocks.length; index++) {
  78961. var block = this.blocks[index];
  78962. block.addEntry(entry);
  78963. }
  78964. return;
  78965. }
  78966. this._creationFunc(entry, this);
  78967. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78968. this.createInnerBlocks();
  78969. }
  78970. };
  78971. OctreeBlock.prototype.addEntries = function (entries) {
  78972. for (var index = 0; index < entries.length; index++) {
  78973. var mesh = entries[index];
  78974. this.addEntry(mesh);
  78975. }
  78976. };
  78977. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78978. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78979. if (this.blocks) {
  78980. for (var index = 0; index < this.blocks.length; index++) {
  78981. var block = this.blocks[index];
  78982. block.select(frustumPlanes, selection, allowDuplicate);
  78983. }
  78984. return;
  78985. }
  78986. if (allowDuplicate) {
  78987. selection.concat(this.entries);
  78988. }
  78989. else {
  78990. selection.concatWithNoDuplicate(this.entries);
  78991. }
  78992. }
  78993. };
  78994. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78995. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78996. if (this.blocks) {
  78997. for (var index = 0; index < this.blocks.length; index++) {
  78998. var block = this.blocks[index];
  78999. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  79000. }
  79001. return;
  79002. }
  79003. if (allowDuplicate) {
  79004. selection.concat(this.entries);
  79005. }
  79006. else {
  79007. selection.concatWithNoDuplicate(this.entries);
  79008. }
  79009. }
  79010. };
  79011. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  79012. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  79013. if (this.blocks) {
  79014. for (var index = 0; index < this.blocks.length; index++) {
  79015. var block = this.blocks[index];
  79016. block.intersectsRay(ray, selection);
  79017. }
  79018. return;
  79019. }
  79020. selection.concatWithNoDuplicate(this.entries);
  79021. }
  79022. };
  79023. OctreeBlock.prototype.createInnerBlocks = function () {
  79024. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  79025. };
  79026. return OctreeBlock;
  79027. }());
  79028. BABYLON.OctreeBlock = OctreeBlock;
  79029. })(BABYLON || (BABYLON = {}));
  79030. //# sourceMappingURL=babylon.octreeBlock.js.map
  79031. var BABYLON;
  79032. (function (BABYLON) {
  79033. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  79034. __extends(VRDistortionCorrectionPostProcess, _super);
  79035. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  79036. var _this = _super.call(this, name, "vrDistortionCorrection", [
  79037. 'LensCenter',
  79038. 'Scale',
  79039. 'ScaleIn',
  79040. 'HmdWarpParam'
  79041. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  79042. _this._isRightEye = isRightEye;
  79043. _this._distortionFactors = vrMetrics.distortionK;
  79044. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  79045. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  79046. _this.adaptScaleToCurrentViewport = true;
  79047. _this.onSizeChangedObservable.add(function () {
  79048. _this.aspectRatio = _this.width * .5 / _this.height;
  79049. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  79050. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  79051. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  79052. });
  79053. _this.onApplyObservable.add(function (effect) {
  79054. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  79055. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  79056. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  79057. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  79058. });
  79059. return _this;
  79060. }
  79061. return VRDistortionCorrectionPostProcess;
  79062. }(BABYLON.PostProcess));
  79063. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  79064. })(BABYLON || (BABYLON = {}));
  79065. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  79066. var BABYLON;
  79067. (function (BABYLON) {
  79068. var AnaglyphPostProcess = /** @class */ (function (_super) {
  79069. __extends(AnaglyphPostProcess, _super);
  79070. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  79071. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  79072. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79073. _this.onApplyObservable.add(function (effect) {
  79074. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  79075. });
  79076. return _this;
  79077. }
  79078. return AnaglyphPostProcess;
  79079. }(BABYLON.PostProcess));
  79080. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  79081. })(BABYLON || (BABYLON = {}));
  79082. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  79083. var BABYLON;
  79084. (function (BABYLON) {
  79085. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  79086. __extends(StereoscopicInterlacePostProcess, _super);
  79087. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  79088. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  79089. _this._passedProcess = rigCameras[0]._rigPostProcess;
  79090. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79091. _this.onSizeChangedObservable.add(function () {
  79092. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  79093. });
  79094. _this.onApplyObservable.add(function (effect) {
  79095. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  79096. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  79097. });
  79098. return _this;
  79099. }
  79100. return StereoscopicInterlacePostProcess;
  79101. }(BABYLON.PostProcess));
  79102. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  79103. })(BABYLON || (BABYLON = {}));
  79104. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  79105. var BABYLON;
  79106. (function (BABYLON) {
  79107. /**
  79108. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  79109. * Screen rotation is taken into account.
  79110. */
  79111. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  79112. function FreeCameraDeviceOrientationInput() {
  79113. var _this = this;
  79114. this._screenOrientationAngle = 0;
  79115. this._screenQuaternion = new BABYLON.Quaternion();
  79116. this._alpha = 0;
  79117. this._beta = 0;
  79118. this._gamma = 0;
  79119. this._orientationChanged = function () {
  79120. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  79121. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  79122. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  79123. };
  79124. this._deviceOrientation = function (evt) {
  79125. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  79126. _this._beta = evt.beta !== null ? evt.beta : 0;
  79127. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  79128. };
  79129. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  79130. this._orientationChanged();
  79131. }
  79132. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  79133. get: function () {
  79134. return this._camera;
  79135. },
  79136. set: function (camera) {
  79137. this._camera = camera;
  79138. if (this._camera != null && !this._camera.rotationQuaternion) {
  79139. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  79140. }
  79141. },
  79142. enumerable: true,
  79143. configurable: true
  79144. });
  79145. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79146. window.addEventListener("orientationchange", this._orientationChanged);
  79147. window.addEventListener("deviceorientation", this._deviceOrientation);
  79148. //In certain cases, the attach control is called AFTER orientation was changed,
  79149. //So this is needed.
  79150. this._orientationChanged();
  79151. };
  79152. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  79153. window.removeEventListener("orientationchange", this._orientationChanged);
  79154. window.removeEventListener("deviceorientation", this._deviceOrientation);
  79155. };
  79156. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  79157. //if no device orientation provided, don't update the rotation.
  79158. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  79159. if (!this._alpha)
  79160. return;
  79161. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  79162. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  79163. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  79164. //Mirror on XY Plane
  79165. this._camera.rotationQuaternion.z *= -1;
  79166. this._camera.rotationQuaternion.w *= -1;
  79167. };
  79168. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  79169. return "FreeCameraDeviceOrientationInput";
  79170. };
  79171. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  79172. return "deviceOrientation";
  79173. };
  79174. return FreeCameraDeviceOrientationInput;
  79175. }());
  79176. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  79177. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  79178. })(BABYLON || (BABYLON = {}));
  79179. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  79180. var BABYLON;
  79181. (function (BABYLON) {
  79182. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  79183. function ArcRotateCameraVRDeviceOrientationInput() {
  79184. this.alphaCorrection = 1;
  79185. this.betaCorrection = 1;
  79186. this.gammaCorrection = 1;
  79187. this._alpha = 0;
  79188. this._gamma = 0;
  79189. this._dirty = false;
  79190. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  79191. }
  79192. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  79193. this.camera.attachControl(element, noPreventDefault);
  79194. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  79195. };
  79196. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  79197. if (evt.alpha !== null) {
  79198. this._alpha = +evt.alpha | 0;
  79199. }
  79200. if (evt.gamma !== null) {
  79201. this._gamma = +evt.gamma | 0;
  79202. }
  79203. this._dirty = true;
  79204. };
  79205. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  79206. if (this._dirty) {
  79207. this._dirty = false;
  79208. if (this._gamma < 0) {
  79209. this._gamma = 180 + this._gamma;
  79210. }
  79211. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  79212. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  79213. }
  79214. };
  79215. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  79216. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  79217. };
  79218. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  79219. return "ArcRotateCameraVRDeviceOrientationInput";
  79220. };
  79221. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79222. return "VRDeviceOrientation";
  79223. };
  79224. return ArcRotateCameraVRDeviceOrientationInput;
  79225. }());
  79226. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79227. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79228. })(BABYLON || (BABYLON = {}));
  79229. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79230. var BABYLON;
  79231. (function (BABYLON) {
  79232. var VRCameraMetrics = /** @class */ (function () {
  79233. function VRCameraMetrics() {
  79234. this.compensateDistortion = true;
  79235. }
  79236. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79237. get: function () {
  79238. return this.hResolution / (2 * this.vResolution);
  79239. },
  79240. enumerable: true,
  79241. configurable: true
  79242. });
  79243. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79244. get: function () {
  79245. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79246. },
  79247. enumerable: true,
  79248. configurable: true
  79249. });
  79250. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79251. get: function () {
  79252. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79253. var h = (4 * meters) / this.hScreenSize;
  79254. return BABYLON.Matrix.Translation(h, 0, 0);
  79255. },
  79256. enumerable: true,
  79257. configurable: true
  79258. });
  79259. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79260. get: function () {
  79261. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79262. var h = (4 * meters) / this.hScreenSize;
  79263. return BABYLON.Matrix.Translation(-h, 0, 0);
  79264. },
  79265. enumerable: true,
  79266. configurable: true
  79267. });
  79268. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79269. get: function () {
  79270. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79271. },
  79272. enumerable: true,
  79273. configurable: true
  79274. });
  79275. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79276. get: function () {
  79277. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79278. },
  79279. enumerable: true,
  79280. configurable: true
  79281. });
  79282. VRCameraMetrics.GetDefault = function () {
  79283. var result = new VRCameraMetrics();
  79284. result.hResolution = 1280;
  79285. result.vResolution = 800;
  79286. result.hScreenSize = 0.149759993;
  79287. result.vScreenSize = 0.0935999975;
  79288. result.vScreenCenter = 0.0467999987;
  79289. result.eyeToScreenDistance = 0.0410000011;
  79290. result.lensSeparationDistance = 0.0635000020;
  79291. result.interpupillaryDistance = 0.0640000030;
  79292. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79293. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79294. result.postProcessScaleFactor = 1.714605507808412;
  79295. result.lensCenterOffset = 0.151976421;
  79296. return result;
  79297. };
  79298. return VRCameraMetrics;
  79299. }());
  79300. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79301. })(BABYLON || (BABYLON = {}));
  79302. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79303. var BABYLON;
  79304. (function (BABYLON) {
  79305. /**
  79306. * This represents a WebVR camera.
  79307. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79308. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79309. */
  79310. var WebVRFreeCamera = /** @class */ (function (_super) {
  79311. __extends(WebVRFreeCamera, _super);
  79312. /**
  79313. * Instantiates a WebVRFreeCamera.
  79314. * @param name The name of the WebVRFreeCamera
  79315. * @param position The starting anchor position for the camera
  79316. * @param scene The scene the camera belongs to
  79317. * @param webVROptions a set of customizable options for the webVRCamera
  79318. */
  79319. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79320. if (webVROptions === void 0) { webVROptions = {}; }
  79321. var _this = _super.call(this, name, position, scene) || this;
  79322. _this.webVROptions = webVROptions;
  79323. /**
  79324. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79325. */
  79326. _this._vrDevice = null;
  79327. /**
  79328. * The rawPose of the vrDevice.
  79329. */
  79330. _this.rawPose = null;
  79331. _this._specsVersion = "1.1";
  79332. _this._attached = false;
  79333. _this._descendants = [];
  79334. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79335. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79336. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79337. _this._standingMatrix = null;
  79338. /**
  79339. * Represents device position in babylon space.
  79340. */
  79341. _this.devicePosition = BABYLON.Vector3.Zero();
  79342. /**
  79343. * Represents device rotation in babylon space.
  79344. */
  79345. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79346. /**
  79347. * The scale of the device to be used when translating from device space to babylon space.
  79348. */
  79349. _this.deviceScaleFactor = 1;
  79350. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79351. _this._worldToDevice = BABYLON.Matrix.Identity();
  79352. /**
  79353. * References to the webVR controllers for the vrDevice.
  79354. */
  79355. _this.controllers = [];
  79356. /**
  79357. * Emits an event when a controller is attached.
  79358. */
  79359. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79360. /**
  79361. * Emits an event when a controller's mesh has been loaded;
  79362. */
  79363. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79364. /**
  79365. * If the rig cameras be used as parent instead of this camera.
  79366. */
  79367. _this.rigParenting = true;
  79368. _this._defaultHeight = undefined;
  79369. _this._workingVector = BABYLON.Vector3.Zero();
  79370. _this._oneVector = BABYLON.Vector3.One();
  79371. _this._workingMatrix = BABYLON.Matrix.Identity();
  79372. _this._cache.position = BABYLON.Vector3.Zero();
  79373. if (webVROptions.defaultHeight) {
  79374. _this._defaultHeight = webVROptions.defaultHeight;
  79375. _this.position.y = _this._defaultHeight;
  79376. }
  79377. _this.minZ = 0.1;
  79378. //legacy support - the compensation boolean was removed.
  79379. if (arguments.length === 5) {
  79380. _this.webVROptions = arguments[4];
  79381. }
  79382. // default webVR options
  79383. if (_this.webVROptions.trackPosition == undefined) {
  79384. _this.webVROptions.trackPosition = true;
  79385. }
  79386. if (_this.webVROptions.controllerMeshes == undefined) {
  79387. _this.webVROptions.controllerMeshes = true;
  79388. }
  79389. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79390. _this.webVROptions.defaultLightingOnControllers = true;
  79391. }
  79392. _this.rotationQuaternion = new BABYLON.Quaternion();
  79393. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79394. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79395. }
  79396. //enable VR
  79397. var engine = _this.getEngine();
  79398. _this._onVREnabled = function (success) { if (success) {
  79399. _this.initControllers();
  79400. } };
  79401. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79402. engine.initWebVR().add(function (event) {
  79403. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79404. return;
  79405. }
  79406. _this._vrDevice = event.vrDisplay;
  79407. //reset the rig parameters.
  79408. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79409. if (_this._attached) {
  79410. _this.getEngine().enableVR();
  79411. }
  79412. });
  79413. if (typeof (VRFrameData) !== "undefined")
  79414. _this._frameData = new VRFrameData();
  79415. /**
  79416. * The idea behind the following lines:
  79417. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79418. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79419. * the second will not show it correctly.
  79420. *
  79421. * To solve this - each object that has the camera as parent will be added to a protected array.
  79422. * When the rig camera renders, it will take this array and set all of those to be its children.
  79423. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79424. * Amazing!
  79425. */
  79426. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79427. if (camera.parent === _this && _this.rigParenting) {
  79428. _this._descendants = _this.getDescendants(true, function (n) {
  79429. // don't take the cameras or the controllers!
  79430. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79431. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79432. return !isController && !isRigCamera;
  79433. });
  79434. _this._descendants.forEach(function (node) {
  79435. node.parent = camera;
  79436. });
  79437. }
  79438. });
  79439. scene.onAfterCameraRenderObservable.add(function (camera) {
  79440. if (camera.parent === _this && _this.rigParenting) {
  79441. _this._descendants.forEach(function (node) {
  79442. node.parent = _this;
  79443. });
  79444. }
  79445. });
  79446. return _this;
  79447. }
  79448. /**
  79449. * Gets the device distance from the ground in meters.
  79450. * @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.
  79451. */
  79452. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79453. if (this._standingMatrix) {
  79454. // Add standing matrix offset to get real offset from ground in room
  79455. this._standingMatrix.getTranslationToRef(this._workingVector);
  79456. return this._deviceRoomPosition.y + this._workingVector.y;
  79457. }
  79458. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79459. return this._defaultHeight || 0;
  79460. };
  79461. /**
  79462. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79463. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79464. */
  79465. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79466. var _this = this;
  79467. if (callback === void 0) { callback = function (bool) { }; }
  79468. // Use standing matrix if available
  79469. this.getEngine().initWebVRAsync().then(function (result) {
  79470. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79471. callback(false);
  79472. }
  79473. else {
  79474. _this._standingMatrix = new BABYLON.Matrix();
  79475. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79476. if (!_this.getScene().useRightHandedSystem) {
  79477. [2, 6, 8, 9, 14].forEach(function (num) {
  79478. if (_this._standingMatrix) {
  79479. _this._standingMatrix.m[num] *= -1;
  79480. }
  79481. });
  79482. }
  79483. callback(true);
  79484. }
  79485. });
  79486. };
  79487. /**
  79488. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79489. * @returns A promise with a boolean set to if the standing matrix is supported.
  79490. */
  79491. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79492. var _this = this;
  79493. return new Promise(function (res, rej) {
  79494. _this.useStandingMatrix(function (supported) {
  79495. res(supported);
  79496. });
  79497. });
  79498. };
  79499. /**
  79500. * Disposes the camera
  79501. */
  79502. WebVRFreeCamera.prototype.dispose = function () {
  79503. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79504. _super.prototype.dispose.call(this);
  79505. };
  79506. /**
  79507. * Gets a vrController by name.
  79508. * @param name The name of the controller to retreive
  79509. * @returns the controller matching the name specified or null if not found
  79510. */
  79511. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79512. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79513. var gp = _a[_i];
  79514. if (gp.hand === name) {
  79515. return gp;
  79516. }
  79517. }
  79518. return null;
  79519. };
  79520. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79521. /**
  79522. * The controller corrisponding to the users left hand.
  79523. */
  79524. get: function () {
  79525. if (!this._leftController) {
  79526. this._leftController = this.getControllerByName("left");
  79527. }
  79528. return this._leftController;
  79529. },
  79530. enumerable: true,
  79531. configurable: true
  79532. });
  79533. ;
  79534. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79535. /**
  79536. * The controller corrisponding to the users right hand.
  79537. */
  79538. get: function () {
  79539. if (!this._rightController) {
  79540. this._rightController = this.getControllerByName("right");
  79541. }
  79542. return this._rightController;
  79543. },
  79544. enumerable: true,
  79545. configurable: true
  79546. });
  79547. ;
  79548. /**
  79549. * Casts a ray forward from the vrCamera's gaze.
  79550. * @param length Length of the ray (default: 100)
  79551. * @returns the ray corrisponding to the gaze
  79552. */
  79553. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79554. if (length === void 0) { length = 100; }
  79555. if (this.leftCamera) {
  79556. // Use left eye to avoid computation to compute center on every call
  79557. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79558. }
  79559. else {
  79560. return _super.prototype.getForwardRay.call(this, length);
  79561. }
  79562. };
  79563. /**
  79564. * Updates the camera based on device's frame data
  79565. */
  79566. WebVRFreeCamera.prototype._checkInputs = function () {
  79567. if (this._vrDevice && this._vrDevice.isPresenting) {
  79568. this._vrDevice.getFrameData(this._frameData);
  79569. this.updateFromDevice(this._frameData.pose);
  79570. }
  79571. _super.prototype._checkInputs.call(this);
  79572. };
  79573. /**
  79574. * Updates the poseControlled values based on the input device pose.
  79575. * @param poseData Pose coming from the device
  79576. */
  79577. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79578. if (poseData && poseData.orientation) {
  79579. this.rawPose = poseData;
  79580. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79581. if (this.getScene().useRightHandedSystem) {
  79582. this._deviceRoomRotationQuaternion.z *= -1;
  79583. this._deviceRoomRotationQuaternion.w *= -1;
  79584. }
  79585. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79586. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79587. if (this.getScene().useRightHandedSystem) {
  79588. this._deviceRoomPosition.z *= -1;
  79589. }
  79590. }
  79591. }
  79592. };
  79593. /**
  79594. * WebVR's attach control will start broadcasting frames to the device.
  79595. * Note that in certain browsers (chrome for example) this function must be called
  79596. * within a user-interaction callback. Example:
  79597. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79598. *
  79599. * @param element html element to attach the vrDevice to
  79600. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79601. */
  79602. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79603. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79604. this._attached = true;
  79605. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79606. if (this._vrDevice) {
  79607. this.getEngine().enableVR();
  79608. }
  79609. };
  79610. /**
  79611. * Detaches the camera from the html element and disables VR
  79612. *
  79613. * @param element html element to detach from
  79614. */
  79615. WebVRFreeCamera.prototype.detachControl = function (element) {
  79616. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79617. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79618. _super.prototype.detachControl.call(this, element);
  79619. this._attached = false;
  79620. this.getEngine().disableVR();
  79621. };
  79622. /**
  79623. * @returns the name of this class
  79624. */
  79625. WebVRFreeCamera.prototype.getClassName = function () {
  79626. return "WebVRFreeCamera";
  79627. };
  79628. /**
  79629. * Calls resetPose on the vrDisplay
  79630. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79631. */
  79632. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79633. //uses the vrDisplay's "resetPose()".
  79634. //pitch and roll won't be affected.
  79635. this._vrDevice.resetPose();
  79636. };
  79637. /**
  79638. * Updates the rig cameras (left and right eye)
  79639. */
  79640. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79641. var camLeft = this._rigCameras[0];
  79642. var camRight = this._rigCameras[1];
  79643. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79644. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79645. camLeft.position.copyFrom(this._deviceRoomPosition);
  79646. camRight.position.copyFrom(this._deviceRoomPosition);
  79647. };
  79648. /**
  79649. * Updates the cached values of the camera
  79650. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79651. */
  79652. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79653. var _this = this;
  79654. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79655. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79656. if (!this.updateCacheCalled) {
  79657. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79658. this.updateCacheCalled = true;
  79659. this.update();
  79660. }
  79661. // Set working vector to the device position in room space rotated by the new rotation
  79662. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79663. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79664. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79665. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79666. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79667. // Add translation from anchor position
  79668. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79669. this._workingVector.addInPlace(this.position);
  79670. this._workingVector.subtractInPlace(this._cache.position);
  79671. this._deviceToWorld.setTranslation(this._workingVector);
  79672. // Set an inverted matrix to be used when updating the camera
  79673. this._deviceToWorld.invertToRef(this._worldToDevice);
  79674. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79675. this.controllers.forEach(function (controller) {
  79676. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79677. controller.update();
  79678. });
  79679. }
  79680. if (!ignoreParentClass) {
  79681. _super.prototype._updateCache.call(this);
  79682. }
  79683. this.updateCacheCalled = false;
  79684. };
  79685. /**
  79686. * Updates the current device position and rotation in the babylon world
  79687. */
  79688. WebVRFreeCamera.prototype.update = function () {
  79689. // Get current device position in babylon world
  79690. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79691. // Get current device rotation in babylon world
  79692. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79693. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79694. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79695. _super.prototype.update.call(this);
  79696. };
  79697. /**
  79698. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79699. * @returns an identity matrix
  79700. */
  79701. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79702. return BABYLON.Matrix.Identity();
  79703. };
  79704. /**
  79705. * This function is called by the two RIG cameras.
  79706. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79707. */
  79708. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79709. var _this = this;
  79710. // Update the parent camera prior to using a child camera to avoid desynchronization
  79711. var parentCamera = this._cameraRigParams["parentCamera"];
  79712. parentCamera._updateCache();
  79713. //WebVR 1.1
  79714. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79715. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79716. if (!this.getScene().useRightHandedSystem) {
  79717. [2, 6, 8, 9, 14].forEach(function (num) {
  79718. _this._webvrViewMatrix.m[num] *= -1;
  79719. });
  79720. }
  79721. // update the camera rotation matrix
  79722. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79723. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79724. // Computing target and final matrix
  79725. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79726. // should the view matrix be updated with scale and position offset?
  79727. if (parentCamera.deviceScaleFactor !== 1) {
  79728. this._webvrViewMatrix.invert();
  79729. // scale the position, if set
  79730. if (parentCamera.deviceScaleFactor) {
  79731. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79732. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79733. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79734. }
  79735. this._webvrViewMatrix.invert();
  79736. }
  79737. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79738. return this._webvrViewMatrix;
  79739. };
  79740. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79741. var _this = this;
  79742. var parentCamera = this.parent;
  79743. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79744. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79745. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79746. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79747. //babylon compatible matrix
  79748. if (!this.getScene().useRightHandedSystem) {
  79749. [8, 9, 10, 11].forEach(function (num) {
  79750. _this._projectionMatrix.m[num] *= -1;
  79751. });
  79752. }
  79753. return this._projectionMatrix;
  79754. };
  79755. /**
  79756. * Initializes the controllers and their meshes
  79757. */
  79758. WebVRFreeCamera.prototype.initControllers = function () {
  79759. var _this = this;
  79760. this.controllers = [];
  79761. var manager = this.getScene().gamepadManager;
  79762. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79763. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79764. var webVrController = gamepad;
  79765. if (webVrController.defaultModel) {
  79766. webVrController.defaultModel.setEnabled(false);
  79767. }
  79768. if (webVrController.hand === "right") {
  79769. _this._rightController = null;
  79770. }
  79771. if (webVrController.hand === "left") {
  79772. _this._leftController = null;
  79773. }
  79774. var controllerIndex = _this.controllers.indexOf(webVrController);
  79775. if (controllerIndex !== -1) {
  79776. _this.controllers.splice(controllerIndex, 1);
  79777. }
  79778. }
  79779. });
  79780. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79781. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79782. var webVrController_1 = gamepad;
  79783. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  79784. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  79785. if (_this.webVROptions.controllerMeshes) {
  79786. if (webVrController_1.defaultModel) {
  79787. webVrController_1.defaultModel.setEnabled(true);
  79788. }
  79789. else {
  79790. // Load the meshes
  79791. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79792. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  79793. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79794. if (_this.webVROptions.defaultLightingOnControllers) {
  79795. if (!_this._lightOnControllers) {
  79796. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79797. }
  79798. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79799. var children = mesh.getChildren();
  79800. if (children.length !== 0) {
  79801. children.forEach(function (mesh) {
  79802. light.includedOnlyMeshes.push(mesh);
  79803. activateLightOnSubMeshes_1(mesh, light);
  79804. });
  79805. }
  79806. };
  79807. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79808. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79809. }
  79810. });
  79811. }
  79812. }
  79813. webVrController_1.attachToPoseControlledCamera(_this);
  79814. // since this is async - sanity check. Is the controller already stored?
  79815. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79816. //add to the controllers array
  79817. _this.controllers.push(webVrController_1);
  79818. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79819. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79820. // So we're overriding setting left & right manually to be sure
  79821. var firstViveWandDetected = false;
  79822. for (var i = 0; i < _this.controllers.length; i++) {
  79823. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79824. if (!firstViveWandDetected) {
  79825. firstViveWandDetected = true;
  79826. _this.controllers[i].hand = "left";
  79827. }
  79828. else {
  79829. _this.controllers[i].hand = "right";
  79830. }
  79831. }
  79832. }
  79833. //did we find enough controllers? Great! let the developer know.
  79834. if (_this.controllers.length >= 2) {
  79835. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79836. }
  79837. }
  79838. }
  79839. });
  79840. };
  79841. return WebVRFreeCamera;
  79842. }(BABYLON.FreeCamera));
  79843. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79844. })(BABYLON || (BABYLON = {}));
  79845. //# sourceMappingURL=babylon.webVRCamera.js.map
  79846. var BABYLON;
  79847. (function (BABYLON) {
  79848. // We're mainly based on the logic defined into the FreeCamera code
  79849. /**
  79850. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79851. * being tilted forward or back and left or right.
  79852. */
  79853. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79854. __extends(DeviceOrientationCamera, _super);
  79855. /**
  79856. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79857. * @param name The name of the camera
  79858. * @param position The start position camera
  79859. * @param scene The scene the camera belongs to
  79860. */
  79861. function DeviceOrientationCamera(name, position, scene) {
  79862. var _this = _super.call(this, name, position, scene) || this;
  79863. _this._quaternionCache = new BABYLON.Quaternion();
  79864. _this.inputs.addDeviceOrientation();
  79865. return _this;
  79866. }
  79867. /**
  79868. * Gets the current instance class name ("DeviceOrientationCamera").
  79869. * This helps avoiding instanceof at run time.
  79870. * @returns the class name
  79871. */
  79872. DeviceOrientationCamera.prototype.getClassName = function () {
  79873. return "DeviceOrientationCamera";
  79874. };
  79875. /**
  79876. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79877. */
  79878. DeviceOrientationCamera.prototype._checkInputs = function () {
  79879. _super.prototype._checkInputs.call(this);
  79880. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79881. if (this._initialQuaternion) {
  79882. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79883. }
  79884. };
  79885. /**
  79886. * Reset the camera to its default orientation on the specified axis only.
  79887. * @param axis The axis to reset
  79888. */
  79889. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79890. var _this = this;
  79891. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79892. //can only work if this camera has a rotation quaternion already.
  79893. if (!this.rotationQuaternion)
  79894. return;
  79895. if (!this._initialQuaternion) {
  79896. this._initialQuaternion = new BABYLON.Quaternion();
  79897. }
  79898. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79899. ['x', 'y', 'z'].forEach(function (axisName) {
  79900. if (!axis[axisName]) {
  79901. _this._initialQuaternion[axisName] = 0;
  79902. }
  79903. else {
  79904. _this._initialQuaternion[axisName] *= -1;
  79905. }
  79906. });
  79907. this._initialQuaternion.normalize();
  79908. //force rotation update
  79909. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79910. };
  79911. return DeviceOrientationCamera;
  79912. }(BABYLON.FreeCamera));
  79913. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79914. })(BABYLON || (BABYLON = {}));
  79915. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79916. var BABYLON;
  79917. (function (BABYLON) {
  79918. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79919. __extends(VRDeviceOrientationFreeCamera, _super);
  79920. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79921. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79922. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79923. var _this = _super.call(this, name, position, scene) || this;
  79924. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79926. return _this;
  79927. }
  79928. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79929. return "VRDeviceOrientationFreeCamera";
  79930. };
  79931. return VRDeviceOrientationFreeCamera;
  79932. }(BABYLON.DeviceOrientationCamera));
  79933. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79934. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79935. __extends(VRDeviceOrientationGamepadCamera, _super);
  79936. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79937. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79938. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79939. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79940. _this.inputs.addGamepad();
  79941. return _this;
  79942. }
  79943. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79944. return "VRDeviceOrientationGamepadCamera";
  79945. };
  79946. return VRDeviceOrientationGamepadCamera;
  79947. }(VRDeviceOrientationFreeCamera));
  79948. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79949. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79950. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79951. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79952. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79953. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79954. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79955. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79956. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79957. _this.inputs.addVRDeviceOrientation();
  79958. return _this;
  79959. }
  79960. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79961. return "VRDeviceOrientationArcRotateCamera";
  79962. };
  79963. return VRDeviceOrientationArcRotateCamera;
  79964. }(BABYLON.ArcRotateCamera));
  79965. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79966. })(BABYLON || (BABYLON = {}));
  79967. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79968. var BABYLON;
  79969. (function (BABYLON) {
  79970. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79971. __extends(AnaglyphFreeCamera, _super);
  79972. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79973. var _this = _super.call(this, name, position, scene) || this;
  79974. _this.interaxialDistance = interaxialDistance;
  79975. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79976. return _this;
  79977. }
  79978. AnaglyphFreeCamera.prototype.getClassName = function () {
  79979. return "AnaglyphFreeCamera";
  79980. };
  79981. return AnaglyphFreeCamera;
  79982. }(BABYLON.FreeCamera));
  79983. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79984. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79985. __extends(AnaglyphArcRotateCamera, _super);
  79986. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79987. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79988. _this.interaxialDistance = interaxialDistance;
  79989. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79990. return _this;
  79991. }
  79992. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79993. return "AnaglyphArcRotateCamera";
  79994. };
  79995. return AnaglyphArcRotateCamera;
  79996. }(BABYLON.ArcRotateCamera));
  79997. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79998. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79999. __extends(AnaglyphGamepadCamera, _super);
  80000. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  80001. var _this = _super.call(this, name, position, scene) || this;
  80002. _this.interaxialDistance = interaxialDistance;
  80003. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80004. return _this;
  80005. }
  80006. AnaglyphGamepadCamera.prototype.getClassName = function () {
  80007. return "AnaglyphGamepadCamera";
  80008. };
  80009. return AnaglyphGamepadCamera;
  80010. }(BABYLON.GamepadCamera));
  80011. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  80012. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  80013. __extends(AnaglyphUniversalCamera, _super);
  80014. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  80015. var _this = _super.call(this, name, position, scene) || this;
  80016. _this.interaxialDistance = interaxialDistance;
  80017. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  80018. return _this;
  80019. }
  80020. AnaglyphUniversalCamera.prototype.getClassName = function () {
  80021. return "AnaglyphUniversalCamera";
  80022. };
  80023. return AnaglyphUniversalCamera;
  80024. }(BABYLON.UniversalCamera));
  80025. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  80026. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  80027. __extends(StereoscopicFreeCamera, _super);
  80028. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80029. var _this = _super.call(this, name, position, scene) || this;
  80030. _this.interaxialDistance = interaxialDistance;
  80031. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80032. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80033. return _this;
  80034. }
  80035. StereoscopicFreeCamera.prototype.getClassName = function () {
  80036. return "StereoscopicFreeCamera";
  80037. };
  80038. return StereoscopicFreeCamera;
  80039. }(BABYLON.FreeCamera));
  80040. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  80041. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  80042. __extends(StereoscopicArcRotateCamera, _super);
  80043. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  80044. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  80045. _this.interaxialDistance = interaxialDistance;
  80046. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80047. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80048. return _this;
  80049. }
  80050. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  80051. return "StereoscopicArcRotateCamera";
  80052. };
  80053. return StereoscopicArcRotateCamera;
  80054. }(BABYLON.ArcRotateCamera));
  80055. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  80056. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  80057. __extends(StereoscopicGamepadCamera, _super);
  80058. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80059. var _this = _super.call(this, name, position, scene) || this;
  80060. _this.interaxialDistance = interaxialDistance;
  80061. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80062. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80063. return _this;
  80064. }
  80065. StereoscopicGamepadCamera.prototype.getClassName = function () {
  80066. return "StereoscopicGamepadCamera";
  80067. };
  80068. return StereoscopicGamepadCamera;
  80069. }(BABYLON.GamepadCamera));
  80070. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  80071. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  80072. __extends(StereoscopicUniversalCamera, _super);
  80073. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  80074. var _this = _super.call(this, name, position, scene) || this;
  80075. _this.interaxialDistance = interaxialDistance;
  80076. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  80077. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  80078. return _this;
  80079. }
  80080. StereoscopicUniversalCamera.prototype.getClassName = function () {
  80081. return "StereoscopicUniversalCamera";
  80082. };
  80083. return StereoscopicUniversalCamera;
  80084. }(BABYLON.UniversalCamera));
  80085. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  80086. })(BABYLON || (BABYLON = {}));
  80087. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  80088. var BABYLON;
  80089. (function (BABYLON) {
  80090. var VRExperienceHelperGazer = /** @class */ (function () {
  80091. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  80092. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  80093. this.scene = scene;
  80094. this._pointerDownOnMeshAsked = false;
  80095. this._isActionableMesh = false;
  80096. this._teleportationRequestInitiated = false;
  80097. this._teleportationBackRequestInitiated = false;
  80098. this._dpadPressed = true;
  80099. this._activePointer = false;
  80100. this._id = VRExperienceHelperGazer._idCounter++;
  80101. // Gaze tracker
  80102. if (!gazeTrackerToClone) {
  80103. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  80104. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80105. this._gazeTracker.isPickable = false;
  80106. this._gazeTracker.isVisible = false;
  80107. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  80108. targetMat.specularColor = BABYLON.Color3.Black();
  80109. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80110. targetMat.backFaceCulling = false;
  80111. this._gazeTracker.material = targetMat;
  80112. }
  80113. else {
  80114. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  80115. }
  80116. }
  80117. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  80118. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  80119. };
  80120. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  80121. this._pointerDownOnMeshAsked = true;
  80122. if (this._currentMeshSelected && this._currentHit) {
  80123. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  80124. }
  80125. };
  80126. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  80127. if (this._currentMeshSelected && this._currentHit) {
  80128. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  80129. }
  80130. this._pointerDownOnMeshAsked = false;
  80131. };
  80132. VRExperienceHelperGazer.prototype._activatePointer = function () {
  80133. this._activePointer = true;
  80134. };
  80135. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  80136. this._activePointer = false;
  80137. };
  80138. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  80139. };
  80140. VRExperienceHelperGazer.prototype.dispose = function () {
  80141. this._interactionsEnabled = false;
  80142. this._teleportationEnabled = false;
  80143. };
  80144. VRExperienceHelperGazer._idCounter = 0;
  80145. return VRExperienceHelperGazer;
  80146. }());
  80147. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  80148. __extends(VRExperienceHelperControllerGazer, _super);
  80149. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  80150. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  80151. _this.webVRController = webVRController;
  80152. // Laser pointer
  80153. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  80154. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  80155. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80156. laserPointerMaterial.alpha = 0.6;
  80157. _this._laserPointer.material = laserPointerMaterial;
  80158. _this._laserPointer.rotation.x = Math.PI / 2;
  80159. _this._laserPointer.position.z = -0.5;
  80160. _this._laserPointer.isVisible = false;
  80161. if (!webVRController.mesh) {
  80162. // Create an empty mesh that is used prior to loading the high quality model
  80163. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  80164. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  80165. preloadPointerPose.rotation.x = -0.7;
  80166. preloadMesh.addChild(preloadPointerPose);
  80167. webVRController.attachToMesh(preloadMesh);
  80168. }
  80169. _this._setLaserPointerParent(webVRController.mesh);
  80170. return _this;
  80171. }
  80172. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  80173. return this.webVRController.getForwardRay(length);
  80174. };
  80175. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  80176. _super.prototype._activatePointer.call(this);
  80177. this._laserPointer.isVisible = true;
  80178. };
  80179. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  80180. _super.prototype._deactivatePointer.call(this);
  80181. this._laserPointer.isVisible = false;
  80182. };
  80183. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  80184. this._laserPointer.material.emissiveColor = color;
  80185. };
  80186. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  80187. var makeNotPick = function (root) {
  80188. root.name += " laserPointer";
  80189. root.getChildMeshes().forEach(function (c) {
  80190. makeNotPick(c);
  80191. });
  80192. };
  80193. makeNotPick(mesh);
  80194. var childMeshes = mesh.getChildMeshes();
  80195. for (var i = 0; i < childMeshes.length; i++) {
  80196. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  80197. mesh = childMeshes[i];
  80198. this.webVRController._pointingPoseNode = mesh;
  80199. break;
  80200. }
  80201. }
  80202. this._laserPointer.parent = mesh;
  80203. };
  80204. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  80205. this._laserPointer.scaling.y = distance;
  80206. this._laserPointer.position.z = -distance / 2;
  80207. };
  80208. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  80209. _super.prototype.dispose.call(this);
  80210. this._laserPointer.dispose();
  80211. };
  80212. return VRExperienceHelperControllerGazer;
  80213. }(VRExperienceHelperGazer));
  80214. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  80215. __extends(VRExperienceHelperCameraGazer, _super);
  80216. function VRExperienceHelperCameraGazer(getCamera, scene) {
  80217. var _this = _super.call(this, scene) || this;
  80218. _this.getCamera = getCamera;
  80219. return _this;
  80220. }
  80221. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  80222. var camera = this.getCamera();
  80223. if (camera) {
  80224. return camera.getForwardRay(length);
  80225. }
  80226. else {
  80227. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  80228. }
  80229. };
  80230. return VRExperienceHelperCameraGazer;
  80231. }(VRExperienceHelperGazer));
  80232. /**
  80233. * Helps to quickly add VR support to an existing scene.
  80234. * See http://doc.babylonjs.com/how_to/webvr_helper
  80235. */
  80236. var VRExperienceHelper = /** @class */ (function () {
  80237. /**
  80238. * Instantiates a VRExperienceHelper.
  80239. * Helps to quickly add VR support to an existing scene.
  80240. * @param scene The scene the VRExperienceHelper belongs to.
  80241. * @param webVROptions Options to modify the vr experience helper's behavior.
  80242. */
  80243. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  80244. if (webVROptions === void 0) { webVROptions = {}; }
  80245. var _this = this;
  80246. this.webVROptions = webVROptions;
  80247. // Can the system support WebVR, even if a headset isn't plugged in?
  80248. this._webVRsupported = false;
  80249. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80250. this._webVRready = false;
  80251. // Are we waiting for the requestPresent callback to complete?
  80252. this._webVRrequesting = false;
  80253. // Are we presenting to the headset right now?
  80254. this._webVRpresenting = false;
  80255. // Are we presenting in the fullscreen fallback?
  80256. this._fullscreenVRpresenting = false;
  80257. /**
  80258. * Observable raised when entering VR.
  80259. */
  80260. this.onEnteringVRObservable = new BABYLON.Observable();
  80261. /**
  80262. * Observable raised when exiting VR.
  80263. */
  80264. this.onExitingVRObservable = new BABYLON.Observable();
  80265. /**
  80266. * Observable raised when controller mesh is loaded.
  80267. */
  80268. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80269. this._useCustomVRButton = false;
  80270. this._teleportationRequested = false;
  80271. this._teleportActive = false;
  80272. this._floorMeshesCollection = [];
  80273. this._rotationAllowed = true;
  80274. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80275. this._rotationRightAsked = false;
  80276. this._rotationLeftAsked = false;
  80277. this._isDefaultTeleportationTarget = true;
  80278. this._teleportationFillColor = "#444444";
  80279. this._teleportationBorderColor = "#FFFFFF";
  80280. this._rotationAngle = 0;
  80281. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80282. this._padSensibilityUp = 0.65;
  80283. this._padSensibilityDown = 0.35;
  80284. this.leftController = null;
  80285. this.rightController = null;
  80286. /**
  80287. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80288. */
  80289. this.onNewMeshSelected = new BABYLON.Observable();
  80290. /**
  80291. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80292. */
  80293. this.onNewMeshPicked = new BABYLON.Observable();
  80294. /**
  80295. * Observable raised before camera teleportation
  80296. */
  80297. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80298. /**
  80299. * Observable raised after camera teleportation
  80300. */
  80301. this.onAfterCameraTeleport = new BABYLON.Observable();
  80302. /**
  80303. * Observable raised when current selected mesh gets unselected
  80304. */
  80305. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80306. /**
  80307. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80308. */
  80309. this.teleportationEnabled = true;
  80310. this._teleportationInitialized = false;
  80311. this._interactionsEnabled = false;
  80312. this._interactionsRequested = false;
  80313. this._displayGaze = true;
  80314. this._displayLaserPointer = true;
  80315. this._onResize = function () {
  80316. _this.moveButtonToBottomRight();
  80317. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80318. _this.exitVR();
  80319. }
  80320. };
  80321. this._onFullscreenChange = function () {
  80322. if (document.fullscreen !== undefined) {
  80323. _this._fullscreenVRpresenting = document.fullscreen;
  80324. }
  80325. else if (document.mozFullScreen !== undefined) {
  80326. _this._fullscreenVRpresenting = document.mozFullScreen;
  80327. }
  80328. else if (document.webkitIsFullScreen !== undefined) {
  80329. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80330. }
  80331. else if (document.msIsFullScreen !== undefined) {
  80332. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80333. }
  80334. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80335. _this.exitVR();
  80336. if (!_this._useCustomVRButton) {
  80337. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80338. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80339. }
  80340. }
  80341. };
  80342. this.beforeRender = function () {
  80343. if (_this.leftController && _this.leftController._activePointer) {
  80344. _this._castRayAndSelectObject(_this.leftController);
  80345. }
  80346. if (_this.rightController && _this.rightController._activePointer) {
  80347. _this._castRayAndSelectObject(_this.rightController);
  80348. }
  80349. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80350. _this._castRayAndSelectObject(_this._cameraGazer);
  80351. }
  80352. else {
  80353. _this._cameraGazer._gazeTracker.isVisible = false;
  80354. }
  80355. };
  80356. this._onNewGamepadConnected = function (gamepad) {
  80357. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80358. if (gamepad.leftStick) {
  80359. gamepad.onleftstickchanged(function (stickValues) {
  80360. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80361. // Listening to classic/xbox gamepad only if no VR controller is active
  80362. if ((!_this.leftController && !_this.rightController) ||
  80363. ((_this.leftController && !_this.leftController._activePointer) &&
  80364. (_this.rightController && !_this.rightController._activePointer))) {
  80365. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80366. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80367. }
  80368. }
  80369. });
  80370. }
  80371. if (gamepad.rightStick) {
  80372. gamepad.onrightstickchanged(function (stickValues) {
  80373. if (_this._teleportationInitialized) {
  80374. _this._checkRotate(stickValues, _this._cameraGazer);
  80375. }
  80376. });
  80377. }
  80378. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80379. gamepad.onbuttondown(function (buttonPressed) {
  80380. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80381. _this._cameraGazer._selectionPointerDown();
  80382. }
  80383. });
  80384. gamepad.onbuttonup(function (buttonPressed) {
  80385. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80386. _this._cameraGazer._selectionPointerUp();
  80387. }
  80388. });
  80389. }
  80390. }
  80391. else {
  80392. var webVRController = gamepad;
  80393. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80394. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80395. _this.rightController = controller;
  80396. }
  80397. else {
  80398. _this.leftController = controller;
  80399. }
  80400. _this._tryEnableInteractionOnController(controller);
  80401. }
  80402. };
  80403. // 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
  80404. this._tryEnableInteractionOnController = function (controller) {
  80405. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80406. _this._enableInteractionOnController(controller);
  80407. }
  80408. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80409. _this._enableTeleportationOnController(controller);
  80410. }
  80411. };
  80412. this._onNewGamepadDisconnected = function (gamepad) {
  80413. if (gamepad instanceof BABYLON.WebVRController) {
  80414. if (gamepad.hand === "left" && _this.leftController != null) {
  80415. _this.leftController.dispose();
  80416. _this.leftController = null;
  80417. }
  80418. if (gamepad.hand === "right" && _this.rightController != null) {
  80419. _this.rightController.dispose();
  80420. _this.rightController = null;
  80421. }
  80422. }
  80423. };
  80424. this._workingVector = BABYLON.Vector3.Zero();
  80425. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80426. this._workingMatrix = BABYLON.Matrix.Identity();
  80427. this._scene = scene;
  80428. this._canvas = scene.getEngine().getRenderingCanvas();
  80429. // Parse options
  80430. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80431. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80432. }
  80433. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80434. webVROptions.createDeviceOrientationCamera = true;
  80435. }
  80436. if (webVROptions.defaultHeight === undefined) {
  80437. webVROptions.defaultHeight = 1.7;
  80438. }
  80439. if (webVROptions.useCustomVRButton) {
  80440. this._useCustomVRButton = true;
  80441. if (webVROptions.customVRButton) {
  80442. this._btnVR = webVROptions.customVRButton;
  80443. }
  80444. }
  80445. if (webVROptions.rayLength) {
  80446. this._rayLength = webVROptions.rayLength;
  80447. }
  80448. this._defaultHeight = webVROptions.defaultHeight;
  80449. if (webVROptions.positionScale) {
  80450. this._rayLength *= webVROptions.positionScale;
  80451. this._defaultHeight *= webVROptions.positionScale;
  80452. }
  80453. // Set position
  80454. if (this._scene.activeCamera) {
  80455. this._position = this._scene.activeCamera.position.clone();
  80456. }
  80457. else {
  80458. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80459. }
  80460. // Set non-vr camera
  80461. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80462. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80463. // Copy data from existing camera
  80464. if (this._scene.activeCamera) {
  80465. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80466. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80467. // Set rotation from previous camera
  80468. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80469. var targetCamera = this._scene.activeCamera;
  80470. if (targetCamera.rotationQuaternion) {
  80471. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80472. }
  80473. else {
  80474. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80475. }
  80476. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80477. }
  80478. }
  80479. this._scene.activeCamera = this._deviceOrientationCamera;
  80480. if (this._canvas) {
  80481. this._scene.activeCamera.attachControl(this._canvas);
  80482. }
  80483. }
  80484. else {
  80485. this._existingCamera = this._scene.activeCamera;
  80486. }
  80487. // Create VR cameras
  80488. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80489. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80490. }
  80491. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80492. this._webVRCamera.useStandingMatrix();
  80493. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80494. // Create default button
  80495. if (!this._useCustomVRButton) {
  80496. this._btnVR = document.createElement("BUTTON");
  80497. this._btnVR.className = "babylonVRicon";
  80498. this._btnVR.id = "babylonVRiconbtn";
  80499. this._btnVR.title = "Click to switch to VR";
  80500. 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) }";
  80501. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80502. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80503. // css += ".babylonVRicon.vrdisplaysupported { }";
  80504. // css += ".babylonVRicon.vrdisplayready { }";
  80505. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80506. var style = document.createElement('style');
  80507. style.appendChild(document.createTextNode(css));
  80508. document.getElementsByTagName('head')[0].appendChild(style);
  80509. this.moveButtonToBottomRight();
  80510. }
  80511. // VR button click event
  80512. if (this._btnVR) {
  80513. this._btnVR.addEventListener("click", function () {
  80514. if (!_this.isInVRMode) {
  80515. _this.enterVR();
  80516. }
  80517. else {
  80518. _this.exitVR();
  80519. }
  80520. });
  80521. }
  80522. // Window events
  80523. window.addEventListener("resize", this._onResize);
  80524. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80525. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80526. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80527. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80528. // Display vr button when headset is connected
  80529. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80530. this.displayVRButton();
  80531. }
  80532. else {
  80533. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80534. if (e.vrDisplay) {
  80535. _this.displayVRButton();
  80536. }
  80537. });
  80538. }
  80539. // Exiting VR mode using 'ESC' key on desktop
  80540. this._onKeyDown = function (event) {
  80541. if (event.keyCode === 27 && _this.isInVRMode) {
  80542. _this.exitVR();
  80543. }
  80544. };
  80545. document.addEventListener("keydown", this._onKeyDown);
  80546. // Exiting VR mode double tapping the touch screen
  80547. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80548. if (_this.isInVRMode) {
  80549. _this.exitVR();
  80550. if (_this._fullscreenVRpresenting) {
  80551. _this._scene.getEngine().switchFullscreen(true);
  80552. }
  80553. }
  80554. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80555. // Listen for WebVR display changes
  80556. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80557. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80558. this._onVRRequestPresentStart = function () {
  80559. _this._webVRrequesting = true;
  80560. _this.updateButtonVisibility();
  80561. };
  80562. this._onVRRequestPresentComplete = function (success) {
  80563. _this._webVRrequesting = false;
  80564. _this.updateButtonVisibility();
  80565. };
  80566. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80567. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80568. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80569. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80570. scene.onDisposeObservable.add(function () {
  80571. _this.dispose();
  80572. });
  80573. // Gamepad connection events
  80574. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80575. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80576. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80577. this.updateButtonVisibility();
  80578. //create easing functions
  80579. this._circleEase = new BABYLON.CircleEase();
  80580. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80581. }
  80582. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80583. /** Return this.onEnteringVRObservable
  80584. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80585. */
  80586. get: function () {
  80587. return this.onEnteringVRObservable;
  80588. },
  80589. enumerable: true,
  80590. configurable: true
  80591. });
  80592. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80593. /** Return this.onExitingVRObservable
  80594. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80595. */
  80596. get: function () {
  80597. return this.onExitingVRObservable;
  80598. },
  80599. enumerable: true,
  80600. configurable: true
  80601. });
  80602. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80603. /** Return this.onControllerMeshLoadedObservable
  80604. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80605. */
  80606. get: function () {
  80607. return this.onControllerMeshLoadedObservable;
  80608. },
  80609. enumerable: true,
  80610. configurable: true
  80611. });
  80612. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80613. /**
  80614. * The mesh used to display where the user is going to teleport.
  80615. */
  80616. get: function () {
  80617. return this._teleportationTarget;
  80618. },
  80619. /**
  80620. * Sets the mesh to be used to display where the user is going to teleport.
  80621. */
  80622. set: function (value) {
  80623. if (value) {
  80624. value.name = "teleportationTarget";
  80625. this._isDefaultTeleportationTarget = false;
  80626. this._teleportationTarget = value;
  80627. }
  80628. },
  80629. enumerable: true,
  80630. configurable: true
  80631. });
  80632. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80633. /**
  80634. * The mesh used to display where the user is selecting,
  80635. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80636. * See http://doc.babylonjs.com/resources/baking_transformations
  80637. */
  80638. get: function () {
  80639. return this._cameraGazer._gazeTracker;
  80640. },
  80641. set: function (value) {
  80642. if (value) {
  80643. this._cameraGazer._gazeTracker = value;
  80644. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80645. this._cameraGazer._gazeTracker.isPickable = false;
  80646. this._cameraGazer._gazeTracker.isVisible = false;
  80647. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80648. if (this.leftController) {
  80649. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80650. }
  80651. if (this.rightController) {
  80652. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80653. }
  80654. }
  80655. },
  80656. enumerable: true,
  80657. configurable: true
  80658. });
  80659. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80660. /**
  80661. * If the ray of the gaze should be displayed.
  80662. */
  80663. get: function () {
  80664. return this._displayGaze;
  80665. },
  80666. /**
  80667. * Sets if the ray of the gaze should be displayed.
  80668. */
  80669. set: function (value) {
  80670. this._displayGaze = value;
  80671. if (!value) {
  80672. this._cameraGazer._gazeTracker.isVisible = false;
  80673. if (this.leftController) {
  80674. this.leftController._gazeTracker.isVisible = false;
  80675. }
  80676. if (this.rightController) {
  80677. this.rightController._gazeTracker.isVisible = false;
  80678. }
  80679. }
  80680. },
  80681. enumerable: true,
  80682. configurable: true
  80683. });
  80684. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80685. /**
  80686. * If the ray of the LaserPointer should be displayed.
  80687. */
  80688. get: function () {
  80689. return this._displayLaserPointer;
  80690. },
  80691. /**
  80692. * Sets if the ray of the LaserPointer should be displayed.
  80693. */
  80694. set: function (value) {
  80695. this._displayLaserPointer = value;
  80696. if (!value) {
  80697. if (this.rightController) {
  80698. this.rightController._deactivatePointer();
  80699. this.rightController._gazeTracker.isVisible = false;
  80700. }
  80701. if (this.leftController) {
  80702. this.leftController._deactivatePointer();
  80703. this.leftController._gazeTracker.isVisible = false;
  80704. }
  80705. }
  80706. else {
  80707. if (this.rightController) {
  80708. this.rightController._activatePointer();
  80709. }
  80710. else if (this.leftController) {
  80711. this.leftController._activatePointer();
  80712. }
  80713. }
  80714. },
  80715. enumerable: true,
  80716. configurable: true
  80717. });
  80718. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80719. /**
  80720. * The deviceOrientationCamera used as the camera when not in VR.
  80721. */
  80722. get: function () {
  80723. return this._deviceOrientationCamera;
  80724. },
  80725. enumerable: true,
  80726. configurable: true
  80727. });
  80728. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80729. /**
  80730. * Based on the current WebVR support, returns the current VR camera used.
  80731. */
  80732. get: function () {
  80733. if (this._webVRready) {
  80734. return this._webVRCamera;
  80735. }
  80736. else {
  80737. return this._scene.activeCamera;
  80738. }
  80739. },
  80740. enumerable: true,
  80741. configurable: true
  80742. });
  80743. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80744. /**
  80745. * The webVRCamera which is used when in VR.
  80746. */
  80747. get: function () {
  80748. return this._webVRCamera;
  80749. },
  80750. enumerable: true,
  80751. configurable: true
  80752. });
  80753. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80754. /**
  80755. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80756. */
  80757. get: function () {
  80758. return this._vrDeviceOrientationCamera;
  80759. },
  80760. enumerable: true,
  80761. configurable: true
  80762. });
  80763. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80764. get: function () {
  80765. var result = this._cameraGazer._teleportationRequestInitiated
  80766. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80767. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80768. return result;
  80769. },
  80770. enumerable: true,
  80771. configurable: true
  80772. });
  80773. // Raised when one of the controller has loaded successfully its associated default mesh
  80774. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80775. if (this.leftController && this.leftController.webVRController == webVRController) {
  80776. if (webVRController.mesh) {
  80777. this.leftController._setLaserPointerParent(webVRController.mesh);
  80778. }
  80779. }
  80780. if (this.rightController && this.rightController.webVRController == webVRController) {
  80781. if (webVRController.mesh) {
  80782. this.rightController._setLaserPointerParent(webVRController.mesh);
  80783. }
  80784. }
  80785. try {
  80786. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80787. }
  80788. catch (err) {
  80789. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80790. }
  80791. };
  80792. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80793. /**
  80794. * Gets a value indicating if we are currently in VR mode.
  80795. */
  80796. get: function () {
  80797. return this._webVRpresenting || this._fullscreenVRpresenting;
  80798. },
  80799. enumerable: true,
  80800. configurable: true
  80801. });
  80802. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80803. var vrDisplay = this._scene.getEngine().getVRDevice();
  80804. if (vrDisplay) {
  80805. var wasPresenting = this._webVRpresenting;
  80806. // A VR display is connected
  80807. this._webVRpresenting = vrDisplay.isPresenting;
  80808. if (wasPresenting && !this._webVRpresenting)
  80809. this.exitVR();
  80810. }
  80811. else {
  80812. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80813. }
  80814. this.updateButtonVisibility();
  80815. };
  80816. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80817. this._webVRsupported = eventArgs.vrSupported;
  80818. this._webVRready = !!eventArgs.vrDisplay;
  80819. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80820. this.updateButtonVisibility();
  80821. };
  80822. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80823. if (this._canvas && !this._useCustomVRButton) {
  80824. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80825. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80826. }
  80827. };
  80828. VRExperienceHelper.prototype.displayVRButton = function () {
  80829. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80830. document.body.appendChild(this._btnVR);
  80831. this._btnVRDisplayed = true;
  80832. }
  80833. };
  80834. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80835. if (!this._btnVR || this._useCustomVRButton) {
  80836. return;
  80837. }
  80838. this._btnVR.className = "babylonVRicon";
  80839. if (this.isInVRMode) {
  80840. this._btnVR.className += " vrdisplaypresenting";
  80841. }
  80842. else {
  80843. if (this._webVRready)
  80844. this._btnVR.className += " vrdisplayready";
  80845. if (this._webVRsupported)
  80846. this._btnVR.className += " vrdisplaysupported";
  80847. if (this._webVRrequesting)
  80848. this._btnVR.className += " vrdisplayrequesting";
  80849. }
  80850. };
  80851. /**
  80852. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80853. * Otherwise, will use the fullscreen API.
  80854. */
  80855. VRExperienceHelper.prototype.enterVR = function () {
  80856. if (this.onEnteringVRObservable) {
  80857. try {
  80858. this.onEnteringVRObservable.notifyObservers(this);
  80859. }
  80860. catch (err) {
  80861. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80862. }
  80863. }
  80864. if (this._scene.activeCamera) {
  80865. this._position = this._scene.activeCamera.position.clone();
  80866. // make sure that we return to the last active camera
  80867. this._existingCamera = this._scene.activeCamera;
  80868. }
  80869. if (this._webVRrequesting)
  80870. return;
  80871. // If WebVR is supported and a headset is connected
  80872. if (this._webVRready) {
  80873. if (!this._webVRpresenting) {
  80874. this._webVRCamera.position = this._position;
  80875. this._scene.activeCamera = this._webVRCamera;
  80876. }
  80877. }
  80878. else if (this._vrDeviceOrientationCamera) {
  80879. this._vrDeviceOrientationCamera.position = this._position;
  80880. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80881. this._scene.getEngine().switchFullscreen(true);
  80882. this.updateButtonVisibility();
  80883. }
  80884. if (this._scene.activeCamera && this._canvas) {
  80885. this._scene.activeCamera.attachControl(this._canvas);
  80886. }
  80887. if (this._interactionsEnabled) {
  80888. this._scene.registerBeforeRender(this.beforeRender);
  80889. }
  80890. };
  80891. /**
  80892. * Attempt to exit VR, or fullscreen.
  80893. */
  80894. VRExperienceHelper.prototype.exitVR = function () {
  80895. if (this.onExitingVRObservable) {
  80896. try {
  80897. this.onExitingVRObservable.notifyObservers(this);
  80898. }
  80899. catch (err) {
  80900. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80901. }
  80902. }
  80903. if (this._webVRpresenting) {
  80904. this._scene.getEngine().disableVR();
  80905. }
  80906. if (this._scene.activeCamera) {
  80907. this._position = this._scene.activeCamera.position.clone();
  80908. }
  80909. if (this._deviceOrientationCamera) {
  80910. this._deviceOrientationCamera.position = this._position;
  80911. this._scene.activeCamera = this._deviceOrientationCamera;
  80912. if (this._canvas) {
  80913. this._scene.activeCamera.attachControl(this._canvas);
  80914. }
  80915. }
  80916. else if (this._existingCamera) {
  80917. this._existingCamera.position = this._position;
  80918. this._scene.activeCamera = this._existingCamera;
  80919. }
  80920. this.updateButtonVisibility();
  80921. if (this._interactionsEnabled) {
  80922. this._scene.unregisterBeforeRender(this.beforeRender);
  80923. }
  80924. };
  80925. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80926. /**
  80927. * The position of the vr experience helper.
  80928. */
  80929. get: function () {
  80930. return this._position;
  80931. },
  80932. /**
  80933. * Sets the position of the vr experience helper.
  80934. */
  80935. set: function (value) {
  80936. this._position = value;
  80937. if (this._scene.activeCamera) {
  80938. this._scene.activeCamera.position = value;
  80939. }
  80940. },
  80941. enumerable: true,
  80942. configurable: true
  80943. });
  80944. /**
  80945. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80946. */
  80947. VRExperienceHelper.prototype.enableInteractions = function () {
  80948. var _this = this;
  80949. if (!this._interactionsEnabled) {
  80950. this._interactionsRequested = true;
  80951. if (this.leftController) {
  80952. this._enableInteractionOnController(this.leftController);
  80953. }
  80954. if (this.rightController) {
  80955. this._enableInteractionOnController(this.rightController);
  80956. }
  80957. this.raySelectionPredicate = function (mesh) {
  80958. return mesh.isVisible;
  80959. };
  80960. this.meshSelectionPredicate = function (mesh) {
  80961. return true;
  80962. };
  80963. this._raySelectionPredicate = function (mesh) {
  80964. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  80965. && mesh.name.indexOf("teleportationTarget") === -1
  80966. && mesh.name.indexOf("torusTeleportation") === -1
  80967. && mesh.name.indexOf("laserPointer") === -1)) {
  80968. return _this.raySelectionPredicate(mesh);
  80969. }
  80970. return false;
  80971. };
  80972. this._interactionsEnabled = true;
  80973. }
  80974. };
  80975. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80976. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80977. if (this._floorMeshesCollection[i].id === mesh.id) {
  80978. return true;
  80979. }
  80980. }
  80981. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80982. return true;
  80983. }
  80984. return false;
  80985. };
  80986. /**
  80987. * Adds a floor mesh to be used for teleportation.
  80988. * @param floorMesh the mesh to be used for teleportation.
  80989. */
  80990. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80991. if (!this._floorMeshesCollection) {
  80992. return;
  80993. }
  80994. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80995. return;
  80996. }
  80997. this._floorMeshesCollection.push(floorMesh);
  80998. };
  80999. /**
  81000. * Removes a floor mesh from being used for teleportation.
  81001. * @param floorMesh the mesh to be removed.
  81002. */
  81003. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  81004. if (!this._floorMeshesCollection) {
  81005. return;
  81006. }
  81007. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  81008. if (meshIndex !== -1) {
  81009. this._floorMeshesCollection.splice(meshIndex, 1);
  81010. }
  81011. };
  81012. /**
  81013. * Enables interactions and teleportation using the VR controllers and gaze.
  81014. * @param vrTeleportationOptions options to modify teleportation behavior.
  81015. */
  81016. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  81017. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  81018. if (!this._teleportationInitialized) {
  81019. this._teleportationRequested = true;
  81020. this.enableInteractions();
  81021. if (vrTeleportationOptions.floorMeshName) {
  81022. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  81023. }
  81024. if (vrTeleportationOptions.floorMeshes) {
  81025. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  81026. }
  81027. if (this.leftController != null) {
  81028. this._enableTeleportationOnController(this.leftController);
  81029. }
  81030. if (this.rightController != null) {
  81031. this._enableTeleportationOnController(this.rightController);
  81032. }
  81033. // Creates an image processing post process for the vignette not relying
  81034. // on the main scene configuration for image processing to reduce setup and spaces
  81035. // (gamma/linear) conflicts.
  81036. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  81037. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81038. imageProcessingConfiguration.vignetteEnabled = true;
  81039. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  81040. this._webVRCamera.detachPostProcess(this._postProcessMove);
  81041. this._teleportationInitialized = true;
  81042. if (this._isDefaultTeleportationTarget) {
  81043. this._createTeleportationCircles();
  81044. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  81045. }
  81046. }
  81047. };
  81048. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  81049. var _this = this;
  81050. var controllerMesh = controller.webVRController.mesh;
  81051. if (controllerMesh) {
  81052. controller._interactionsEnabled = true;
  81053. controller._activatePointer();
  81054. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  81055. // Enabling / disabling laserPointer
  81056. if (_this._displayLaserPointer && stateObject.value === 1) {
  81057. if (controller._activePointer) {
  81058. controller._deactivatePointer();
  81059. }
  81060. else {
  81061. controller._activatePointer();
  81062. }
  81063. if (_this.displayGaze) {
  81064. controller._gazeTracker.isVisible = controller._activePointer;
  81065. }
  81066. }
  81067. });
  81068. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  81069. if (!controller._pointerDownOnMeshAsked) {
  81070. if (stateObject.value > _this._padSensibilityUp) {
  81071. controller._selectionPointerDown();
  81072. }
  81073. }
  81074. else if (stateObject.value < _this._padSensibilityDown) {
  81075. controller._selectionPointerUp();
  81076. }
  81077. });
  81078. }
  81079. };
  81080. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  81081. // Dont teleport if another gaze already requested teleportation
  81082. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  81083. return;
  81084. }
  81085. if (!gazer._teleportationRequestInitiated) {
  81086. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  81087. gazer._activatePointer();
  81088. gazer._teleportationRequestInitiated = true;
  81089. }
  81090. }
  81091. else {
  81092. // Listening to the proper controller values changes to confirm teleportation
  81093. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  81094. if (this._teleportActive) {
  81095. this._teleportCamera(this._haloCenter);
  81096. }
  81097. gazer._teleportationRequestInitiated = false;
  81098. }
  81099. }
  81100. };
  81101. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  81102. // Only rotate when user is not currently selecting a teleportation location
  81103. if (gazer._teleportationRequestInitiated) {
  81104. return;
  81105. }
  81106. if (!this._rotationLeftAsked) {
  81107. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  81108. this._rotationLeftAsked = true;
  81109. if (this._rotationAllowed) {
  81110. this._rotateCamera(false);
  81111. }
  81112. }
  81113. }
  81114. else {
  81115. if (stateObject.x > -this._padSensibilityDown) {
  81116. this._rotationLeftAsked = false;
  81117. }
  81118. }
  81119. if (!this._rotationRightAsked) {
  81120. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  81121. this._rotationRightAsked = true;
  81122. if (this._rotationAllowed) {
  81123. this._rotateCamera(true);
  81124. }
  81125. }
  81126. }
  81127. else {
  81128. if (stateObject.x < this._padSensibilityDown) {
  81129. this._rotationRightAsked = false;
  81130. }
  81131. }
  81132. };
  81133. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  81134. // Only teleport backwards when user is not currently selecting a teleportation location
  81135. if (gazer._teleportationRequestInitiated) {
  81136. return;
  81137. }
  81138. // Teleport backwards
  81139. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  81140. if (!gazer._teleportationBackRequestInitiated) {
  81141. if (!this.currentVRCamera) {
  81142. return;
  81143. }
  81144. // Get rotation and position of the current camera
  81145. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  81146. var position = this.currentVRCamera.position;
  81147. // If the camera has device position, use that instead
  81148. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  81149. rotation = this.currentVRCamera.deviceRotationQuaternion;
  81150. position = this.currentVRCamera.devicePosition;
  81151. }
  81152. // Get matrix with only the y rotation of the device rotation
  81153. rotation.toEulerAnglesToRef(this._workingVector);
  81154. this._workingVector.z = 0;
  81155. this._workingVector.x = 0;
  81156. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  81157. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  81158. // Rotate backwards ray by device rotation to cast at the ground behind the user
  81159. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  81160. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  81161. var ray = new BABYLON.Ray(position, this._workingVector);
  81162. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81163. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  81164. this._teleportCamera(hit.pickedPoint);
  81165. }
  81166. gazer._teleportationBackRequestInitiated = true;
  81167. }
  81168. }
  81169. else {
  81170. gazer._teleportationBackRequestInitiated = false;
  81171. }
  81172. };
  81173. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  81174. var _this = this;
  81175. var controllerMesh = controller.webVRController.mesh;
  81176. if (controllerMesh) {
  81177. if (!controller._interactionsEnabled) {
  81178. this._enableInteractionOnController(controller);
  81179. }
  81180. controller._interactionsEnabled = true;
  81181. controller._teleportationEnabled = true;
  81182. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81183. controller._dpadPressed = false;
  81184. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  81185. controller._dpadPressed = stateObject.pressed;
  81186. if (!controller._dpadPressed) {
  81187. _this._rotationLeftAsked = false;
  81188. _this._rotationRightAsked = false;
  81189. controller._teleportationBackRequestInitiated = false;
  81190. }
  81191. });
  81192. }
  81193. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  81194. if (_this.teleportationEnabled) {
  81195. _this._checkTeleportBackwards(stateObject, controller);
  81196. _this._checkTeleportWithRay(stateObject, controller);
  81197. }
  81198. _this._checkRotate(stateObject, controller);
  81199. });
  81200. }
  81201. };
  81202. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  81203. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  81204. this._teleportationTarget.isPickable = false;
  81205. var length = 512;
  81206. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  81207. dynamicTexture.hasAlpha = true;
  81208. var context = dynamicTexture.getContext();
  81209. var centerX = length / 2;
  81210. var centerY = length / 2;
  81211. var radius = 200;
  81212. context.beginPath();
  81213. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  81214. context.fillStyle = this._teleportationFillColor;
  81215. context.fill();
  81216. context.lineWidth = 10;
  81217. context.strokeStyle = this._teleportationBorderColor;
  81218. context.stroke();
  81219. context.closePath();
  81220. dynamicTexture.update();
  81221. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  81222. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  81223. this._teleportationTarget.material = teleportationCircleMaterial;
  81224. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  81225. torus.isPickable = false;
  81226. torus.parent = this._teleportationTarget;
  81227. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  81228. var keys = [];
  81229. keys.push({
  81230. frame: 0,
  81231. value: 0
  81232. });
  81233. keys.push({
  81234. frame: 30,
  81235. value: 0.4
  81236. });
  81237. keys.push({
  81238. frame: 60,
  81239. value: 0
  81240. });
  81241. animationInnerCircle.setKeys(keys);
  81242. var easingFunction = new BABYLON.SineEase();
  81243. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81244. animationInnerCircle.setEasingFunction(easingFunction);
  81245. torus.animations = [];
  81246. torus.animations.push(animationInnerCircle);
  81247. this._scene.beginAnimation(torus, 0, 60, true);
  81248. this._hideTeleportationTarget();
  81249. };
  81250. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81251. this._teleportActive = true;
  81252. if (this._teleportationInitialized) {
  81253. this._teleportationTarget.isVisible = true;
  81254. if (this._isDefaultTeleportationTarget) {
  81255. this._teleportationTarget.getChildren()[0].isVisible = true;
  81256. }
  81257. }
  81258. };
  81259. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81260. this._teleportActive = false;
  81261. if (this._teleportationInitialized) {
  81262. this._teleportationTarget.isVisible = false;
  81263. if (this._isDefaultTeleportationTarget) {
  81264. this._teleportationTarget.getChildren()[0].isVisible = false;
  81265. }
  81266. }
  81267. };
  81268. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81269. var _this = this;
  81270. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81271. return;
  81272. }
  81273. if (right) {
  81274. this._rotationAngle++;
  81275. }
  81276. else {
  81277. this._rotationAngle--;
  81278. }
  81279. this.currentVRCamera.animations = [];
  81280. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81281. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81282. var animationRotationKeys = [];
  81283. animationRotationKeys.push({
  81284. frame: 0,
  81285. value: this.currentVRCamera.rotationQuaternion
  81286. });
  81287. animationRotationKeys.push({
  81288. frame: 6,
  81289. value: target
  81290. });
  81291. animationRotation.setKeys(animationRotationKeys);
  81292. animationRotation.setEasingFunction(this._circleEase);
  81293. this.currentVRCamera.animations.push(animationRotation);
  81294. this._postProcessMove.animations = [];
  81295. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81296. var vignetteWeightKeys = [];
  81297. vignetteWeightKeys.push({
  81298. frame: 0,
  81299. value: 0
  81300. });
  81301. vignetteWeightKeys.push({
  81302. frame: 3,
  81303. value: 4
  81304. });
  81305. vignetteWeightKeys.push({
  81306. frame: 6,
  81307. value: 0
  81308. });
  81309. animationPP.setKeys(vignetteWeightKeys);
  81310. animationPP.setEasingFunction(this._circleEase);
  81311. this._postProcessMove.animations.push(animationPP);
  81312. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81313. var vignetteStretchKeys = [];
  81314. vignetteStretchKeys.push({
  81315. frame: 0,
  81316. value: 0
  81317. });
  81318. vignetteStretchKeys.push({
  81319. frame: 3,
  81320. value: 10
  81321. });
  81322. vignetteStretchKeys.push({
  81323. frame: 6,
  81324. value: 0
  81325. });
  81326. animationPP2.setKeys(vignetteStretchKeys);
  81327. animationPP2.setEasingFunction(this._circleEase);
  81328. this._postProcessMove.animations.push(animationPP2);
  81329. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81330. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81331. this._postProcessMove.samples = 4;
  81332. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81333. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81334. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81335. });
  81336. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81337. };
  81338. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81339. if (hit.pickedPoint) {
  81340. if (gazer._teleportationRequestInitiated) {
  81341. this._displayTeleportationTarget();
  81342. this._haloCenter.copyFrom(hit.pickedPoint);
  81343. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81344. }
  81345. var pickNormal = hit.getNormal(true, false);
  81346. if (pickNormal) {
  81347. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81348. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81349. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81350. }
  81351. this._teleportationTarget.position.y += 0.1;
  81352. }
  81353. };
  81354. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81355. var _this = this;
  81356. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81357. return;
  81358. }
  81359. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81360. // offset of the headset from the anchor.
  81361. if (this.webVRCamera.leftCamera) {
  81362. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81363. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81364. location.subtractToRef(this._workingVector, this._workingVector);
  81365. }
  81366. else {
  81367. this._workingVector.copyFrom(location);
  81368. }
  81369. // Add height to account for user's height offset
  81370. if (this.isInVRMode) {
  81371. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  81372. }
  81373. else {
  81374. this._workingVector.y += this._defaultHeight;
  81375. }
  81376. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81377. // Create animation from the camera's position to the new location
  81378. this.currentVRCamera.animations = [];
  81379. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81380. var animationCameraTeleportationKeys = [{
  81381. frame: 0,
  81382. value: this.currentVRCamera.position
  81383. },
  81384. {
  81385. frame: 11,
  81386. value: this._workingVector
  81387. }
  81388. ];
  81389. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81390. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81391. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81392. this._postProcessMove.animations = [];
  81393. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81394. var vignetteWeightKeys = [];
  81395. vignetteWeightKeys.push({
  81396. frame: 0,
  81397. value: 0
  81398. });
  81399. vignetteWeightKeys.push({
  81400. frame: 5,
  81401. value: 8
  81402. });
  81403. vignetteWeightKeys.push({
  81404. frame: 11,
  81405. value: 0
  81406. });
  81407. animationPP.setKeys(vignetteWeightKeys);
  81408. this._postProcessMove.animations.push(animationPP);
  81409. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81410. var vignetteStretchKeys = [];
  81411. vignetteStretchKeys.push({
  81412. frame: 0,
  81413. value: 0
  81414. });
  81415. vignetteStretchKeys.push({
  81416. frame: 5,
  81417. value: 10
  81418. });
  81419. vignetteStretchKeys.push({
  81420. frame: 11,
  81421. value: 0
  81422. });
  81423. animationPP2.setKeys(vignetteStretchKeys);
  81424. this._postProcessMove.animations.push(animationPP2);
  81425. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81426. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81427. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81428. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81429. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81430. });
  81431. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81432. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81433. });
  81434. this._hideTeleportationTarget();
  81435. };
  81436. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81437. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81438. return;
  81439. }
  81440. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81441. // Moving the gazeTracker on the mesh face targetted
  81442. if (hit && hit.pickedPoint) {
  81443. if (this._displayGaze) {
  81444. var multiplier = 1;
  81445. gazer._gazeTracker.isVisible = true;
  81446. if (gazer._isActionableMesh) {
  81447. multiplier = 3;
  81448. }
  81449. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81450. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81451. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81452. var pickNormal = hit.getNormal();
  81453. // To avoid z-fighting
  81454. var deltaFighting = 0.002;
  81455. if (pickNormal) {
  81456. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81457. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81458. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81459. }
  81460. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81461. if (gazer._gazeTracker.position.x < 0) {
  81462. gazer._gazeTracker.position.x += deltaFighting;
  81463. }
  81464. else {
  81465. gazer._gazeTracker.position.x -= deltaFighting;
  81466. }
  81467. if (gazer._gazeTracker.position.y < 0) {
  81468. gazer._gazeTracker.position.y += deltaFighting;
  81469. }
  81470. else {
  81471. gazer._gazeTracker.position.y -= deltaFighting;
  81472. }
  81473. if (gazer._gazeTracker.position.z < 0) {
  81474. gazer._gazeTracker.position.z += deltaFighting;
  81475. }
  81476. else {
  81477. gazer._gazeTracker.position.z -= deltaFighting;
  81478. }
  81479. }
  81480. // Changing the size of the laser pointer based on the distance from the targetted point
  81481. gazer._updatePointerDistance(hit.distance);
  81482. }
  81483. else {
  81484. gazer._gazeTracker.isVisible = false;
  81485. }
  81486. if (hit && hit.pickedMesh) {
  81487. gazer._currentHit = hit;
  81488. if (gazer._pointerDownOnMeshAsked) {
  81489. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81490. }
  81491. // The object selected is the floor, we're in a teleportation scenario
  81492. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81493. // Moving the teleportation area to this targetted point
  81494. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81495. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81496. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81497. }
  81498. gazer._currentMeshSelected = null;
  81499. if (gazer._teleportationRequestInitiated) {
  81500. this._moveTeleportationSelectorTo(hit, gazer);
  81501. }
  81502. return;
  81503. }
  81504. // If not, we're in a selection scenario
  81505. //this._teleportationAllowed = false;
  81506. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81507. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81508. this.onNewMeshPicked.notifyObservers(hit);
  81509. gazer._currentMeshSelected = hit.pickedMesh;
  81510. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81511. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81512. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81513. gazer._isActionableMesh = true;
  81514. }
  81515. else {
  81516. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81517. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81518. gazer._isActionableMesh = false;
  81519. }
  81520. try {
  81521. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81522. }
  81523. catch (err) {
  81524. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81525. }
  81526. }
  81527. else {
  81528. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81529. gazer._currentMeshSelected = null;
  81530. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81531. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81532. }
  81533. }
  81534. }
  81535. else {
  81536. gazer._currentHit = null;
  81537. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81538. gazer._currentMeshSelected = null;
  81539. //this._teleportationAllowed = false;
  81540. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81541. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81542. }
  81543. };
  81544. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81545. if (mesh) {
  81546. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81547. }
  81548. };
  81549. /**
  81550. * Sets the color of the laser ray from the vr controllers.
  81551. * @param color new color for the ray.
  81552. */
  81553. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81554. if (this.leftController) {
  81555. this.leftController._setLaserPointerColor(color);
  81556. }
  81557. if (this.rightController) {
  81558. this.rightController._setLaserPointerColor(color);
  81559. }
  81560. };
  81561. /**
  81562. * Sets the color of the ray from the vr headsets gaze.
  81563. * @param color new color for the ray.
  81564. */
  81565. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81566. if (!this._cameraGazer._gazeTracker.material) {
  81567. return;
  81568. }
  81569. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81570. if (this.leftController) {
  81571. this.leftController._gazeTracker.material.emissiveColor = color;
  81572. }
  81573. if (this.rightController) {
  81574. this.rightController._gazeTracker.material.emissiveColor = color;
  81575. }
  81576. };
  81577. /**
  81578. * Exits VR and disposes of the vr experience helper
  81579. */
  81580. VRExperienceHelper.prototype.dispose = function () {
  81581. if (this.isInVRMode) {
  81582. this.exitVR();
  81583. }
  81584. if (this._postProcessMove) {
  81585. this._postProcessMove.dispose();
  81586. }
  81587. if (this._webVRCamera) {
  81588. this._webVRCamera.dispose();
  81589. }
  81590. if (this._vrDeviceOrientationCamera) {
  81591. this._vrDeviceOrientationCamera.dispose();
  81592. }
  81593. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81594. document.body.removeChild(this._btnVR);
  81595. }
  81596. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81597. this._deviceOrientationCamera.dispose();
  81598. }
  81599. if (this._cameraGazer) {
  81600. this._cameraGazer.dispose();
  81601. }
  81602. if (this.leftController) {
  81603. this.leftController.dispose();
  81604. }
  81605. if (this.rightController) {
  81606. this.rightController.dispose();
  81607. }
  81608. if (this._teleportationTarget) {
  81609. this._teleportationTarget.dispose();
  81610. }
  81611. this._floorMeshesCollection = [];
  81612. document.removeEventListener("keydown", this._onKeyDown);
  81613. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81614. window.removeEventListener("resize", this._onResize);
  81615. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81616. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81617. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81618. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81619. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81620. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81621. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81622. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81623. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81624. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81625. this._scene.unregisterBeforeRender(this.beforeRender);
  81626. };
  81627. /**
  81628. * Gets the name of the VRExperienceHelper class
  81629. * @returns "VRExperienceHelper"
  81630. */
  81631. VRExperienceHelper.prototype.getClassName = function () {
  81632. return "VRExperienceHelper";
  81633. };
  81634. return VRExperienceHelper;
  81635. }());
  81636. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81637. })(BABYLON || (BABYLON = {}));
  81638. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81639. // Mainly based on these 2 articles :
  81640. // 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
  81641. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81642. var BABYLON;
  81643. (function (BABYLON) {
  81644. var JoystickAxis;
  81645. (function (JoystickAxis) {
  81646. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81647. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81648. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81649. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81650. var VirtualJoystick = /** @class */ (function () {
  81651. function VirtualJoystick(leftJoystick) {
  81652. var _this = this;
  81653. if (leftJoystick) {
  81654. this._leftJoystick = true;
  81655. }
  81656. else {
  81657. this._leftJoystick = false;
  81658. }
  81659. VirtualJoystick._globalJoystickIndex++;
  81660. // By default left & right arrow keys are moving the X
  81661. // and up & down keys are moving the Y
  81662. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81663. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81664. this.reverseLeftRight = false;
  81665. this.reverseUpDown = false;
  81666. // collections of pointers
  81667. this._touches = new BABYLON.StringDictionary();
  81668. this.deltaPosition = BABYLON.Vector3.Zero();
  81669. this._joystickSensibility = 25;
  81670. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81671. this._onResize = function (evt) {
  81672. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81673. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81674. if (VirtualJoystick.vjCanvas) {
  81675. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81676. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81677. }
  81678. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81679. };
  81680. // injecting a canvas element on top of the canvas 3D game
  81681. if (!VirtualJoystick.vjCanvas) {
  81682. window.addEventListener("resize", this._onResize, false);
  81683. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81684. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81685. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81686. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81687. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81688. VirtualJoystick.vjCanvas.style.width = "100%";
  81689. VirtualJoystick.vjCanvas.style.height = "100%";
  81690. VirtualJoystick.vjCanvas.style.position = "absolute";
  81691. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81692. VirtualJoystick.vjCanvas.style.top = "0px";
  81693. VirtualJoystick.vjCanvas.style.left = "0px";
  81694. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81695. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81696. // Support for jQuery PEP polyfill
  81697. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81698. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81699. if (!context) {
  81700. throw new Error("Unable to create canvas for virtual joystick");
  81701. }
  81702. VirtualJoystick.vjCanvasContext = context;
  81703. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81704. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81705. document.body.appendChild(VirtualJoystick.vjCanvas);
  81706. }
  81707. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81708. this.pressed = false;
  81709. // default joystick color
  81710. this._joystickColor = "cyan";
  81711. this._joystickPointerID = -1;
  81712. // current joystick position
  81713. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81714. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81715. // origin joystick position
  81716. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81717. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81718. this._onPointerDownHandlerRef = function (evt) {
  81719. _this._onPointerDown(evt);
  81720. };
  81721. this._onPointerMoveHandlerRef = function (evt) {
  81722. _this._onPointerMove(evt);
  81723. };
  81724. this._onPointerUpHandlerRef = function (evt) {
  81725. _this._onPointerUp(evt);
  81726. };
  81727. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81728. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81729. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81730. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81731. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81732. evt.preventDefault(); // Disables system menu
  81733. }, false);
  81734. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81735. }
  81736. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81737. this._joystickSensibility = newJoystickSensibility;
  81738. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81739. };
  81740. VirtualJoystick.prototype._onPointerDown = function (e) {
  81741. var positionOnScreenCondition;
  81742. e.preventDefault();
  81743. if (this._leftJoystick === true) {
  81744. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81745. }
  81746. else {
  81747. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81748. }
  81749. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81750. // First contact will be dedicated to the virtual joystick
  81751. this._joystickPointerID = e.pointerId;
  81752. this._joystickPointerStartPos.x = e.clientX;
  81753. this._joystickPointerStartPos.y = e.clientY;
  81754. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81755. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81756. this._deltaJoystickVector.x = 0;
  81757. this._deltaJoystickVector.y = 0;
  81758. this.pressed = true;
  81759. this._touches.add(e.pointerId.toString(), e);
  81760. }
  81761. else {
  81762. // You can only trigger the action buttons with a joystick declared
  81763. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81764. this._action();
  81765. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81766. }
  81767. }
  81768. };
  81769. VirtualJoystick.prototype._onPointerMove = function (e) {
  81770. // If the current pointer is the one associated to the joystick (first touch contact)
  81771. if (this._joystickPointerID == e.pointerId) {
  81772. this._joystickPointerPos.x = e.clientX;
  81773. this._joystickPointerPos.y = e.clientY;
  81774. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81775. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81776. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81777. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81778. switch (this._axisTargetedByLeftAndRight) {
  81779. case JoystickAxis.X:
  81780. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81781. break;
  81782. case JoystickAxis.Y:
  81783. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81784. break;
  81785. case JoystickAxis.Z:
  81786. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81787. break;
  81788. }
  81789. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81790. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81791. switch (this._axisTargetedByUpAndDown) {
  81792. case JoystickAxis.X:
  81793. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81794. break;
  81795. case JoystickAxis.Y:
  81796. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81797. break;
  81798. case JoystickAxis.Z:
  81799. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81800. break;
  81801. }
  81802. }
  81803. else {
  81804. var data = this._touches.get(e.pointerId.toString());
  81805. if (data) {
  81806. data.x = e.clientX;
  81807. data.y = e.clientY;
  81808. }
  81809. }
  81810. };
  81811. VirtualJoystick.prototype._onPointerUp = function (e) {
  81812. if (this._joystickPointerID == e.pointerId) {
  81813. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81814. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81815. this._joystickPointerID = -1;
  81816. this.pressed = false;
  81817. }
  81818. else {
  81819. var touch = this._touches.get(e.pointerId.toString());
  81820. if (touch) {
  81821. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81822. }
  81823. }
  81824. this._deltaJoystickVector.x = 0;
  81825. this._deltaJoystickVector.y = 0;
  81826. this._touches.remove(e.pointerId.toString());
  81827. };
  81828. /**
  81829. * Change the color of the virtual joystick
  81830. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81831. */
  81832. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81833. this._joystickColor = newColor;
  81834. };
  81835. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81836. this._action = action;
  81837. };
  81838. // Define which axis you'd like to control for left & right
  81839. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81840. switch (axis) {
  81841. case JoystickAxis.X:
  81842. case JoystickAxis.Y:
  81843. case JoystickAxis.Z:
  81844. this._axisTargetedByLeftAndRight = axis;
  81845. break;
  81846. default:
  81847. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81848. break;
  81849. }
  81850. };
  81851. // Define which axis you'd like to control for up & down
  81852. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81853. switch (axis) {
  81854. case JoystickAxis.X:
  81855. case JoystickAxis.Y:
  81856. case JoystickAxis.Z:
  81857. this._axisTargetedByUpAndDown = axis;
  81858. break;
  81859. default:
  81860. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81861. break;
  81862. }
  81863. };
  81864. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81865. var _this = this;
  81866. if (this.pressed) {
  81867. this._touches.forEach(function (key, touch) {
  81868. if (touch.pointerId === _this._joystickPointerID) {
  81869. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81870. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81871. VirtualJoystick.vjCanvasContext.beginPath();
  81872. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81873. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81874. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81875. VirtualJoystick.vjCanvasContext.stroke();
  81876. VirtualJoystick.vjCanvasContext.closePath();
  81877. VirtualJoystick.vjCanvasContext.beginPath();
  81878. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81879. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81880. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81881. VirtualJoystick.vjCanvasContext.stroke();
  81882. VirtualJoystick.vjCanvasContext.closePath();
  81883. VirtualJoystick.vjCanvasContext.beginPath();
  81884. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81885. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81886. VirtualJoystick.vjCanvasContext.stroke();
  81887. VirtualJoystick.vjCanvasContext.closePath();
  81888. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81889. }
  81890. else {
  81891. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81892. VirtualJoystick.vjCanvasContext.beginPath();
  81893. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81894. VirtualJoystick.vjCanvasContext.beginPath();
  81895. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81896. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81897. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81898. VirtualJoystick.vjCanvasContext.stroke();
  81899. VirtualJoystick.vjCanvasContext.closePath();
  81900. touch.prevX = touch.x;
  81901. touch.prevY = touch.y;
  81902. }
  81903. ;
  81904. });
  81905. }
  81906. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81907. };
  81908. VirtualJoystick.prototype.releaseCanvas = function () {
  81909. if (VirtualJoystick.vjCanvas) {
  81910. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81911. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81912. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81913. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81914. window.removeEventListener("resize", this._onResize);
  81915. document.body.removeChild(VirtualJoystick.vjCanvas);
  81916. VirtualJoystick.vjCanvas = null;
  81917. }
  81918. };
  81919. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81920. VirtualJoystick._globalJoystickIndex = 0;
  81921. return VirtualJoystick;
  81922. }());
  81923. BABYLON.VirtualJoystick = VirtualJoystick;
  81924. })(BABYLON || (BABYLON = {}));
  81925. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81926. var BABYLON;
  81927. (function (BABYLON) {
  81928. // We're mainly based on the logic defined into the FreeCamera code
  81929. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81930. __extends(VirtualJoysticksCamera, _super);
  81931. function VirtualJoysticksCamera(name, position, scene) {
  81932. var _this = _super.call(this, name, position, scene) || this;
  81933. _this.inputs.addVirtualJoystick();
  81934. return _this;
  81935. }
  81936. VirtualJoysticksCamera.prototype.getClassName = function () {
  81937. return "VirtualJoysticksCamera";
  81938. };
  81939. return VirtualJoysticksCamera;
  81940. }(BABYLON.FreeCamera));
  81941. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81942. })(BABYLON || (BABYLON = {}));
  81943. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81944. var BABYLON;
  81945. (function (BABYLON) {
  81946. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81947. function FreeCameraVirtualJoystickInput() {
  81948. }
  81949. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81950. return this._leftjoystick;
  81951. };
  81952. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81953. return this._rightjoystick;
  81954. };
  81955. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81956. if (this._leftjoystick) {
  81957. var camera = this.camera;
  81958. var speed = camera._computeLocalCameraSpeed() * 50;
  81959. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81960. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81961. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81962. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81963. if (!this._leftjoystick.pressed) {
  81964. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81965. }
  81966. if (!this._rightjoystick.pressed) {
  81967. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81968. }
  81969. }
  81970. };
  81971. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81972. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81973. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81974. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81975. this._leftjoystick.setJoystickSensibility(0.15);
  81976. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81977. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81978. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81979. this._rightjoystick.reverseUpDown = true;
  81980. this._rightjoystick.setJoystickSensibility(0.05);
  81981. this._rightjoystick.setJoystickColor("yellow");
  81982. };
  81983. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81984. this._leftjoystick.releaseCanvas();
  81985. this._rightjoystick.releaseCanvas();
  81986. };
  81987. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81988. return "FreeCameraVirtualJoystickInput";
  81989. };
  81990. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81991. return "virtualJoystick";
  81992. };
  81993. return FreeCameraVirtualJoystickInput;
  81994. }());
  81995. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81996. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81997. })(BABYLON || (BABYLON = {}));
  81998. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81999. var BABYLON;
  82000. (function (BABYLON) {
  82001. var SimplificationSettings = /** @class */ (function () {
  82002. function SimplificationSettings(quality, distance, optimizeMesh) {
  82003. this.quality = quality;
  82004. this.distance = distance;
  82005. this.optimizeMesh = optimizeMesh;
  82006. }
  82007. return SimplificationSettings;
  82008. }());
  82009. BABYLON.SimplificationSettings = SimplificationSettings;
  82010. var SimplificationQueue = /** @class */ (function () {
  82011. function SimplificationQueue() {
  82012. this.running = false;
  82013. this._simplificationArray = [];
  82014. }
  82015. SimplificationQueue.prototype.addTask = function (task) {
  82016. this._simplificationArray.push(task);
  82017. };
  82018. SimplificationQueue.prototype.executeNext = function () {
  82019. var task = this._simplificationArray.pop();
  82020. if (task) {
  82021. this.running = true;
  82022. this.runSimplification(task);
  82023. }
  82024. else {
  82025. this.running = false;
  82026. }
  82027. };
  82028. SimplificationQueue.prototype.runSimplification = function (task) {
  82029. var _this = this;
  82030. if (task.parallelProcessing) {
  82031. //parallel simplifier
  82032. task.settings.forEach(function (setting) {
  82033. var simplifier = _this.getSimplifier(task);
  82034. simplifier.simplify(setting, function (newMesh) {
  82035. task.mesh.addLODLevel(setting.distance, newMesh);
  82036. newMesh.isVisible = true;
  82037. //check if it is the last
  82038. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  82039. //all done, run the success callback.
  82040. task.successCallback();
  82041. }
  82042. _this.executeNext();
  82043. });
  82044. });
  82045. }
  82046. else {
  82047. //single simplifier.
  82048. var simplifier = this.getSimplifier(task);
  82049. var runDecimation = function (setting, callback) {
  82050. simplifier.simplify(setting, function (newMesh) {
  82051. task.mesh.addLODLevel(setting.distance, newMesh);
  82052. newMesh.isVisible = true;
  82053. //run the next quality level
  82054. callback();
  82055. });
  82056. };
  82057. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  82058. runDecimation(task.settings[loop.index], function () {
  82059. loop.executeNext();
  82060. });
  82061. }, function () {
  82062. //execution ended, run the success callback.
  82063. if (task.successCallback) {
  82064. task.successCallback();
  82065. }
  82066. _this.executeNext();
  82067. });
  82068. }
  82069. };
  82070. SimplificationQueue.prototype.getSimplifier = function (task) {
  82071. switch (task.simplificationType) {
  82072. case SimplificationType.QUADRATIC:
  82073. default:
  82074. return new QuadraticErrorSimplification(task.mesh);
  82075. }
  82076. };
  82077. return SimplificationQueue;
  82078. }());
  82079. BABYLON.SimplificationQueue = SimplificationQueue;
  82080. /**
  82081. * The implemented types of simplification.
  82082. * At the moment only Quadratic Error Decimation is implemented.
  82083. */
  82084. var SimplificationType;
  82085. (function (SimplificationType) {
  82086. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  82087. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  82088. var DecimationTriangle = /** @class */ (function () {
  82089. function DecimationTriangle(vertices) {
  82090. this.vertices = vertices;
  82091. this.error = new Array(4);
  82092. this.deleted = false;
  82093. this.isDirty = false;
  82094. this.deletePending = false;
  82095. this.borderFactor = 0;
  82096. }
  82097. return DecimationTriangle;
  82098. }());
  82099. BABYLON.DecimationTriangle = DecimationTriangle;
  82100. var DecimationVertex = /** @class */ (function () {
  82101. function DecimationVertex(position, id) {
  82102. this.position = position;
  82103. this.id = id;
  82104. this.isBorder = true;
  82105. this.q = new QuadraticMatrix();
  82106. this.triangleCount = 0;
  82107. this.triangleStart = 0;
  82108. this.originalOffsets = [];
  82109. }
  82110. DecimationVertex.prototype.updatePosition = function (newPosition) {
  82111. this.position.copyFrom(newPosition);
  82112. };
  82113. return DecimationVertex;
  82114. }());
  82115. BABYLON.DecimationVertex = DecimationVertex;
  82116. var QuadraticMatrix = /** @class */ (function () {
  82117. function QuadraticMatrix(data) {
  82118. this.data = new Array(10);
  82119. for (var i = 0; i < 10; ++i) {
  82120. if (data && data[i]) {
  82121. this.data[i] = data[i];
  82122. }
  82123. else {
  82124. this.data[i] = 0;
  82125. }
  82126. }
  82127. }
  82128. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  82129. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  82130. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  82131. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  82132. return det;
  82133. };
  82134. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  82135. for (var i = 0; i < 10; ++i) {
  82136. this.data[i] += matrix.data[i];
  82137. }
  82138. };
  82139. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  82140. for (var i = 0; i < 10; ++i) {
  82141. this.data[i] += data[i];
  82142. }
  82143. };
  82144. QuadraticMatrix.prototype.add = function (matrix) {
  82145. var m = new QuadraticMatrix();
  82146. for (var i = 0; i < 10; ++i) {
  82147. m.data[i] = this.data[i] + matrix.data[i];
  82148. }
  82149. return m;
  82150. };
  82151. QuadraticMatrix.FromData = function (a, b, c, d) {
  82152. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  82153. };
  82154. //returning an array to avoid garbage collection
  82155. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  82156. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  82157. };
  82158. return QuadraticMatrix;
  82159. }());
  82160. BABYLON.QuadraticMatrix = QuadraticMatrix;
  82161. var Reference = /** @class */ (function () {
  82162. function Reference(vertexId, triangleId) {
  82163. this.vertexId = vertexId;
  82164. this.triangleId = triangleId;
  82165. }
  82166. return Reference;
  82167. }());
  82168. BABYLON.Reference = Reference;
  82169. /**
  82170. * An implementation of the Quadratic Error simplification algorithm.
  82171. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  82172. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  82173. * @author RaananW
  82174. */
  82175. var QuadraticErrorSimplification = /** @class */ (function () {
  82176. function QuadraticErrorSimplification(_mesh) {
  82177. this._mesh = _mesh;
  82178. this.syncIterations = 5000;
  82179. this.aggressiveness = 7;
  82180. this.decimationIterations = 100;
  82181. this.boundingBoxEpsilon = BABYLON.Epsilon;
  82182. }
  82183. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  82184. var _this = this;
  82185. this.initDecimatedMesh();
  82186. //iterating through the submeshes array, one after the other.
  82187. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  82188. _this.initWithMesh(loop.index, function () {
  82189. _this.runDecimation(settings, loop.index, function () {
  82190. loop.executeNext();
  82191. });
  82192. }, settings.optimizeMesh);
  82193. }, function () {
  82194. setTimeout(function () {
  82195. successCallback(_this._reconstructedMesh);
  82196. }, 0);
  82197. });
  82198. };
  82199. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  82200. var _this = this;
  82201. var targetCount = ~~(this.triangles.length * settings.quality);
  82202. var deletedTriangles = 0;
  82203. var triangleCount = this.triangles.length;
  82204. var iterationFunction = function (iteration, callback) {
  82205. setTimeout(function () {
  82206. if (iteration % 5 === 0) {
  82207. _this.updateMesh(iteration === 0);
  82208. }
  82209. for (var i = 0; i < _this.triangles.length; ++i) {
  82210. _this.triangles[i].isDirty = false;
  82211. }
  82212. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  82213. var trianglesIterator = function (i) {
  82214. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  82215. var t = _this.triangles[tIdx];
  82216. if (!t)
  82217. return;
  82218. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  82219. return;
  82220. }
  82221. for (var j = 0; j < 3; ++j) {
  82222. if (t.error[j] < threshold) {
  82223. var deleted0 = [];
  82224. var deleted1 = [];
  82225. var v0 = t.vertices[j];
  82226. var v1 = t.vertices[(j + 1) % 3];
  82227. if (v0.isBorder || v1.isBorder)
  82228. continue;
  82229. var p = BABYLON.Vector3.Zero();
  82230. var n = BABYLON.Vector3.Zero();
  82231. var uv = BABYLON.Vector2.Zero();
  82232. var color = new BABYLON.Color4(0, 0, 0, 1);
  82233. _this.calculateError(v0, v1, p, n, uv, color);
  82234. var delTr = new Array();
  82235. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  82236. continue;
  82237. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  82238. continue;
  82239. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82240. continue;
  82241. var uniqueArray = new Array();
  82242. delTr.forEach(function (deletedT) {
  82243. if (uniqueArray.indexOf(deletedT) === -1) {
  82244. deletedT.deletePending = true;
  82245. uniqueArray.push(deletedT);
  82246. }
  82247. });
  82248. if (uniqueArray.length % 2 !== 0) {
  82249. continue;
  82250. }
  82251. v0.q = v1.q.add(v0.q);
  82252. v0.updatePosition(p);
  82253. var tStart = _this.references.length;
  82254. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82255. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82256. var tCount = _this.references.length - tStart;
  82257. if (tCount <= v0.triangleCount) {
  82258. if (tCount) {
  82259. for (var c = 0; c < tCount; c++) {
  82260. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82261. }
  82262. }
  82263. }
  82264. else {
  82265. v0.triangleStart = tStart;
  82266. }
  82267. v0.triangleCount = tCount;
  82268. break;
  82269. }
  82270. }
  82271. };
  82272. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82273. }, 0);
  82274. };
  82275. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82276. if (triangleCount - deletedTriangles <= targetCount)
  82277. loop.breakLoop();
  82278. else {
  82279. iterationFunction(loop.index, function () {
  82280. loop.executeNext();
  82281. });
  82282. }
  82283. }, function () {
  82284. setTimeout(function () {
  82285. //reconstruct this part of the mesh
  82286. _this.reconstructMesh(submeshIndex);
  82287. successCallback();
  82288. }, 0);
  82289. });
  82290. };
  82291. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82292. var _this = this;
  82293. this.vertices = [];
  82294. this.triangles = [];
  82295. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82296. var indices = this._mesh.getIndices();
  82297. var submesh = this._mesh.subMeshes[submeshIndex];
  82298. var findInVertices = function (positionToSearch) {
  82299. if (optimizeMesh) {
  82300. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82301. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82302. return _this.vertices[ii];
  82303. }
  82304. }
  82305. }
  82306. return null;
  82307. };
  82308. var vertexReferences = [];
  82309. var vertexInit = function (i) {
  82310. if (!positionData) {
  82311. return;
  82312. }
  82313. var offset = i + submesh.verticesStart;
  82314. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82315. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82316. vertex.originalOffsets.push(offset);
  82317. if (vertex.id === _this.vertices.length) {
  82318. _this.vertices.push(vertex);
  82319. }
  82320. vertexReferences.push(vertex.id);
  82321. };
  82322. //var totalVertices = mesh.getTotalVertices();
  82323. var totalVertices = submesh.verticesCount;
  82324. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82325. var indicesInit = function (i) {
  82326. if (!indices) {
  82327. return;
  82328. }
  82329. var offset = (submesh.indexStart / 3) + i;
  82330. var pos = (offset * 3);
  82331. var i0 = indices[pos + 0];
  82332. var i1 = indices[pos + 1];
  82333. var i2 = indices[pos + 2];
  82334. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82335. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82336. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82337. var triangle = new DecimationTriangle([v0, v1, v2]);
  82338. triangle.originalOffset = pos;
  82339. _this.triangles.push(triangle);
  82340. };
  82341. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82342. _this.init(callback);
  82343. });
  82344. });
  82345. };
  82346. QuadraticErrorSimplification.prototype.init = function (callback) {
  82347. var _this = this;
  82348. var triangleInit1 = function (i) {
  82349. var t = _this.triangles[i];
  82350. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82351. for (var j = 0; j < 3; j++) {
  82352. 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))));
  82353. }
  82354. };
  82355. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82356. var triangleInit2 = function (i) {
  82357. var t = _this.triangles[i];
  82358. for (var j = 0; j < 3; ++j) {
  82359. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82360. }
  82361. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82362. };
  82363. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82364. callback();
  82365. });
  82366. });
  82367. };
  82368. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82369. var newTriangles = [];
  82370. var i;
  82371. for (i = 0; i < this.vertices.length; ++i) {
  82372. this.vertices[i].triangleCount = 0;
  82373. }
  82374. var t;
  82375. var j;
  82376. for (i = 0; i < this.triangles.length; ++i) {
  82377. if (!this.triangles[i].deleted) {
  82378. t = this.triangles[i];
  82379. for (j = 0; j < 3; ++j) {
  82380. t.vertices[j].triangleCount = 1;
  82381. }
  82382. newTriangles.push(t);
  82383. }
  82384. }
  82385. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82386. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82387. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82388. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82389. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82390. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82391. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82392. var vertexCount = 0;
  82393. for (i = 0; i < this.vertices.length; ++i) {
  82394. var vertex = this.vertices[i];
  82395. vertex.id = vertexCount;
  82396. if (vertex.triangleCount) {
  82397. vertex.originalOffsets.forEach(function (originalOffset) {
  82398. if (!normalData) {
  82399. return;
  82400. }
  82401. newPositionData.push(vertex.position.x);
  82402. newPositionData.push(vertex.position.y);
  82403. newPositionData.push(vertex.position.z);
  82404. newNormalData.push(normalData[originalOffset * 3]);
  82405. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82406. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82407. if (uvs && uvs.length) {
  82408. newUVsData.push(uvs[(originalOffset * 2)]);
  82409. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82410. }
  82411. else if (colorsData && colorsData.length) {
  82412. newColorsData.push(colorsData[(originalOffset * 4)]);
  82413. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82414. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82415. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82416. }
  82417. ++vertexCount;
  82418. });
  82419. }
  82420. }
  82421. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82422. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82423. var submeshesArray = this._reconstructedMesh.subMeshes;
  82424. this._reconstructedMesh.subMeshes = [];
  82425. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82426. var originalIndices = this._mesh.getIndices();
  82427. for (i = 0; i < newTriangles.length; ++i) {
  82428. t = newTriangles[i]; //now get the new referencing point for each vertex
  82429. [0, 1, 2].forEach(function (idx) {
  82430. var id = originalIndices[t.originalOffset + idx];
  82431. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82432. if (offset < 0)
  82433. offset = 0;
  82434. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82435. });
  82436. }
  82437. //overwriting the old vertex buffers and indices.
  82438. this._reconstructedMesh.setIndices(newIndicesArray);
  82439. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82440. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82441. if (newUVsData.length > 0)
  82442. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82443. if (newColorsData.length > 0)
  82444. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82445. //create submesh
  82446. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82447. if (submeshIndex > 0) {
  82448. this._reconstructedMesh.subMeshes = [];
  82449. submeshesArray.forEach(function (submesh) {
  82450. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82451. });
  82452. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82453. }
  82454. };
  82455. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82456. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82457. this._reconstructedMesh.material = this._mesh.material;
  82458. this._reconstructedMesh.parent = this._mesh.parent;
  82459. this._reconstructedMesh.isVisible = false;
  82460. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82461. };
  82462. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82463. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82464. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82465. if (t.deleted)
  82466. continue;
  82467. var s = this.references[vertex1.triangleStart + i].vertexId;
  82468. var v1 = t.vertices[(s + 1) % 3];
  82469. var v2 = t.vertices[(s + 2) % 3];
  82470. if ((v1 === vertex2 || v2 === vertex2)) {
  82471. deletedArray[i] = true;
  82472. delTr.push(t);
  82473. continue;
  82474. }
  82475. var d1 = v1.position.subtract(point);
  82476. d1 = d1.normalize();
  82477. var d2 = v2.position.subtract(point);
  82478. d2 = d2.normalize();
  82479. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82480. return true;
  82481. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82482. deletedArray[i] = false;
  82483. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82484. return true;
  82485. }
  82486. return false;
  82487. };
  82488. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82489. var newDeleted = deletedTriangles;
  82490. for (var i = 0; i < vertex.triangleCount; ++i) {
  82491. var ref = this.references[vertex.triangleStart + i];
  82492. var t = this.triangles[ref.triangleId];
  82493. if (t.deleted)
  82494. continue;
  82495. if (deletedArray[i] && t.deletePending) {
  82496. t.deleted = true;
  82497. newDeleted++;
  82498. continue;
  82499. }
  82500. t.vertices[ref.vertexId] = origVertex;
  82501. t.isDirty = true;
  82502. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82503. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82504. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82505. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82506. this.references.push(ref);
  82507. }
  82508. return newDeleted;
  82509. };
  82510. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82511. for (var i = 0; i < this.vertices.length; ++i) {
  82512. var vCount = [];
  82513. var vId = [];
  82514. var v = this.vertices[i];
  82515. var j;
  82516. for (j = 0; j < v.triangleCount; ++j) {
  82517. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82518. for (var ii = 0; ii < 3; ii++) {
  82519. var ofs = 0;
  82520. var vv = triangle.vertices[ii];
  82521. while (ofs < vCount.length) {
  82522. if (vId[ofs] === vv.id)
  82523. break;
  82524. ++ofs;
  82525. }
  82526. if (ofs === vCount.length) {
  82527. vCount.push(1);
  82528. vId.push(vv.id);
  82529. }
  82530. else {
  82531. vCount[ofs]++;
  82532. }
  82533. }
  82534. }
  82535. for (j = 0; j < vCount.length; ++j) {
  82536. if (vCount[j] === 1) {
  82537. this.vertices[vId[j]].isBorder = true;
  82538. }
  82539. else {
  82540. this.vertices[vId[j]].isBorder = false;
  82541. }
  82542. }
  82543. }
  82544. };
  82545. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82546. if (identifyBorders === void 0) { identifyBorders = false; }
  82547. var i;
  82548. if (!identifyBorders) {
  82549. var newTrianglesVector = [];
  82550. for (i = 0; i < this.triangles.length; ++i) {
  82551. if (!this.triangles[i].deleted) {
  82552. newTrianglesVector.push(this.triangles[i]);
  82553. }
  82554. }
  82555. this.triangles = newTrianglesVector;
  82556. }
  82557. for (i = 0; i < this.vertices.length; ++i) {
  82558. this.vertices[i].triangleCount = 0;
  82559. this.vertices[i].triangleStart = 0;
  82560. }
  82561. var t;
  82562. var j;
  82563. var v;
  82564. for (i = 0; i < this.triangles.length; ++i) {
  82565. t = this.triangles[i];
  82566. for (j = 0; j < 3; ++j) {
  82567. v = t.vertices[j];
  82568. v.triangleCount++;
  82569. }
  82570. }
  82571. var tStart = 0;
  82572. for (i = 0; i < this.vertices.length; ++i) {
  82573. this.vertices[i].triangleStart = tStart;
  82574. tStart += this.vertices[i].triangleCount;
  82575. this.vertices[i].triangleCount = 0;
  82576. }
  82577. var newReferences = new Array(this.triangles.length * 3);
  82578. for (i = 0; i < this.triangles.length; ++i) {
  82579. t = this.triangles[i];
  82580. for (j = 0; j < 3; ++j) {
  82581. v = t.vertices[j];
  82582. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82583. v.triangleCount++;
  82584. }
  82585. }
  82586. this.references = newReferences;
  82587. if (identifyBorders) {
  82588. this.identifyBorder();
  82589. }
  82590. };
  82591. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82592. var x = point.x;
  82593. var y = point.y;
  82594. var z = point.z;
  82595. 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
  82596. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82597. };
  82598. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82599. var q = vertex1.q.add(vertex2.q);
  82600. var border = vertex1.isBorder && vertex2.isBorder;
  82601. var error = 0;
  82602. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82603. if (qDet !== 0 && !border) {
  82604. if (!pointResult) {
  82605. pointResult = BABYLON.Vector3.Zero();
  82606. }
  82607. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82608. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82609. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82610. error = this.vertexError(q, pointResult);
  82611. }
  82612. else {
  82613. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82614. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82615. var error1 = this.vertexError(q, vertex1.position);
  82616. var error2 = this.vertexError(q, vertex2.position);
  82617. var error3 = this.vertexError(q, p3);
  82618. error = Math.min(error1, error2, error3);
  82619. if (error === error1) {
  82620. if (pointResult) {
  82621. pointResult.copyFrom(vertex1.position);
  82622. }
  82623. }
  82624. else if (error === error2) {
  82625. if (pointResult) {
  82626. pointResult.copyFrom(vertex2.position);
  82627. }
  82628. }
  82629. else {
  82630. if (pointResult) {
  82631. pointResult.copyFrom(p3);
  82632. }
  82633. }
  82634. }
  82635. return error;
  82636. };
  82637. return QuadraticErrorSimplification;
  82638. }());
  82639. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82640. })(BABYLON || (BABYLON = {}));
  82641. //# sourceMappingURL=babylon.meshSimplification.js.map
  82642. var BABYLON;
  82643. (function (BABYLON) {
  82644. var MeshLODLevel = /** @class */ (function () {
  82645. function MeshLODLevel(distance, mesh) {
  82646. this.distance = distance;
  82647. this.mesh = mesh;
  82648. }
  82649. return MeshLODLevel;
  82650. }());
  82651. BABYLON.MeshLODLevel = MeshLODLevel;
  82652. })(BABYLON || (BABYLON = {}));
  82653. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82654. var BABYLON;
  82655. (function (BABYLON) {
  82656. /**
  82657. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82658. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82659. */
  82660. var SceneOptimization = /** @class */ (function () {
  82661. /**
  82662. * Creates the SceneOptimization object
  82663. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82664. * @param desc defines the description associated with the optimization
  82665. */
  82666. function SceneOptimization(
  82667. /**
  82668. * Defines the priority of this optimization (0 by default which means first in the list)
  82669. */
  82670. priority) {
  82671. if (priority === void 0) { priority = 0; }
  82672. this.priority = priority;
  82673. }
  82674. /**
  82675. * Gets a string describing the action executed by the current optimization
  82676. * @returns description string
  82677. */
  82678. SceneOptimization.prototype.getDescription = function () {
  82679. return "";
  82680. };
  82681. /**
  82682. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82683. * @param scene defines the current scene where to apply this optimization
  82684. * @param optimizer defines the current optimizer
  82685. * @returns true if everything that can be done was applied
  82686. */
  82687. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82688. return true;
  82689. };
  82690. ;
  82691. return SceneOptimization;
  82692. }());
  82693. BABYLON.SceneOptimization = SceneOptimization;
  82694. /**
  82695. * Defines an optimization used to reduce the size of render target textures
  82696. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82697. */
  82698. var TextureOptimization = /** @class */ (function (_super) {
  82699. __extends(TextureOptimization, _super);
  82700. /**
  82701. * Creates the TextureOptimization object
  82702. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82703. * @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
  82704. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82705. */
  82706. function TextureOptimization(
  82707. /**
  82708. * Defines the priority of this optimization (0 by default which means first in the list)
  82709. */
  82710. priority,
  82711. /**
  82712. * 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
  82713. */
  82714. maximumSize,
  82715. /**
  82716. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82717. */
  82718. step) {
  82719. if (priority === void 0) { priority = 0; }
  82720. if (maximumSize === void 0) { maximumSize = 1024; }
  82721. if (step === void 0) { step = 0.5; }
  82722. var _this = _super.call(this, priority) || this;
  82723. _this.priority = priority;
  82724. _this.maximumSize = maximumSize;
  82725. _this.step = step;
  82726. return _this;
  82727. }
  82728. /**
  82729. * Gets a string describing the action executed by the current optimization
  82730. * @returns description string
  82731. */
  82732. TextureOptimization.prototype.getDescription = function () {
  82733. return "Reducing render target texture size to " + this.maximumSize;
  82734. };
  82735. /**
  82736. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82737. * @param scene defines the current scene where to apply this optimization
  82738. * @param optimizer defines the current optimizer
  82739. * @returns true if everything that can be done was applied
  82740. */
  82741. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82742. var allDone = true;
  82743. for (var index = 0; index < scene.textures.length; index++) {
  82744. var texture = scene.textures[index];
  82745. if (!texture.canRescale || texture.getContext) {
  82746. continue;
  82747. }
  82748. var currentSize = texture.getSize();
  82749. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82750. if (maxDimension > this.maximumSize) {
  82751. texture.scale(this.step);
  82752. allDone = false;
  82753. }
  82754. }
  82755. return allDone;
  82756. };
  82757. return TextureOptimization;
  82758. }(SceneOptimization));
  82759. BABYLON.TextureOptimization = TextureOptimization;
  82760. /**
  82761. * Defines an optimization used to increase or decrease the rendering resolution
  82762. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82763. */
  82764. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82765. __extends(HardwareScalingOptimization, _super);
  82766. /**
  82767. * Creates the HardwareScalingOptimization object
  82768. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82769. * @param maximumScale defines the maximum scale to use (2 by default)
  82770. * @param step defines the step to use between two passes (0.5 by default)
  82771. */
  82772. function HardwareScalingOptimization(
  82773. /**
  82774. * Defines the priority of this optimization (0 by default which means first in the list)
  82775. */
  82776. priority,
  82777. /**
  82778. * Defines the maximum scale to use (2 by default)
  82779. */
  82780. maximumScale,
  82781. /**
  82782. * Defines the step to use between two passes (0.5 by default)
  82783. */
  82784. step) {
  82785. if (priority === void 0) { priority = 0; }
  82786. if (maximumScale === void 0) { maximumScale = 2; }
  82787. if (step === void 0) { step = 0.25; }
  82788. var _this = _super.call(this, priority) || this;
  82789. _this.priority = priority;
  82790. _this.maximumScale = maximumScale;
  82791. _this.step = step;
  82792. _this._currentScale = -1;
  82793. _this._directionOffset = 1;
  82794. return _this;
  82795. }
  82796. /**
  82797. * Gets a string describing the action executed by the current optimization
  82798. * @return description string
  82799. */
  82800. HardwareScalingOptimization.prototype.getDescription = function () {
  82801. return "Setting hardware scaling level to " + this._currentScale;
  82802. };
  82803. /**
  82804. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82805. * @param scene defines the current scene where to apply this optimization
  82806. * @param optimizer defines the current optimizer
  82807. * @returns true if everything that can be done was applied
  82808. */
  82809. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82810. if (this._currentScale === -1) {
  82811. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82812. if (this._currentScale > this.maximumScale) {
  82813. this._directionOffset = -1;
  82814. }
  82815. }
  82816. this._currentScale += this._directionOffset * this.step;
  82817. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82818. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82819. };
  82820. ;
  82821. return HardwareScalingOptimization;
  82822. }(SceneOptimization));
  82823. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82824. /**
  82825. * Defines an optimization used to remove shadows
  82826. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82827. */
  82828. var ShadowsOptimization = /** @class */ (function (_super) {
  82829. __extends(ShadowsOptimization, _super);
  82830. function ShadowsOptimization() {
  82831. return _super !== null && _super.apply(this, arguments) || this;
  82832. }
  82833. /**
  82834. * Gets a string describing the action executed by the current optimization
  82835. * @return description string
  82836. */
  82837. ShadowsOptimization.prototype.getDescription = function () {
  82838. return "Turning shadows on/off";
  82839. };
  82840. /**
  82841. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82842. * @param scene defines the current scene where to apply this optimization
  82843. * @param optimizer defines the current optimizer
  82844. * @returns true if everything that can be done was applied
  82845. */
  82846. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82847. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82848. return true;
  82849. };
  82850. ;
  82851. return ShadowsOptimization;
  82852. }(SceneOptimization));
  82853. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82854. /**
  82855. * Defines an optimization used to turn post-processes off
  82856. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82857. */
  82858. var PostProcessesOptimization = /** @class */ (function (_super) {
  82859. __extends(PostProcessesOptimization, _super);
  82860. function PostProcessesOptimization() {
  82861. return _super !== null && _super.apply(this, arguments) || this;
  82862. }
  82863. /**
  82864. * Gets a string describing the action executed by the current optimization
  82865. * @return description string
  82866. */
  82867. PostProcessesOptimization.prototype.getDescription = function () {
  82868. return "Turning post-processes on/off";
  82869. };
  82870. /**
  82871. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82872. * @param scene defines the current scene where to apply this optimization
  82873. * @param optimizer defines the current optimizer
  82874. * @returns true if everything that can be done was applied
  82875. */
  82876. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82877. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82878. return true;
  82879. };
  82880. ;
  82881. return PostProcessesOptimization;
  82882. }(SceneOptimization));
  82883. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82884. /**
  82885. * Defines an optimization used to turn lens flares off
  82886. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82887. */
  82888. var LensFlaresOptimization = /** @class */ (function (_super) {
  82889. __extends(LensFlaresOptimization, _super);
  82890. function LensFlaresOptimization() {
  82891. return _super !== null && _super.apply(this, arguments) || this;
  82892. }
  82893. /**
  82894. * Gets a string describing the action executed by the current optimization
  82895. * @return description string
  82896. */
  82897. LensFlaresOptimization.prototype.getDescription = function () {
  82898. return "Turning lens flares on/off";
  82899. };
  82900. /**
  82901. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82902. * @param scene defines the current scene where to apply this optimization
  82903. * @param optimizer defines the current optimizer
  82904. * @returns true if everything that can be done was applied
  82905. */
  82906. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82907. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82908. return true;
  82909. };
  82910. ;
  82911. return LensFlaresOptimization;
  82912. }(SceneOptimization));
  82913. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82914. /**
  82915. * Defines an optimization based on user defined callback.
  82916. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82917. */
  82918. var CustomOptimization = /** @class */ (function (_super) {
  82919. __extends(CustomOptimization, _super);
  82920. function CustomOptimization() {
  82921. return _super !== null && _super.apply(this, arguments) || this;
  82922. }
  82923. /**
  82924. * Gets a string describing the action executed by the current optimization
  82925. * @returns description string
  82926. */
  82927. CustomOptimization.prototype.getDescription = function () {
  82928. if (this.onGetDescription) {
  82929. return this.onGetDescription();
  82930. }
  82931. return "Running user defined callback";
  82932. };
  82933. /**
  82934. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82935. * @param scene defines the current scene where to apply this optimization
  82936. * @param optimizer defines the current optimizer
  82937. * @returns true if everything that can be done was applied
  82938. */
  82939. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82940. if (this.onApply) {
  82941. return this.onApply(scene, optimizer);
  82942. }
  82943. return true;
  82944. };
  82945. ;
  82946. return CustomOptimization;
  82947. }(SceneOptimization));
  82948. BABYLON.CustomOptimization = CustomOptimization;
  82949. /**
  82950. * Defines an optimization used to turn particles off
  82951. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82952. */
  82953. var ParticlesOptimization = /** @class */ (function (_super) {
  82954. __extends(ParticlesOptimization, _super);
  82955. function ParticlesOptimization() {
  82956. return _super !== null && _super.apply(this, arguments) || this;
  82957. }
  82958. /**
  82959. * Gets a string describing the action executed by the current optimization
  82960. * @return description string
  82961. */
  82962. ParticlesOptimization.prototype.getDescription = function () {
  82963. return "Turning particles on/off";
  82964. };
  82965. /**
  82966. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82967. * @param scene defines the current scene where to apply this optimization
  82968. * @param optimizer defines the current optimizer
  82969. * @returns true if everything that can be done was applied
  82970. */
  82971. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82972. scene.particlesEnabled = optimizer.isInImprovementMode;
  82973. return true;
  82974. };
  82975. ;
  82976. return ParticlesOptimization;
  82977. }(SceneOptimization));
  82978. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82979. /**
  82980. * Defines an optimization used to turn render targets off
  82981. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82982. */
  82983. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82984. __extends(RenderTargetsOptimization, _super);
  82985. function RenderTargetsOptimization() {
  82986. return _super !== null && _super.apply(this, arguments) || this;
  82987. }
  82988. /**
  82989. * Gets a string describing the action executed by the current optimization
  82990. * @return description string
  82991. */
  82992. RenderTargetsOptimization.prototype.getDescription = function () {
  82993. return "Turning render targets off";
  82994. };
  82995. /**
  82996. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82997. * @param scene defines the current scene where to apply this optimization
  82998. * @param optimizer defines the current optimizer
  82999. * @returns true if everything that can be done was applied
  83000. */
  83001. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  83002. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  83003. return true;
  83004. };
  83005. ;
  83006. return RenderTargetsOptimization;
  83007. }(SceneOptimization));
  83008. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  83009. /**
  83010. * Defines an optimization used to merge meshes with compatible materials
  83011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83012. */
  83013. var MergeMeshesOptimization = /** @class */ (function (_super) {
  83014. __extends(MergeMeshesOptimization, _super);
  83015. function MergeMeshesOptimization() {
  83016. var _this = _super !== null && _super.apply(this, arguments) || this;
  83017. _this._canBeMerged = function (abstractMesh) {
  83018. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  83019. return false;
  83020. }
  83021. var mesh = abstractMesh;
  83022. if (!mesh.isVisible || !mesh.isEnabled()) {
  83023. return false;
  83024. }
  83025. if (mesh.instances.length > 0) {
  83026. return false;
  83027. }
  83028. if (mesh.skeleton || mesh.hasLODLevels) {
  83029. return false;
  83030. }
  83031. if (mesh.parent) {
  83032. return false;
  83033. }
  83034. return true;
  83035. };
  83036. return _this;
  83037. }
  83038. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  83039. /**
  83040. * Gets or sets a boolean which defines if optimization octree has to be updated
  83041. */
  83042. get: function () {
  83043. return MergeMeshesOptimization._UpdateSelectionTree;
  83044. },
  83045. /**
  83046. * Gets or sets a boolean which defines if optimization octree has to be updated
  83047. */
  83048. set: function (value) {
  83049. MergeMeshesOptimization._UpdateSelectionTree = value;
  83050. },
  83051. enumerable: true,
  83052. configurable: true
  83053. });
  83054. /**
  83055. * Gets a string describing the action executed by the current optimization
  83056. * @return description string
  83057. */
  83058. MergeMeshesOptimization.prototype.getDescription = function () {
  83059. return "Merging similar meshes together";
  83060. };
  83061. /**
  83062. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  83063. * @param scene defines the current scene where to apply this optimization
  83064. * @param optimizer defines the current optimizer
  83065. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  83066. * @returns true if everything that can be done was applied
  83067. */
  83068. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  83069. var globalPool = scene.meshes.slice(0);
  83070. var globalLength = globalPool.length;
  83071. for (var index = 0; index < globalLength; index++) {
  83072. var currentPool = new Array();
  83073. var current = globalPool[index];
  83074. // Checks
  83075. if (!this._canBeMerged(current)) {
  83076. continue;
  83077. }
  83078. currentPool.push(current);
  83079. // Find compatible meshes
  83080. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  83081. var otherMesh = globalPool[subIndex];
  83082. if (!this._canBeMerged(otherMesh)) {
  83083. continue;
  83084. }
  83085. if (otherMesh.material !== current.material) {
  83086. continue;
  83087. }
  83088. if (otherMesh.checkCollisions !== current.checkCollisions) {
  83089. continue;
  83090. }
  83091. currentPool.push(otherMesh);
  83092. globalLength--;
  83093. globalPool.splice(subIndex, 1);
  83094. subIndex--;
  83095. }
  83096. if (currentPool.length < 2) {
  83097. continue;
  83098. }
  83099. // Merge meshes
  83100. BABYLON.Mesh.MergeMeshes(currentPool);
  83101. }
  83102. if (updateSelectionTree != undefined) {
  83103. if (updateSelectionTree) {
  83104. scene.createOrUpdateSelectionOctree();
  83105. }
  83106. }
  83107. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  83108. scene.createOrUpdateSelectionOctree();
  83109. }
  83110. return true;
  83111. };
  83112. ;
  83113. MergeMeshesOptimization._UpdateSelectionTree = false;
  83114. return MergeMeshesOptimization;
  83115. }(SceneOptimization));
  83116. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  83117. /**
  83118. * Defines a list of options used by SceneOptimizer
  83119. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83120. */
  83121. var SceneOptimizerOptions = /** @class */ (function () {
  83122. /**
  83123. * Creates a new list of options used by SceneOptimizer
  83124. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  83125. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  83126. */
  83127. function SceneOptimizerOptions(
  83128. /**
  83129. * Defines the target frame rate to reach (60 by default)
  83130. */
  83131. targetFrameRate,
  83132. /**
  83133. * Defines the interval between two checkes (2000ms by default)
  83134. */
  83135. trackerDuration) {
  83136. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  83137. if (trackerDuration === void 0) { trackerDuration = 2000; }
  83138. this.targetFrameRate = targetFrameRate;
  83139. this.trackerDuration = trackerDuration;
  83140. /**
  83141. * Gets the list of optimizations to apply
  83142. */
  83143. this.optimizations = new Array();
  83144. }
  83145. /**
  83146. * Add a new optimization
  83147. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  83148. * @returns the current SceneOptimizerOptions
  83149. */
  83150. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  83151. this.optimizations.push(optimization);
  83152. return this;
  83153. };
  83154. /**
  83155. * Add a new custom optimization
  83156. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  83157. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  83158. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  83159. * @returns the current SceneOptimizerOptions
  83160. */
  83161. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  83162. if (priority === void 0) { priority = 0; }
  83163. var optimization = new CustomOptimization(priority);
  83164. optimization.onApply = onApply;
  83165. optimization.onGetDescription = onGetDescription;
  83166. this.optimizations.push(optimization);
  83167. return this;
  83168. };
  83169. /**
  83170. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  83171. * @param targetFrameRate defines the target frame rate (60 by default)
  83172. * @returns a SceneOptimizerOptions object
  83173. */
  83174. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  83175. var result = new SceneOptimizerOptions(targetFrameRate);
  83176. var priority = 0;
  83177. result.addOptimization(new MergeMeshesOptimization(priority));
  83178. result.addOptimization(new ShadowsOptimization(priority));
  83179. result.addOptimization(new LensFlaresOptimization(priority));
  83180. // Next priority
  83181. priority++;
  83182. result.addOptimization(new PostProcessesOptimization(priority));
  83183. result.addOptimization(new ParticlesOptimization(priority));
  83184. // Next priority
  83185. priority++;
  83186. result.addOptimization(new TextureOptimization(priority, 1024));
  83187. return result;
  83188. };
  83189. /**
  83190. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  83191. * @param targetFrameRate defines the target frame rate (60 by default)
  83192. * @returns a SceneOptimizerOptions object
  83193. */
  83194. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  83195. var result = new SceneOptimizerOptions(targetFrameRate);
  83196. var priority = 0;
  83197. result.addOptimization(new MergeMeshesOptimization(priority));
  83198. result.addOptimization(new ShadowsOptimization(priority));
  83199. result.addOptimization(new LensFlaresOptimization(priority));
  83200. // Next priority
  83201. priority++;
  83202. result.addOptimization(new PostProcessesOptimization(priority));
  83203. result.addOptimization(new ParticlesOptimization(priority));
  83204. // Next priority
  83205. priority++;
  83206. result.addOptimization(new TextureOptimization(priority, 512));
  83207. // Next priority
  83208. priority++;
  83209. result.addOptimization(new RenderTargetsOptimization(priority));
  83210. // Next priority
  83211. priority++;
  83212. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  83213. return result;
  83214. };
  83215. /**
  83216. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  83217. * @param targetFrameRate defines the target frame rate (60 by default)
  83218. * @returns a SceneOptimizerOptions object
  83219. */
  83220. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  83221. var result = new SceneOptimizerOptions(targetFrameRate);
  83222. var priority = 0;
  83223. result.addOptimization(new MergeMeshesOptimization(priority));
  83224. result.addOptimization(new ShadowsOptimization(priority));
  83225. result.addOptimization(new LensFlaresOptimization(priority));
  83226. // Next priority
  83227. priority++;
  83228. result.addOptimization(new PostProcessesOptimization(priority));
  83229. result.addOptimization(new ParticlesOptimization(priority));
  83230. // Next priority
  83231. priority++;
  83232. result.addOptimization(new TextureOptimization(priority, 256));
  83233. // Next priority
  83234. priority++;
  83235. result.addOptimization(new RenderTargetsOptimization(priority));
  83236. // Next priority
  83237. priority++;
  83238. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  83239. return result;
  83240. };
  83241. return SceneOptimizerOptions;
  83242. }());
  83243. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83244. /**
  83245. * Class used to run optimizations in order to reach a target frame rate
  83246. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83247. */
  83248. var SceneOptimizer = /** @class */ (function () {
  83249. /**
  83250. * Creates a new SceneOptimizer
  83251. * @param scene defines the scene to work on
  83252. * @param options defines the options to use with the SceneOptimizer
  83253. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83254. * @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)
  83255. */
  83256. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83257. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83258. if (improvementMode === void 0) { improvementMode = false; }
  83259. var _this = this;
  83260. this._isRunning = false;
  83261. this._currentPriorityLevel = 0;
  83262. this._targetFrameRate = 60;
  83263. this._trackerDuration = 2000;
  83264. this._currentFrameRate = 0;
  83265. this._improvementMode = false;
  83266. /**
  83267. * Defines an observable called when the optimizer reaches the target frame rate
  83268. */
  83269. this.onSuccessObservable = new BABYLON.Observable();
  83270. /**
  83271. * Defines an observable called when the optimizer enables an optimization
  83272. */
  83273. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83274. /**
  83275. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83276. */
  83277. this.onFailureObservable = new BABYLON.Observable();
  83278. if (!options) {
  83279. this._options = new SceneOptimizerOptions();
  83280. }
  83281. else {
  83282. this._options = options;
  83283. }
  83284. if (this._options.targetFrameRate) {
  83285. this._targetFrameRate = this._options.targetFrameRate;
  83286. }
  83287. if (this._options.trackerDuration) {
  83288. this._trackerDuration = this._options.trackerDuration;
  83289. }
  83290. if (autoGeneratePriorities) {
  83291. var priority = 0;
  83292. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83293. var optim = _a[_i];
  83294. optim.priority = priority++;
  83295. }
  83296. }
  83297. this._improvementMode = improvementMode;
  83298. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83299. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83300. _this._sceneDisposeObserver = null;
  83301. _this.dispose();
  83302. });
  83303. }
  83304. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83305. /**
  83306. * Gets a boolean indicating if the optimizer is in improvement mode
  83307. */
  83308. get: function () {
  83309. return this._improvementMode;
  83310. },
  83311. enumerable: true,
  83312. configurable: true
  83313. });
  83314. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83315. /**
  83316. * Gets the current priority level (0 at start)
  83317. */
  83318. get: function () {
  83319. return this._currentPriorityLevel;
  83320. },
  83321. enumerable: true,
  83322. configurable: true
  83323. });
  83324. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83325. /**
  83326. * Gets the current frame rate checked by the SceneOptimizer
  83327. */
  83328. get: function () {
  83329. return this._currentFrameRate;
  83330. },
  83331. enumerable: true,
  83332. configurable: true
  83333. });
  83334. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83335. /**
  83336. * Gets or sets the current target frame rate (60 by default)
  83337. */
  83338. get: function () {
  83339. return this._targetFrameRate;
  83340. },
  83341. /**
  83342. * Gets or sets the current target frame rate (60 by default)
  83343. */
  83344. set: function (value) {
  83345. this._targetFrameRate = value;
  83346. },
  83347. enumerable: true,
  83348. configurable: true
  83349. });
  83350. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83351. /**
  83352. * Gets or sets the current interval between two checks (every 2000ms by default)
  83353. */
  83354. get: function () {
  83355. return this._trackerDuration;
  83356. },
  83357. /**
  83358. * Gets or sets the current interval between two checks (every 2000ms by default)
  83359. */
  83360. set: function (value) {
  83361. this._trackerDuration = value;
  83362. },
  83363. enumerable: true,
  83364. configurable: true
  83365. });
  83366. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83367. /**
  83368. * Gets the list of active optimizations
  83369. */
  83370. get: function () {
  83371. return this._options.optimizations;
  83372. },
  83373. enumerable: true,
  83374. configurable: true
  83375. });
  83376. /**
  83377. * Stops the current optimizer
  83378. */
  83379. SceneOptimizer.prototype.stop = function () {
  83380. this._isRunning = false;
  83381. };
  83382. /**
  83383. * Reset the optimizer to initial step (current priority level = 0)
  83384. */
  83385. SceneOptimizer.prototype.reset = function () {
  83386. this._currentPriorityLevel = 0;
  83387. };
  83388. /**
  83389. * Start the optimizer. By default it will try to reach a specific framerate
  83390. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83391. */
  83392. SceneOptimizer.prototype.start = function () {
  83393. var _this = this;
  83394. if (this._isRunning) {
  83395. return;
  83396. }
  83397. this._isRunning = true;
  83398. // Let's wait for the scene to be ready before running our check
  83399. this._scene.executeWhenReady(function () {
  83400. setTimeout(function () {
  83401. _this._checkCurrentState();
  83402. }, _this._trackerDuration);
  83403. });
  83404. };
  83405. SceneOptimizer.prototype._checkCurrentState = function () {
  83406. var _this = this;
  83407. if (!this._isRunning) {
  83408. return;
  83409. }
  83410. var scene = this._scene;
  83411. var options = this._options;
  83412. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83413. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83414. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83415. this._isRunning = false;
  83416. this.onSuccessObservable.notifyObservers(this);
  83417. return;
  83418. }
  83419. // Apply current level of optimizations
  83420. var allDone = true;
  83421. var noOptimizationApplied = true;
  83422. for (var index = 0; index < options.optimizations.length; index++) {
  83423. var optimization = options.optimizations[index];
  83424. if (optimization.priority === this._currentPriorityLevel) {
  83425. noOptimizationApplied = false;
  83426. allDone = allDone && optimization.apply(scene, this);
  83427. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83428. }
  83429. }
  83430. // If no optimization was applied, this is a failure :(
  83431. if (noOptimizationApplied) {
  83432. this._isRunning = false;
  83433. this.onFailureObservable.notifyObservers(this);
  83434. return;
  83435. }
  83436. // If all optimizations were done, move to next level
  83437. if (allDone) {
  83438. this._currentPriorityLevel++;
  83439. }
  83440. // Let's the system running for a specific amount of time before checking FPS
  83441. scene.executeWhenReady(function () {
  83442. setTimeout(function () {
  83443. _this._checkCurrentState();
  83444. }, _this._trackerDuration);
  83445. });
  83446. };
  83447. /**
  83448. * Release all resources
  83449. */
  83450. SceneOptimizer.prototype.dispose = function () {
  83451. this.stop();
  83452. this.onSuccessObservable.clear();
  83453. this.onFailureObservable.clear();
  83454. this.onNewOptimizationAppliedObservable.clear();
  83455. if (this._sceneDisposeObserver) {
  83456. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83457. }
  83458. };
  83459. /**
  83460. * Helper function to create a SceneOptimizer with one single line of code
  83461. * @param scene defines the scene to work on
  83462. * @param options defines the options to use with the SceneOptimizer
  83463. * @param onSuccess defines a callback to call on success
  83464. * @param onFailure defines a callback to call on failure
  83465. * @returns the new SceneOptimizer object
  83466. */
  83467. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83468. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83469. if (onSuccess) {
  83470. optimizer.onSuccessObservable.add(function () {
  83471. onSuccess();
  83472. });
  83473. }
  83474. if (onFailure) {
  83475. optimizer.onFailureObservable.add(function () {
  83476. onFailure();
  83477. });
  83478. }
  83479. optimizer.start();
  83480. return optimizer;
  83481. };
  83482. return SceneOptimizer;
  83483. }());
  83484. BABYLON.SceneOptimizer = SceneOptimizer;
  83485. })(BABYLON || (BABYLON = {}));
  83486. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83487. var BABYLON;
  83488. (function (BABYLON) {
  83489. var OutlineRenderer = /** @class */ (function () {
  83490. function OutlineRenderer(scene) {
  83491. this.zOffset = 1;
  83492. this._scene = scene;
  83493. }
  83494. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83495. var _this = this;
  83496. if (useOverlay === void 0) { useOverlay = false; }
  83497. var scene = this._scene;
  83498. var engine = this._scene.getEngine();
  83499. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83500. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83501. return;
  83502. }
  83503. var mesh = subMesh.getRenderingMesh();
  83504. var material = subMesh.getMaterial();
  83505. if (!material || !scene.activeCamera) {
  83506. return;
  83507. }
  83508. engine.enableEffect(this._effect);
  83509. // Logarithmic depth
  83510. if (material.useLogarithmicDepth) {
  83511. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83512. }
  83513. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83514. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83515. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83516. // Bones
  83517. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83518. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83519. }
  83520. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83521. // Alpha test
  83522. if (material && material.needAlphaTesting()) {
  83523. var alphaTexture = material.getAlphaTestTexture();
  83524. if (alphaTexture) {
  83525. this._effect.setTexture("diffuseSampler", alphaTexture);
  83526. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83527. }
  83528. }
  83529. engine.setZOffset(-this.zOffset);
  83530. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83531. engine.setZOffset(0);
  83532. };
  83533. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83534. var defines = [];
  83535. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83536. var mesh = subMesh.getMesh();
  83537. var material = subMesh.getMaterial();
  83538. if (material) {
  83539. // Alpha test
  83540. if (material.needAlphaTesting()) {
  83541. defines.push("#define ALPHATEST");
  83542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83543. attribs.push(BABYLON.VertexBuffer.UVKind);
  83544. defines.push("#define UV1");
  83545. }
  83546. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83547. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83548. defines.push("#define UV2");
  83549. }
  83550. }
  83551. //Logarithmic depth
  83552. if (material.useLogarithmicDepth) {
  83553. defines.push("#define LOGARITHMICDEPTH");
  83554. }
  83555. }
  83556. // Bones
  83557. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83558. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83559. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83560. if (mesh.numBoneInfluencers > 4) {
  83561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83563. }
  83564. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83565. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83566. }
  83567. else {
  83568. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83569. }
  83570. // Instances
  83571. if (useInstances) {
  83572. defines.push("#define INSTANCES");
  83573. attribs.push("world0");
  83574. attribs.push("world1");
  83575. attribs.push("world2");
  83576. attribs.push("world3");
  83577. }
  83578. // Get correct effect
  83579. var join = defines.join("\n");
  83580. if (this._cachedDefines !== join) {
  83581. this._cachedDefines = join;
  83582. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83583. }
  83584. return this._effect.isReady();
  83585. };
  83586. return OutlineRenderer;
  83587. }());
  83588. BABYLON.OutlineRenderer = OutlineRenderer;
  83589. })(BABYLON || (BABYLON = {}));
  83590. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83591. var BABYLON;
  83592. (function (BABYLON) {
  83593. var FaceAdjacencies = /** @class */ (function () {
  83594. function FaceAdjacencies() {
  83595. this.edges = new Array();
  83596. this.edgesConnectedCount = 0;
  83597. }
  83598. return FaceAdjacencies;
  83599. }());
  83600. var EdgesRenderer = /** @class */ (function () {
  83601. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83602. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83603. if (epsilon === void 0) { epsilon = 0.95; }
  83604. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83605. this.edgesWidthScalerForOrthographic = 1000.0;
  83606. this.edgesWidthScalerForPerspective = 50.0;
  83607. this._linesPositions = new Array();
  83608. this._linesNormals = new Array();
  83609. this._linesIndices = new Array();
  83610. this._buffers = {};
  83611. this._checkVerticesInsteadOfIndices = false;
  83612. this._source = source;
  83613. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83614. this._epsilon = epsilon;
  83615. this._prepareRessources();
  83616. this._generateEdgesLines();
  83617. }
  83618. EdgesRenderer.prototype._prepareRessources = function () {
  83619. if (this._lineShader) {
  83620. return;
  83621. }
  83622. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83623. attributes: ["position", "normal"],
  83624. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83625. });
  83626. this._lineShader.disableDepthWrite = true;
  83627. this._lineShader.backFaceCulling = false;
  83628. };
  83629. EdgesRenderer.prototype._rebuild = function () {
  83630. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83631. if (buffer) {
  83632. buffer._rebuild();
  83633. }
  83634. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83635. if (buffer) {
  83636. buffer._rebuild();
  83637. }
  83638. var scene = this._source.getScene();
  83639. var engine = scene.getEngine();
  83640. this._ib = engine.createIndexBuffer(this._linesIndices);
  83641. };
  83642. EdgesRenderer.prototype.dispose = function () {
  83643. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83644. if (buffer) {
  83645. buffer.dispose();
  83646. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83647. }
  83648. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83649. if (buffer) {
  83650. buffer.dispose();
  83651. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83652. }
  83653. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83654. this._lineShader.dispose();
  83655. };
  83656. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83657. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83658. return 0;
  83659. }
  83660. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83661. return 1;
  83662. }
  83663. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83664. return 2;
  83665. }
  83666. return -1;
  83667. };
  83668. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83669. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83670. return 0;
  83671. }
  83672. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83673. return 1;
  83674. }
  83675. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83676. return 2;
  83677. }
  83678. return -1;
  83679. };
  83680. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83681. var needToCreateLine;
  83682. if (edge === undefined) {
  83683. needToCreateLine = true;
  83684. }
  83685. else {
  83686. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83687. needToCreateLine = dotProduct < this._epsilon;
  83688. }
  83689. if (needToCreateLine) {
  83690. var offset = this._linesPositions.length / 3;
  83691. var normal = p0.subtract(p1);
  83692. normal.normalize();
  83693. // Positions
  83694. this._linesPositions.push(p0.x);
  83695. this._linesPositions.push(p0.y);
  83696. this._linesPositions.push(p0.z);
  83697. this._linesPositions.push(p0.x);
  83698. this._linesPositions.push(p0.y);
  83699. this._linesPositions.push(p0.z);
  83700. this._linesPositions.push(p1.x);
  83701. this._linesPositions.push(p1.y);
  83702. this._linesPositions.push(p1.z);
  83703. this._linesPositions.push(p1.x);
  83704. this._linesPositions.push(p1.y);
  83705. this._linesPositions.push(p1.z);
  83706. // Normals
  83707. this._linesNormals.push(p1.x);
  83708. this._linesNormals.push(p1.y);
  83709. this._linesNormals.push(p1.z);
  83710. this._linesNormals.push(-1);
  83711. this._linesNormals.push(p1.x);
  83712. this._linesNormals.push(p1.y);
  83713. this._linesNormals.push(p1.z);
  83714. this._linesNormals.push(1);
  83715. this._linesNormals.push(p0.x);
  83716. this._linesNormals.push(p0.y);
  83717. this._linesNormals.push(p0.z);
  83718. this._linesNormals.push(-1);
  83719. this._linesNormals.push(p0.x);
  83720. this._linesNormals.push(p0.y);
  83721. this._linesNormals.push(p0.z);
  83722. this._linesNormals.push(1);
  83723. // Indices
  83724. this._linesIndices.push(offset);
  83725. this._linesIndices.push(offset + 1);
  83726. this._linesIndices.push(offset + 2);
  83727. this._linesIndices.push(offset);
  83728. this._linesIndices.push(offset + 2);
  83729. this._linesIndices.push(offset + 3);
  83730. }
  83731. };
  83732. EdgesRenderer.prototype._generateEdgesLines = function () {
  83733. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83734. var indices = this._source.getIndices();
  83735. if (!indices || !positions) {
  83736. return;
  83737. }
  83738. // First let's find adjacencies
  83739. var adjacencies = new Array();
  83740. var faceNormals = new Array();
  83741. var index;
  83742. var faceAdjacencies;
  83743. // Prepare faces
  83744. for (index = 0; index < indices.length; index += 3) {
  83745. faceAdjacencies = new FaceAdjacencies();
  83746. var p0Index = indices[index];
  83747. var p1Index = indices[index + 1];
  83748. var p2Index = indices[index + 2];
  83749. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83750. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83751. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83752. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83753. faceNormal.normalize();
  83754. faceNormals.push(faceNormal);
  83755. adjacencies.push(faceAdjacencies);
  83756. }
  83757. // Scan
  83758. for (index = 0; index < adjacencies.length; index++) {
  83759. faceAdjacencies = adjacencies[index];
  83760. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83761. var otherFaceAdjacencies = adjacencies[otherIndex];
  83762. if (faceAdjacencies.edgesConnectedCount === 3) {
  83763. break;
  83764. }
  83765. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83766. continue;
  83767. }
  83768. var otherP0 = indices[otherIndex * 3];
  83769. var otherP1 = indices[otherIndex * 3 + 1];
  83770. var otherP2 = indices[otherIndex * 3 + 2];
  83771. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83772. var otherEdgeIndex = 0;
  83773. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83774. continue;
  83775. }
  83776. switch (edgeIndex) {
  83777. case 0:
  83778. if (this._checkVerticesInsteadOfIndices) {
  83779. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83780. }
  83781. else {
  83782. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83783. }
  83784. break;
  83785. case 1:
  83786. if (this._checkVerticesInsteadOfIndices) {
  83787. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83788. }
  83789. else {
  83790. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83791. }
  83792. break;
  83793. case 2:
  83794. if (this._checkVerticesInsteadOfIndices) {
  83795. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83796. }
  83797. else {
  83798. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83799. }
  83800. break;
  83801. }
  83802. if (otherEdgeIndex === -1) {
  83803. continue;
  83804. }
  83805. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83806. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83807. faceAdjacencies.edgesConnectedCount++;
  83808. otherFaceAdjacencies.edgesConnectedCount++;
  83809. if (faceAdjacencies.edgesConnectedCount === 3) {
  83810. break;
  83811. }
  83812. }
  83813. }
  83814. }
  83815. // Create lines
  83816. for (index = 0; index < adjacencies.length; index++) {
  83817. // 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
  83818. var current = adjacencies[index];
  83819. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83820. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83821. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83822. }
  83823. // Merge into a single mesh
  83824. var engine = this._source.getScene().getEngine();
  83825. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83826. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83827. this._ib = engine.createIndexBuffer(this._linesIndices);
  83828. this._indicesCount = this._linesIndices.length;
  83829. };
  83830. EdgesRenderer.prototype.render = function () {
  83831. var scene = this._source.getScene();
  83832. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83833. return;
  83834. }
  83835. var engine = scene.getEngine();
  83836. this._lineShader._preBind();
  83837. // VBOs
  83838. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83839. scene.resetCachedMaterial();
  83840. this._lineShader.setColor4("color", this._source.edgesColor);
  83841. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83842. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83843. }
  83844. else {
  83845. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83846. }
  83847. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83848. this._lineShader.bind(this._source.getWorldMatrix());
  83849. // Draw order
  83850. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83851. this._lineShader.unbind();
  83852. engine.setDepthWrite(true);
  83853. };
  83854. return EdgesRenderer;
  83855. }());
  83856. BABYLON.EdgesRenderer = EdgesRenderer;
  83857. })(BABYLON || (BABYLON = {}));
  83858. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83859. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83860. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83861. s = arguments[i];
  83862. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83863. t[p] = s[p];
  83864. }
  83865. return t;
  83866. };
  83867. var BABYLON;
  83868. (function (BABYLON) {
  83869. /**
  83870. * The effect layer Helps adding post process effect blended with the main pass.
  83871. *
  83872. * This can be for instance use to generate glow or higlight effects on the scene.
  83873. *
  83874. * The effect layer class can not be used directly and is intented to inherited from to be
  83875. * customized per effects.
  83876. */
  83877. var EffectLayer = /** @class */ (function () {
  83878. /**
  83879. * Instantiates a new effect Layer and references it in the scene.
  83880. * @param name The name of the layer
  83881. * @param scene The scene to use the layer in
  83882. */
  83883. function EffectLayer(
  83884. /** The Friendly of the effect in the scene */
  83885. name, scene) {
  83886. this.name = name;
  83887. this._vertexBuffers = {};
  83888. this._maxSize = 0;
  83889. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83890. this._shouldRender = true;
  83891. this._postProcesses = [];
  83892. this._textures = [];
  83893. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83894. /**
  83895. * The clear color of the texture used to generate the glow map.
  83896. */
  83897. this.neutralColor = new BABYLON.Color4();
  83898. /**
  83899. * Specifies wether the highlight layer is enabled or not.
  83900. */
  83901. this.isEnabled = true;
  83902. /**
  83903. * An event triggered when the effect layer has been disposed.
  83904. */
  83905. this.onDisposeObservable = new BABYLON.Observable();
  83906. /**
  83907. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83908. */
  83909. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83910. /**
  83911. * An event triggered when the generated texture is being merged in the scene.
  83912. */
  83913. this.onBeforeComposeObservable = new BABYLON.Observable();
  83914. /**
  83915. * An event triggered when the generated texture has been merged in the scene.
  83916. */
  83917. this.onAfterComposeObservable = new BABYLON.Observable();
  83918. /**
  83919. * An event triggered when the efffect layer changes its size.
  83920. */
  83921. this.onSizeChangedObservable = new BABYLON.Observable();
  83922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83923. this._engine = scene.getEngine();
  83924. this._maxSize = this._engine.getCaps().maxTextureSize;
  83925. this._scene.effectLayers.push(this);
  83926. // Generate Buffers
  83927. this._generateIndexBuffer();
  83928. this._genrateVertexBuffer();
  83929. }
  83930. Object.defineProperty(EffectLayer.prototype, "camera", {
  83931. /**
  83932. * Gets the camera attached to the layer.
  83933. */
  83934. get: function () {
  83935. return this._effectLayerOptions.camera;
  83936. },
  83937. enumerable: true,
  83938. configurable: true
  83939. });
  83940. /**
  83941. * Initializes the effect layer with the required options.
  83942. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83943. */
  83944. EffectLayer.prototype._init = function (options) {
  83945. // Adapt options
  83946. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83947. this._setMainTextureSize();
  83948. this._createMainTexture();
  83949. this._createTextureAndPostProcesses();
  83950. this._mergeEffect = this._createMergeEffect();
  83951. };
  83952. /**
  83953. * Generates the index buffer of the full screen quad blending to the main canvas.
  83954. */
  83955. EffectLayer.prototype._generateIndexBuffer = function () {
  83956. // Indices
  83957. var indices = [];
  83958. indices.push(0);
  83959. indices.push(1);
  83960. indices.push(2);
  83961. indices.push(0);
  83962. indices.push(2);
  83963. indices.push(3);
  83964. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83965. };
  83966. /**
  83967. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83968. */
  83969. EffectLayer.prototype._genrateVertexBuffer = function () {
  83970. // VBO
  83971. var vertices = [];
  83972. vertices.push(1, 1);
  83973. vertices.push(-1, 1);
  83974. vertices.push(-1, -1);
  83975. vertices.push(1, -1);
  83976. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83977. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83978. };
  83979. /**
  83980. * Sets the main texture desired size which is the closest power of two
  83981. * of the engine canvas size.
  83982. */
  83983. EffectLayer.prototype._setMainTextureSize = function () {
  83984. if (this._effectLayerOptions.mainTextureFixedSize) {
  83985. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83986. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83987. }
  83988. else {
  83989. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83990. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83991. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83992. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83993. }
  83994. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83995. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83996. };
  83997. /**
  83998. * Creates the main texture for the effect layer.
  83999. */
  84000. EffectLayer.prototype._createMainTexture = function () {
  84001. var _this = this;
  84002. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  84003. width: this._mainTextureDesiredSize.width,
  84004. height: this._mainTextureDesiredSize.height
  84005. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84006. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  84007. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84008. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84009. this._mainTexture.anisotropicFilteringLevel = 1;
  84010. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84011. this._mainTexture.renderParticles = false;
  84012. this._mainTexture.renderList = null;
  84013. this._mainTexture.ignoreCameraViewport = true;
  84014. // Custom render function
  84015. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  84016. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  84017. var index;
  84018. var engine = _this._scene.getEngine();
  84019. if (depthOnlySubMeshes.length) {
  84020. engine.setColorWrite(false);
  84021. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  84022. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  84023. }
  84024. engine.setColorWrite(true);
  84025. }
  84026. for (index = 0; index < opaqueSubMeshes.length; index++) {
  84027. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  84028. }
  84029. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  84030. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  84031. }
  84032. for (index = 0; index < transparentSubMeshes.length; index++) {
  84033. _this._renderSubMesh(transparentSubMeshes.data[index]);
  84034. }
  84035. };
  84036. this._mainTexture.onClearObservable.add(function (engine) {
  84037. engine.clear(_this.neutralColor, true, true, true);
  84038. });
  84039. };
  84040. /**
  84041. * Checks for the readiness of the element composing the layer.
  84042. * @param subMesh the mesh to check for
  84043. * @param useInstances specify wether or not to use instances to render the mesh
  84044. * @param emissiveTexture the associated emissive texture used to generate the glow
  84045. * @return true if ready otherwise, false
  84046. */
  84047. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  84048. var material = subMesh.getMaterial();
  84049. if (!material) {
  84050. return false;
  84051. }
  84052. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  84053. return false;
  84054. }
  84055. var defines = [];
  84056. var attribs = [BABYLON.VertexBuffer.PositionKind];
  84057. var mesh = subMesh.getMesh();
  84058. var uv1 = false;
  84059. var uv2 = false;
  84060. // Alpha test
  84061. if (material && material.needAlphaTesting()) {
  84062. var alphaTexture = material.getAlphaTestTexture();
  84063. if (alphaTexture) {
  84064. defines.push("#define ALPHATEST");
  84065. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84066. alphaTexture.coordinatesIndex === 1) {
  84067. defines.push("#define DIFFUSEUV2");
  84068. uv2 = true;
  84069. }
  84070. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84071. defines.push("#define DIFFUSEUV1");
  84072. uv1 = true;
  84073. }
  84074. }
  84075. }
  84076. // Emissive
  84077. if (emissiveTexture) {
  84078. defines.push("#define EMISSIVE");
  84079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  84080. emissiveTexture.coordinatesIndex === 1) {
  84081. defines.push("#define EMISSIVEUV2");
  84082. uv2 = true;
  84083. }
  84084. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84085. defines.push("#define EMISSIVEUV1");
  84086. uv1 = true;
  84087. }
  84088. }
  84089. if (uv1) {
  84090. attribs.push(BABYLON.VertexBuffer.UVKind);
  84091. defines.push("#define UV1");
  84092. }
  84093. if (uv2) {
  84094. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84095. defines.push("#define UV2");
  84096. }
  84097. // Bones
  84098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84101. if (mesh.numBoneInfluencers > 4) {
  84102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84104. }
  84105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84106. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  84107. }
  84108. else {
  84109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84110. }
  84111. // Instances
  84112. if (useInstances) {
  84113. defines.push("#define INSTANCES");
  84114. attribs.push("world0");
  84115. attribs.push("world1");
  84116. attribs.push("world2");
  84117. attribs.push("world3");
  84118. }
  84119. // Get correct effect
  84120. var join = defines.join("\n");
  84121. if (this._cachedDefines !== join) {
  84122. this._cachedDefines = join;
  84123. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  84124. }
  84125. return this._effectLayerMapGenerationEffect.isReady();
  84126. };
  84127. /**
  84128. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  84129. */
  84130. EffectLayer.prototype.render = function () {
  84131. var currentEffect = this._mergeEffect;
  84132. // Check
  84133. if (!currentEffect.isReady())
  84134. return;
  84135. for (var i = 0; i < this._postProcesses.length; i++) {
  84136. if (!this._postProcesses[i].isReady()) {
  84137. return;
  84138. }
  84139. }
  84140. var engine = this._scene.getEngine();
  84141. this.onBeforeComposeObservable.notifyObservers(this);
  84142. // Render
  84143. engine.enableEffect(currentEffect);
  84144. engine.setState(false);
  84145. // VBOs
  84146. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84147. // Cache
  84148. var previousAlphaMode = engine.getAlphaMode();
  84149. // Go Blend.
  84150. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  84151. // Blends the map on the main canvas.
  84152. this._internalRender(currentEffect);
  84153. // Restore Alpha
  84154. engine.setAlphaMode(previousAlphaMode);
  84155. this.onAfterComposeObservable.notifyObservers(this);
  84156. // Handle size changes.
  84157. var size = this._mainTexture.getSize();
  84158. this._setMainTextureSize();
  84159. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  84160. // Recreate RTT and post processes on size change.
  84161. this.onSizeChangedObservable.notifyObservers(this);
  84162. this._disposeTextureAndPostProcesses();
  84163. this._createMainTexture();
  84164. this._createTextureAndPostProcesses();
  84165. }
  84166. };
  84167. /**
  84168. * Determine if a given mesh will be used in the current effect.
  84169. * @param mesh mesh to test
  84170. * @returns true if the mesh will be used
  84171. */
  84172. EffectLayer.prototype.hasMesh = function (mesh) {
  84173. return true;
  84174. };
  84175. /**
  84176. * Returns true if the layer contains information to display, otherwise false.
  84177. * @returns true if the glow layer should be rendered
  84178. */
  84179. EffectLayer.prototype.shouldRender = function () {
  84180. return this.isEnabled && this._shouldRender;
  84181. };
  84182. /**
  84183. * Returns true if the mesh should render, otherwise false.
  84184. * @param mesh The mesh to render
  84185. * @returns true if it should render otherwise false
  84186. */
  84187. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  84188. return true;
  84189. };
  84190. /**
  84191. * Returns true if the mesh should render, otherwise false.
  84192. * @param mesh The mesh to render
  84193. * @returns true if it should render otherwise false
  84194. */
  84195. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  84196. return true;
  84197. };
  84198. /**
  84199. * Renders the submesh passed in parameter to the generation map.
  84200. */
  84201. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  84202. var _this = this;
  84203. if (!this.shouldRender()) {
  84204. return;
  84205. }
  84206. var material = subMesh.getMaterial();
  84207. var mesh = subMesh.getRenderingMesh();
  84208. var scene = this._scene;
  84209. var engine = scene.getEngine();
  84210. if (!material) {
  84211. return;
  84212. }
  84213. // Do not block in blend mode.
  84214. if (material.needAlphaBlendingForMesh(mesh)) {
  84215. return;
  84216. }
  84217. // Culling
  84218. engine.setState(material.backFaceCulling);
  84219. // Managing instances
  84220. var batch = mesh._getInstancesRenderList(subMesh._id);
  84221. if (batch.mustReturn) {
  84222. return;
  84223. }
  84224. // Early Exit per mesh
  84225. if (!this._shouldRenderMesh(mesh)) {
  84226. return;
  84227. }
  84228. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84229. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  84230. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  84231. engine.enableEffect(this._effectLayerMapGenerationEffect);
  84232. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  84233. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  84234. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  84235. // Alpha test
  84236. if (material && material.needAlphaTesting()) {
  84237. var alphaTexture = material.getAlphaTestTexture();
  84238. if (alphaTexture) {
  84239. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84240. var textureMatrix = alphaTexture.getTextureMatrix();
  84241. if (textureMatrix) {
  84242. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84243. }
  84244. }
  84245. }
  84246. // Glow emissive only
  84247. if (this._emissiveTextureAndColor.texture) {
  84248. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84249. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84250. }
  84251. // Bones
  84252. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84253. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84254. }
  84255. // Draw
  84256. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84257. }
  84258. else {
  84259. // Need to reset refresh rate of the shadowMap
  84260. this._mainTexture.resetRefreshCounter();
  84261. }
  84262. };
  84263. /**
  84264. * Rebuild the required buffers.
  84265. * @ignore Internal use only.
  84266. */
  84267. EffectLayer.prototype._rebuild = function () {
  84268. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84269. if (vb) {
  84270. vb._rebuild();
  84271. }
  84272. this._generateIndexBuffer();
  84273. };
  84274. /**
  84275. * Dispose only the render target textures and post process.
  84276. */
  84277. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84278. this._mainTexture.dispose();
  84279. for (var i = 0; i < this._postProcesses.length; i++) {
  84280. if (this._postProcesses[i]) {
  84281. this._postProcesses[i].dispose();
  84282. }
  84283. }
  84284. this._postProcesses = [];
  84285. for (var i = 0; i < this._textures.length; i++) {
  84286. if (this._textures[i]) {
  84287. this._textures[i].dispose();
  84288. }
  84289. }
  84290. this._textures = [];
  84291. };
  84292. /**
  84293. * Dispose the highlight layer and free resources.
  84294. */
  84295. EffectLayer.prototype.dispose = function () {
  84296. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84297. if (vertexBuffer) {
  84298. vertexBuffer.dispose();
  84299. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84300. }
  84301. if (this._indexBuffer) {
  84302. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84303. this._indexBuffer = null;
  84304. }
  84305. // Clean textures and post processes
  84306. this._disposeTextureAndPostProcesses();
  84307. // Remove from scene
  84308. var index = this._scene.effectLayers.indexOf(this, 0);
  84309. if (index > -1) {
  84310. this._scene.effectLayers.splice(index, 1);
  84311. }
  84312. // Callback
  84313. this.onDisposeObservable.notifyObservers(this);
  84314. this.onDisposeObservable.clear();
  84315. this.onBeforeRenderMainTextureObservable.clear();
  84316. this.onBeforeComposeObservable.clear();
  84317. this.onAfterComposeObservable.clear();
  84318. this.onSizeChangedObservable.clear();
  84319. };
  84320. return EffectLayer;
  84321. }());
  84322. BABYLON.EffectLayer = EffectLayer;
  84323. })(BABYLON || (BABYLON = {}));
  84324. //# sourceMappingURL=babylon.effectLayer.js.map
  84325. var BABYLON;
  84326. (function (BABYLON) {
  84327. /**
  84328. * Special Glow Blur post process only blurring the alpha channel
  84329. * It enforces keeping the most luminous color in the color channel.
  84330. */
  84331. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84332. __extends(GlowBlurPostProcess, _super);
  84333. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84334. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84335. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84336. _this.direction = direction;
  84337. _this.kernel = kernel;
  84338. _this.onApplyObservable.add(function (effect) {
  84339. effect.setFloat2("screenSize", _this.width, _this.height);
  84340. effect.setVector2("direction", _this.direction);
  84341. effect.setFloat("blurWidth", _this.kernel);
  84342. });
  84343. return _this;
  84344. }
  84345. return GlowBlurPostProcess;
  84346. }(BABYLON.PostProcess));
  84347. /**
  84348. * The highlight layer Helps adding a glow effect around a mesh.
  84349. *
  84350. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84351. * glowy meshes to your scene.
  84352. *
  84353. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84354. */
  84355. var HighlightLayer = /** @class */ (function (_super) {
  84356. __extends(HighlightLayer, _super);
  84357. /**
  84358. * Instantiates a new highlight Layer and references it to the scene..
  84359. * @param name The name of the layer
  84360. * @param scene The scene to use the layer in
  84361. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84362. */
  84363. function HighlightLayer(name, scene, options) {
  84364. var _this = _super.call(this, name, scene) || this;
  84365. _this.name = name;
  84366. /**
  84367. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84368. */
  84369. _this.innerGlow = true;
  84370. /**
  84371. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84372. */
  84373. _this.outerGlow = true;
  84374. /**
  84375. * An event triggered when the highlight layer is being blurred.
  84376. */
  84377. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84378. /**
  84379. * An event triggered when the highlight layer has been blurred.
  84380. */
  84381. _this.onAfterBlurObservable = new BABYLON.Observable();
  84382. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84383. _this._meshes = {};
  84384. _this._excludedMeshes = {};
  84385. _this.neutralColor = HighlightLayer.NeutralColor;
  84386. // Warn on stencil
  84387. if (!_this._engine.isStencilEnable) {
  84388. 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 }");
  84389. }
  84390. // Adapt options
  84391. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84392. // Initialize the layer
  84393. _this._init({
  84394. alphaBlendingMode: _this._options.alphaBlendingMode,
  84395. camera: _this._options.camera,
  84396. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84397. mainTextureRatio: _this._options.mainTextureRatio
  84398. });
  84399. // Do not render as long as no meshes have been added
  84400. _this._shouldRender = false;
  84401. return _this;
  84402. }
  84403. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84404. /**
  84405. * Gets the horizontal size of the blur.
  84406. */
  84407. get: function () {
  84408. return this._horizontalBlurPostprocess.kernel;
  84409. },
  84410. /**
  84411. * Specifies the horizontal size of the blur.
  84412. */
  84413. set: function (value) {
  84414. this._horizontalBlurPostprocess.kernel = value;
  84415. },
  84416. enumerable: true,
  84417. configurable: true
  84418. });
  84419. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84420. /**
  84421. * Gets the vertical size of the blur.
  84422. */
  84423. get: function () {
  84424. return this._verticalBlurPostprocess.kernel;
  84425. },
  84426. /**
  84427. * Specifies the vertical size of the blur.
  84428. */
  84429. set: function (value) {
  84430. this._verticalBlurPostprocess.kernel = value;
  84431. },
  84432. enumerable: true,
  84433. configurable: true
  84434. });
  84435. /**
  84436. * Get the effect name of the layer.
  84437. * @return The effect name
  84438. */
  84439. HighlightLayer.prototype.getEffectName = function () {
  84440. return HighlightLayer.EffectName;
  84441. };
  84442. /**
  84443. * Create the merge effect. This is the shader use to blit the information back
  84444. * to the main canvas at the end of the scene rendering.
  84445. */
  84446. HighlightLayer.prototype._createMergeEffect = function () {
  84447. // Effect
  84448. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84449. };
  84450. /**
  84451. * Creates the render target textures and post processes used in the highlight layer.
  84452. */
  84453. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84454. var _this = this;
  84455. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84456. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84457. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84458. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84459. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84460. width: blurTextureWidth,
  84461. height: blurTextureHeight
  84462. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84463. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84464. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84465. this._blurTexture.anisotropicFilteringLevel = 16;
  84466. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84467. this._blurTexture.renderParticles = false;
  84468. this._blurTexture.ignoreCameraViewport = true;
  84469. this._textures = [this._blurTexture];
  84470. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84471. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84472. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84473. effect.setTexture("textureSampler", _this._mainTexture);
  84474. });
  84475. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84476. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84477. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84478. });
  84479. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84480. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84481. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84482. });
  84483. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84484. }
  84485. else {
  84486. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84487. width: blurTextureWidth,
  84488. height: blurTextureHeight
  84489. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84490. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84491. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84492. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84493. effect.setTexture("textureSampler", _this._mainTexture);
  84494. });
  84495. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84496. width: blurTextureWidth,
  84497. height: blurTextureHeight
  84498. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84499. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84500. }
  84501. this._mainTexture.onAfterUnbindObservable.add(function () {
  84502. _this.onBeforeBlurObservable.notifyObservers(_this);
  84503. var internalTexture = _this._blurTexture.getInternalTexture();
  84504. if (internalTexture) {
  84505. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84506. }
  84507. _this.onAfterBlurObservable.notifyObservers(_this);
  84508. });
  84509. // Prevent autoClear.
  84510. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84511. };
  84512. /**
  84513. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84514. */
  84515. HighlightLayer.prototype.needStencil = function () {
  84516. return true;
  84517. };
  84518. /**
  84519. * Checks for the readiness of the element composing the layer.
  84520. * @param subMesh the mesh to check for
  84521. * @param useInstances specify wether or not to use instances to render the mesh
  84522. * @param emissiveTexture the associated emissive texture used to generate the glow
  84523. * @return true if ready otherwise, false
  84524. */
  84525. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84526. var material = subMesh.getMaterial();
  84527. var mesh = subMesh.getRenderingMesh();
  84528. if (!material || !mesh || !this._meshes) {
  84529. return false;
  84530. }
  84531. var emissiveTexture = null;
  84532. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84533. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84534. emissiveTexture = material.emissiveTexture;
  84535. }
  84536. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84537. };
  84538. /**
  84539. * Implementation specific of rendering the generating effect on the main canvas.
  84540. * @param effect The effect used to render through
  84541. */
  84542. HighlightLayer.prototype._internalRender = function (effect) {
  84543. // Texture
  84544. effect.setTexture("textureSampler", this._blurTexture);
  84545. // Cache
  84546. var engine = this._engine;
  84547. var previousStencilBuffer = engine.getStencilBuffer();
  84548. var previousStencilFunction = engine.getStencilFunction();
  84549. var previousStencilMask = engine.getStencilMask();
  84550. var previousStencilOperationPass = engine.getStencilOperationPass();
  84551. var previousStencilOperationFail = engine.getStencilOperationFail();
  84552. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84553. var previousStencilReference = engine.getStencilFunctionReference();
  84554. // Stencil operations
  84555. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84556. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84557. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84558. // Draw order
  84559. engine.setStencilMask(0x00);
  84560. engine.setStencilBuffer(true);
  84561. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84562. // 2 passes inner outer
  84563. if (this.outerGlow) {
  84564. effect.setFloat("offset", 0);
  84565. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84566. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84567. }
  84568. if (this.innerGlow) {
  84569. effect.setFloat("offset", 1);
  84570. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84571. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84572. }
  84573. // Restore Cache
  84574. engine.setStencilFunction(previousStencilFunction);
  84575. engine.setStencilMask(previousStencilMask);
  84576. engine.setStencilBuffer(previousStencilBuffer);
  84577. engine.setStencilOperationPass(previousStencilOperationPass);
  84578. engine.setStencilOperationFail(previousStencilOperationFail);
  84579. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84580. engine.setStencilFunctionReference(previousStencilReference);
  84581. };
  84582. /**
  84583. * Returns true if the layer contains information to display, otherwise false.
  84584. */
  84585. HighlightLayer.prototype.shouldRender = function () {
  84586. if (_super.prototype.shouldRender.call(this)) {
  84587. return this._meshes ? true : false;
  84588. }
  84589. return false;
  84590. };
  84591. /**
  84592. * Returns true if the mesh should render, otherwise false.
  84593. * @param mesh The mesh to render
  84594. * @returns true if it should render otherwise false
  84595. */
  84596. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84597. // Excluded Mesh
  84598. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84599. return false;
  84600. }
  84601. ;
  84602. return true;
  84603. };
  84604. /**
  84605. * Sets the required values for both the emissive texture and and the main color.
  84606. */
  84607. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84608. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84609. if (highlightLayerMesh) {
  84610. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84611. }
  84612. else {
  84613. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84614. }
  84615. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84616. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84617. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84618. }
  84619. else {
  84620. this._emissiveTextureAndColor.texture = null;
  84621. }
  84622. };
  84623. /**
  84624. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84625. * @param mesh The mesh to exclude from the highlight layer
  84626. */
  84627. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84628. if (!this._excludedMeshes) {
  84629. return;
  84630. }
  84631. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84632. if (!meshExcluded) {
  84633. this._excludedMeshes[mesh.uniqueId] = {
  84634. mesh: mesh,
  84635. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84636. mesh.getEngine().setStencilBuffer(false);
  84637. }),
  84638. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84639. mesh.getEngine().setStencilBuffer(true);
  84640. }),
  84641. };
  84642. }
  84643. };
  84644. /**
  84645. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84646. * @param mesh The mesh to highlight
  84647. */
  84648. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84649. if (!this._excludedMeshes) {
  84650. return;
  84651. }
  84652. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84653. if (meshExcluded) {
  84654. if (meshExcluded.beforeRender) {
  84655. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84656. }
  84657. if (meshExcluded.afterRender) {
  84658. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84659. }
  84660. }
  84661. this._excludedMeshes[mesh.uniqueId] = null;
  84662. };
  84663. /**
  84664. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84665. * @param mesh mesh to test
  84666. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84667. */
  84668. HighlightLayer.prototype.hasMesh = function (mesh) {
  84669. if (!this._meshes) {
  84670. return false;
  84671. }
  84672. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84673. };
  84674. /**
  84675. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84676. * @param mesh The mesh to highlight
  84677. * @param color The color of the highlight
  84678. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84679. */
  84680. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84681. var _this = this;
  84682. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84683. if (!this._meshes) {
  84684. return;
  84685. }
  84686. var meshHighlight = this._meshes[mesh.uniqueId];
  84687. if (meshHighlight) {
  84688. meshHighlight.color = color;
  84689. }
  84690. else {
  84691. this._meshes[mesh.uniqueId] = {
  84692. mesh: mesh,
  84693. color: color,
  84694. // Lambda required for capture due to Observable this context
  84695. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84696. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84697. _this._defaultStencilReference(mesh);
  84698. }
  84699. else {
  84700. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84701. }
  84702. }),
  84703. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84704. glowEmissiveOnly: glowEmissiveOnly
  84705. };
  84706. }
  84707. this._shouldRender = true;
  84708. };
  84709. /**
  84710. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84711. * @param mesh The mesh to highlight
  84712. */
  84713. HighlightLayer.prototype.removeMesh = function (mesh) {
  84714. if (!this._meshes) {
  84715. return;
  84716. }
  84717. var meshHighlight = this._meshes[mesh.uniqueId];
  84718. if (meshHighlight) {
  84719. if (meshHighlight.observerHighlight) {
  84720. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84721. }
  84722. if (meshHighlight.observerDefault) {
  84723. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84724. }
  84725. delete this._meshes[mesh.uniqueId];
  84726. }
  84727. this._shouldRender = false;
  84728. for (var meshHighlightToCheck in this._meshes) {
  84729. if (this._meshes[meshHighlightToCheck]) {
  84730. this._shouldRender = true;
  84731. break;
  84732. }
  84733. }
  84734. };
  84735. /**
  84736. * Force the stencil to the normal expected value for none glowing parts
  84737. */
  84738. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84739. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84740. };
  84741. /**
  84742. * Free any resources and references associated to a mesh.
  84743. * Internal use
  84744. * @param mesh The mesh to free.
  84745. */
  84746. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84747. this.removeMesh(mesh);
  84748. this.removeExcludedMesh(mesh);
  84749. };
  84750. /**
  84751. * Dispose the highlight layer and free resources.
  84752. */
  84753. HighlightLayer.prototype.dispose = function () {
  84754. if (this._meshes) {
  84755. // Clean mesh references
  84756. for (var id in this._meshes) {
  84757. var meshHighlight = this._meshes[id];
  84758. if (meshHighlight && meshHighlight.mesh) {
  84759. if (meshHighlight.observerHighlight) {
  84760. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84761. }
  84762. if (meshHighlight.observerDefault) {
  84763. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84764. }
  84765. }
  84766. }
  84767. this._meshes = null;
  84768. }
  84769. if (this._excludedMeshes) {
  84770. for (var id in this._excludedMeshes) {
  84771. var meshHighlight = this._excludedMeshes[id];
  84772. if (meshHighlight) {
  84773. if (meshHighlight.beforeRender) {
  84774. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84775. }
  84776. if (meshHighlight.afterRender) {
  84777. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84778. }
  84779. }
  84780. }
  84781. this._excludedMeshes = null;
  84782. }
  84783. _super.prototype.dispose.call(this);
  84784. };
  84785. /**
  84786. * Effect Name of the highlight layer.
  84787. */
  84788. HighlightLayer.EffectName = "HighlightLayer";
  84789. /**
  84790. * The neutral color used during the preparation of the glow effect.
  84791. * This is black by default as the blend operation is a blend operation.
  84792. */
  84793. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84794. /**
  84795. * Stencil value used for glowing meshes.
  84796. */
  84797. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84798. /**
  84799. * Stencil value used for the other meshes in the scene.
  84800. */
  84801. HighlightLayer.NormalMeshStencilReference = 0x01;
  84802. return HighlightLayer;
  84803. }(BABYLON.EffectLayer));
  84804. BABYLON.HighlightLayer = HighlightLayer;
  84805. })(BABYLON || (BABYLON = {}));
  84806. //# sourceMappingURL=babylon.highlightLayer.js.map
  84807. var BABYLON;
  84808. (function (BABYLON) {
  84809. /**
  84810. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84811. *
  84812. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84813. * glowy meshes to your scene.
  84814. *
  84815. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84816. */
  84817. var GlowLayer = /** @class */ (function (_super) {
  84818. __extends(GlowLayer, _super);
  84819. /**
  84820. * Instantiates a new glow Layer and references it to the scene.
  84821. * @param name The name of the layer
  84822. * @param scene The scene to use the layer in
  84823. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84824. */
  84825. function GlowLayer(name, scene, options) {
  84826. var _this = _super.call(this, name, scene) || this;
  84827. _this.name = name;
  84828. _this._intensity = 1.0;
  84829. _this._includedOnlyMeshes = [];
  84830. _this._excludedMeshes = [];
  84831. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84832. // Adapt options
  84833. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84834. // Initialize the layer
  84835. _this._init({
  84836. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84837. camera: _this._options.camera,
  84838. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84839. mainTextureRatio: _this._options.mainTextureRatio
  84840. });
  84841. return _this;
  84842. }
  84843. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84844. /**
  84845. * Gets the kernel size of the blur.
  84846. */
  84847. get: function () {
  84848. return this._horizontalBlurPostprocess1.kernel;
  84849. },
  84850. /**
  84851. * Sets the kernel size of the blur.
  84852. */
  84853. set: function (value) {
  84854. this._horizontalBlurPostprocess1.kernel = value;
  84855. this._verticalBlurPostprocess1.kernel = value;
  84856. this._horizontalBlurPostprocess2.kernel = value;
  84857. this._verticalBlurPostprocess2.kernel = value;
  84858. },
  84859. enumerable: true,
  84860. configurable: true
  84861. });
  84862. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84863. /**
  84864. * Gets the glow intensity.
  84865. */
  84866. get: function () {
  84867. return this._intensity;
  84868. },
  84869. /**
  84870. * Sets the glow intensity.
  84871. */
  84872. set: function (value) {
  84873. this._intensity = value;
  84874. },
  84875. enumerable: true,
  84876. configurable: true
  84877. });
  84878. /**
  84879. * Get the effect name of the layer.
  84880. * @return The effect name
  84881. */
  84882. GlowLayer.prototype.getEffectName = function () {
  84883. return GlowLayer.EffectName;
  84884. };
  84885. /**
  84886. * Create the merge effect. This is the shader use to blit the information back
  84887. * to the main canvas at the end of the scene rendering.
  84888. */
  84889. GlowLayer.prototype._createMergeEffect = function () {
  84890. // Effect
  84891. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84892. };
  84893. /**
  84894. * Creates the render target textures and post processes used in the glow layer.
  84895. */
  84896. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84897. var _this = this;
  84898. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84899. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84900. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84901. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84902. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84903. width: blurTextureWidth,
  84904. height: blurTextureHeight
  84905. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84906. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84907. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84908. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84909. this._blurTexture1.renderParticles = false;
  84910. this._blurTexture1.ignoreCameraViewport = true;
  84911. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84912. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84913. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84914. width: blurTextureWidth2,
  84915. height: blurTextureHeight2
  84916. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84917. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84918. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84919. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84920. this._blurTexture2.renderParticles = false;
  84921. this._blurTexture2.ignoreCameraViewport = true;
  84922. this._textures = [this._blurTexture1, this._blurTexture2];
  84923. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84924. width: blurTextureWidth,
  84925. height: blurTextureHeight
  84926. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84927. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84928. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84929. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84930. effect.setTexture("textureSampler", _this._mainTexture);
  84931. });
  84932. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84933. width: blurTextureWidth,
  84934. height: blurTextureHeight
  84935. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84936. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84937. width: blurTextureWidth2,
  84938. height: blurTextureHeight2
  84939. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84940. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84941. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84942. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84943. effect.setTexture("textureSampler", _this._blurTexture1);
  84944. });
  84945. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84946. width: blurTextureWidth2,
  84947. height: blurTextureHeight2
  84948. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84949. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84950. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84951. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84952. this._mainTexture.samples = this._options.mainTextureSamples;
  84953. this._mainTexture.onAfterUnbindObservable.add(function () {
  84954. var internalTexture = _this._blurTexture1.getInternalTexture();
  84955. if (internalTexture) {
  84956. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84957. internalTexture = _this._blurTexture2.getInternalTexture();
  84958. if (internalTexture) {
  84959. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84960. }
  84961. }
  84962. });
  84963. // Prevent autoClear.
  84964. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84965. };
  84966. /**
  84967. * Checks for the readiness of the element composing the layer.
  84968. * @param subMesh the mesh to check for
  84969. * @param useInstances specify wether or not to use instances to render the mesh
  84970. * @param emissiveTexture the associated emissive texture used to generate the glow
  84971. * @return true if ready otherwise, false
  84972. */
  84973. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84974. var material = subMesh.getMaterial();
  84975. var mesh = subMesh.getRenderingMesh();
  84976. if (!material || !mesh) {
  84977. return false;
  84978. }
  84979. var emissiveTexture = material.emissiveTexture;
  84980. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84981. };
  84982. /**
  84983. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84984. */
  84985. GlowLayer.prototype.needStencil = function () {
  84986. return false;
  84987. };
  84988. /**
  84989. * Implementation specific of rendering the generating effect on the main canvas.
  84990. * @param effect The effect used to render through
  84991. */
  84992. GlowLayer.prototype._internalRender = function (effect) {
  84993. // Texture
  84994. effect.setTexture("textureSampler", this._blurTexture1);
  84995. effect.setTexture("textureSampler2", this._blurTexture2);
  84996. effect.setFloat("offset", this._intensity);
  84997. // Cache
  84998. var engine = this._engine;
  84999. var previousStencilBuffer = engine.getStencilBuffer();
  85000. // Draw order
  85001. engine.setStencilBuffer(false);
  85002. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85003. // Draw order
  85004. engine.setStencilBuffer(previousStencilBuffer);
  85005. };
  85006. /**
  85007. * Sets the required values for both the emissive texture and and the main color.
  85008. */
  85009. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85010. var textureLevel = 1.0;
  85011. if (this.customEmissiveTextureSelector) {
  85012. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  85013. }
  85014. else {
  85015. if (material) {
  85016. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85017. if (this._emissiveTextureAndColor.texture) {
  85018. textureLevel = this._emissiveTextureAndColor.texture.level;
  85019. }
  85020. }
  85021. else {
  85022. this._emissiveTextureAndColor.texture = null;
  85023. }
  85024. }
  85025. if (this.customEmissiveColorSelector) {
  85026. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  85027. }
  85028. else {
  85029. if (material.emissiveColor) {
  85030. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  85031. }
  85032. else {
  85033. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85034. }
  85035. }
  85036. };
  85037. /**
  85038. * Returns true if the mesh should render, otherwise false.
  85039. * @param mesh The mesh to render
  85040. * @returns true if it should render otherwise false
  85041. */
  85042. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  85043. return this.hasMesh(mesh);
  85044. };
  85045. /**
  85046. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  85047. * @param mesh The mesh to exclude from the glow layer
  85048. */
  85049. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  85050. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  85051. this._excludedMeshes.push(mesh.uniqueId);
  85052. }
  85053. };
  85054. /**
  85055. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  85056. * @param mesh The mesh to remove
  85057. */
  85058. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  85059. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  85060. if (index !== -1) {
  85061. this._excludedMeshes.splice(index, 1);
  85062. }
  85063. };
  85064. /**
  85065. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  85066. * @param mesh The mesh to include in the glow layer
  85067. */
  85068. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  85069. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  85070. this._includedOnlyMeshes.push(mesh.uniqueId);
  85071. }
  85072. };
  85073. /**
  85074. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  85075. * @param mesh The mesh to remove
  85076. */
  85077. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  85078. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  85079. if (index !== -1) {
  85080. this._includedOnlyMeshes.splice(index, 1);
  85081. }
  85082. };
  85083. /**
  85084. * Determine if a given mesh will be used in the glow layer
  85085. * @param mesh The mesh to test
  85086. * @returns true if the mesh will be highlighted by the current glow layer
  85087. */
  85088. GlowLayer.prototype.hasMesh = function (mesh) {
  85089. // Included Mesh
  85090. if (this._includedOnlyMeshes.length) {
  85091. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  85092. }
  85093. ;
  85094. // Excluded Mesh
  85095. if (this._excludedMeshes.length) {
  85096. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  85097. }
  85098. ;
  85099. return true;
  85100. };
  85101. /**
  85102. * Free any resources and references associated to a mesh.
  85103. * Internal use
  85104. * @param mesh The mesh to free.
  85105. */
  85106. GlowLayer.prototype._disposeMesh = function (mesh) {
  85107. this.removeIncludedOnlyMesh(mesh);
  85108. this.removeExcludedMesh(mesh);
  85109. };
  85110. /**
  85111. * Effect Name of the layer.
  85112. */
  85113. GlowLayer.EffectName = "GlowLayer";
  85114. /**
  85115. * The default blur kernel size used for the glow.
  85116. */
  85117. GlowLayer.DefaultBlurKernelSize = 32;
  85118. /**
  85119. * The default texture size ratio used for the glow.
  85120. */
  85121. GlowLayer.DefaultTextureRatio = 0.5;
  85122. return GlowLayer;
  85123. }(BABYLON.EffectLayer));
  85124. BABYLON.GlowLayer = GlowLayer;
  85125. })(BABYLON || (BABYLON = {}));
  85126. //# sourceMappingURL=babylon.glowLayer.js.map
  85127. var BABYLON;
  85128. (function (BABYLON) {
  85129. /**
  85130. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  85131. */
  85132. var AssetTaskState;
  85133. (function (AssetTaskState) {
  85134. /**
  85135. * Initialization
  85136. */
  85137. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  85138. /**
  85139. * Running
  85140. */
  85141. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  85142. /**
  85143. * Done
  85144. */
  85145. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  85146. /**
  85147. * Error
  85148. */
  85149. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  85150. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  85151. /**
  85152. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  85153. */
  85154. var AbstractAssetTask = /** @class */ (function () {
  85155. /**
  85156. * Creates a new {BABYLON.AssetsManager}
  85157. * @param name defines the name of the task
  85158. */
  85159. function AbstractAssetTask(
  85160. /**
  85161. * Task name
  85162. */ name) {
  85163. this.name = name;
  85164. this._isCompleted = false;
  85165. this._taskState = AssetTaskState.INIT;
  85166. }
  85167. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  85168. /**
  85169. * Get if the task is completed
  85170. */
  85171. get: function () {
  85172. return this._isCompleted;
  85173. },
  85174. enumerable: true,
  85175. configurable: true
  85176. });
  85177. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  85178. /**
  85179. * Gets the current state of the task
  85180. */
  85181. get: function () {
  85182. return this._taskState;
  85183. },
  85184. enumerable: true,
  85185. configurable: true
  85186. });
  85187. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  85188. /**
  85189. * Gets the current error object (if task is in error)
  85190. */
  85191. get: function () {
  85192. return this._errorObject;
  85193. },
  85194. enumerable: true,
  85195. configurable: true
  85196. });
  85197. /**
  85198. * Internal only
  85199. * @ignore
  85200. */
  85201. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  85202. if (this._errorObject) {
  85203. return;
  85204. }
  85205. this._errorObject = {
  85206. message: message,
  85207. exception: exception
  85208. };
  85209. };
  85210. /**
  85211. * Execute the current task
  85212. * @param scene defines the scene where you want your assets to be loaded
  85213. * @param onSuccess is a callback called when the task is successfully executed
  85214. * @param onError is a callback called if an error occurs
  85215. */
  85216. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85217. var _this = this;
  85218. this._taskState = AssetTaskState.RUNNING;
  85219. this.runTask(scene, function () {
  85220. _this.onDoneCallback(onSuccess, onError);
  85221. }, function (msg, exception) {
  85222. _this.onErrorCallback(onError, msg, exception);
  85223. });
  85224. };
  85225. /**
  85226. * Execute the current task
  85227. * @param scene defines the scene where you want your assets to be loaded
  85228. * @param onSuccess is a callback called when the task is successfully executed
  85229. * @param onError is a callback called if an error occurs
  85230. */
  85231. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85232. throw new Error("runTask is not implemented");
  85233. };
  85234. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  85235. this._taskState = AssetTaskState.ERROR;
  85236. this._errorObject = {
  85237. message: message,
  85238. exception: exception
  85239. };
  85240. if (this.onError) {
  85241. this.onError(this, message, exception);
  85242. }
  85243. onError();
  85244. };
  85245. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85246. try {
  85247. this._taskState = AssetTaskState.DONE;
  85248. this._isCompleted = true;
  85249. if (this.onSuccess) {
  85250. this.onSuccess(this);
  85251. }
  85252. onSuccess();
  85253. }
  85254. catch (e) {
  85255. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85256. }
  85257. };
  85258. return AbstractAssetTask;
  85259. }());
  85260. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85261. /**
  85262. * Class used to share progress information about assets loading
  85263. */
  85264. var AssetsProgressEvent = /** @class */ (function () {
  85265. /**
  85266. * Creates a {BABYLON.AssetsProgressEvent}
  85267. * @param remainingCount defines the number of remaining tasks to process
  85268. * @param totalCount defines the total number of tasks
  85269. * @param task defines the task that was just processed
  85270. */
  85271. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85272. this.remainingCount = remainingCount;
  85273. this.totalCount = totalCount;
  85274. this.task = task;
  85275. }
  85276. return AssetsProgressEvent;
  85277. }());
  85278. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85279. /**
  85280. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85281. */
  85282. var MeshAssetTask = /** @class */ (function (_super) {
  85283. __extends(MeshAssetTask, _super);
  85284. /**
  85285. * Creates a new {BABYLON.MeshAssetTask}
  85286. * @param name defines the name of the task
  85287. * @param meshesNames defines the list of mesh's names you want to load
  85288. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85289. * @param sceneFilename defines the filename of the scene to load from
  85290. */
  85291. function MeshAssetTask(
  85292. /**
  85293. * Defines the name of the task
  85294. */
  85295. name,
  85296. /**
  85297. * Defines the list of mesh's names you want to load
  85298. */
  85299. meshesNames,
  85300. /**
  85301. * Defines the root url to use as a base to load your meshes and associated resources
  85302. */
  85303. rootUrl,
  85304. /**
  85305. * Defines the filename of the scene to load from
  85306. */
  85307. sceneFilename) {
  85308. var _this = _super.call(this, name) || this;
  85309. _this.name = name;
  85310. _this.meshesNames = meshesNames;
  85311. _this.rootUrl = rootUrl;
  85312. _this.sceneFilename = sceneFilename;
  85313. return _this;
  85314. }
  85315. /**
  85316. * Execute the current task
  85317. * @param scene defines the scene where you want your assets to be loaded
  85318. * @param onSuccess is a callback called when the task is successfully executed
  85319. * @param onError is a callback called if an error occurs
  85320. */
  85321. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85322. var _this = this;
  85323. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85324. _this.loadedMeshes = meshes;
  85325. _this.loadedParticleSystems = particleSystems;
  85326. _this.loadedSkeletons = skeletons;
  85327. onSuccess();
  85328. }, null, function (scene, message, exception) {
  85329. onError(message, exception);
  85330. });
  85331. };
  85332. return MeshAssetTask;
  85333. }(AbstractAssetTask));
  85334. BABYLON.MeshAssetTask = MeshAssetTask;
  85335. /**
  85336. * Define a task used by {BABYLON.AssetsManager} to load text content
  85337. */
  85338. var TextFileAssetTask = /** @class */ (function (_super) {
  85339. __extends(TextFileAssetTask, _super);
  85340. /**
  85341. * Creates a new TextFileAssetTask object
  85342. * @param name defines the name of the task
  85343. * @param url defines the location of the file to load
  85344. */
  85345. function TextFileAssetTask(
  85346. /**
  85347. * Defines the name of the task
  85348. */
  85349. name,
  85350. /**
  85351. * Defines the location of the file to load
  85352. */
  85353. url) {
  85354. var _this = _super.call(this, name) || this;
  85355. _this.name = name;
  85356. _this.url = url;
  85357. return _this;
  85358. }
  85359. /**
  85360. * Execute the current task
  85361. * @param scene defines the scene where you want your assets to be loaded
  85362. * @param onSuccess is a callback called when the task is successfully executed
  85363. * @param onError is a callback called if an error occurs
  85364. */
  85365. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85366. var _this = this;
  85367. scene._loadFile(this.url, function (data) {
  85368. _this.text = data;
  85369. onSuccess();
  85370. }, undefined, false, false, function (request, exception) {
  85371. if (request) {
  85372. onError(request.status + " " + request.statusText, exception);
  85373. }
  85374. });
  85375. };
  85376. return TextFileAssetTask;
  85377. }(AbstractAssetTask));
  85378. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85379. /**
  85380. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85381. */
  85382. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85383. __extends(BinaryFileAssetTask, _super);
  85384. /**
  85385. * Creates a new BinaryFileAssetTask object
  85386. * @param name defines the name of the new task
  85387. * @param url defines the location of the file to load
  85388. */
  85389. function BinaryFileAssetTask(
  85390. /**
  85391. * Defines the name of the task
  85392. */
  85393. name,
  85394. /**
  85395. * Defines the location of the file to load
  85396. */
  85397. url) {
  85398. var _this = _super.call(this, name) || this;
  85399. _this.name = name;
  85400. _this.url = url;
  85401. return _this;
  85402. }
  85403. /**
  85404. * Execute the current task
  85405. * @param scene defines the scene where you want your assets to be loaded
  85406. * @param onSuccess is a callback called when the task is successfully executed
  85407. * @param onError is a callback called if an error occurs
  85408. */
  85409. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85410. var _this = this;
  85411. scene._loadFile(this.url, function (data) {
  85412. _this.data = data;
  85413. onSuccess();
  85414. }, undefined, true, true, function (request, exception) {
  85415. if (request) {
  85416. onError(request.status + " " + request.statusText, exception);
  85417. }
  85418. });
  85419. };
  85420. return BinaryFileAssetTask;
  85421. }(AbstractAssetTask));
  85422. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85423. /**
  85424. * Define a task used by {BABYLON.AssetsManager} to load images
  85425. */
  85426. var ImageAssetTask = /** @class */ (function (_super) {
  85427. __extends(ImageAssetTask, _super);
  85428. /**
  85429. * Creates a new ImageAssetTask
  85430. * @param name defines the name of the task
  85431. * @param url defines the location of the image to load
  85432. */
  85433. function ImageAssetTask(
  85434. /**
  85435. * Defines the name of the task
  85436. */
  85437. name,
  85438. /**
  85439. * Defines the location of the image to load
  85440. */
  85441. url) {
  85442. var _this = _super.call(this, name) || this;
  85443. _this.name = name;
  85444. _this.url = url;
  85445. return _this;
  85446. }
  85447. /**
  85448. * Execute the current task
  85449. * @param scene defines the scene where you want your assets to be loaded
  85450. * @param onSuccess is a callback called when the task is successfully executed
  85451. * @param onError is a callback called if an error occurs
  85452. */
  85453. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85454. var _this = this;
  85455. var img = new Image();
  85456. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85457. img.onload = function () {
  85458. _this.image = img;
  85459. onSuccess();
  85460. };
  85461. img.onerror = function (err) {
  85462. onError("Error loading image", err);
  85463. };
  85464. img.src = this.url;
  85465. };
  85466. return ImageAssetTask;
  85467. }(AbstractAssetTask));
  85468. BABYLON.ImageAssetTask = ImageAssetTask;
  85469. /**
  85470. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85471. */
  85472. var TextureAssetTask = /** @class */ (function (_super) {
  85473. __extends(TextureAssetTask, _super);
  85474. /**
  85475. * Creates a new TextureAssetTask object
  85476. * @param name defines the name of the task
  85477. * @param url defines the location of the file to load
  85478. * @param noMipmap defines if mipmap should not be generated (default is false)
  85479. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85480. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85481. */
  85482. function TextureAssetTask(
  85483. /**
  85484. * Defines the name of the task
  85485. */
  85486. name,
  85487. /**
  85488. * Defines the location of the file to load
  85489. */
  85490. url,
  85491. /**
  85492. * Defines if mipmap should not be generated (default is false)
  85493. */
  85494. noMipmap,
  85495. /**
  85496. * Defines if texture must be inverted on Y axis (default is false)
  85497. */
  85498. invertY,
  85499. /**
  85500. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85501. */
  85502. samplingMode) {
  85503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85504. var _this = _super.call(this, name) || this;
  85505. _this.name = name;
  85506. _this.url = url;
  85507. _this.noMipmap = noMipmap;
  85508. _this.invertY = invertY;
  85509. _this.samplingMode = samplingMode;
  85510. return _this;
  85511. }
  85512. /**
  85513. * Execute the current task
  85514. * @param scene defines the scene where you want your assets to be loaded
  85515. * @param onSuccess is a callback called when the task is successfully executed
  85516. * @param onError is a callback called if an error occurs
  85517. */
  85518. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85519. var onload = function () {
  85520. onSuccess();
  85521. };
  85522. var onerror = function (message, exception) {
  85523. onError(message, exception);
  85524. };
  85525. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85526. };
  85527. return TextureAssetTask;
  85528. }(AbstractAssetTask));
  85529. BABYLON.TextureAssetTask = TextureAssetTask;
  85530. /**
  85531. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85532. */
  85533. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85534. __extends(CubeTextureAssetTask, _super);
  85535. /**
  85536. * Creates a new CubeTextureAssetTask
  85537. * @param name defines the name of the task
  85538. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85539. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85540. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85541. * @param files defines the explicit list of files (undefined by default)
  85542. */
  85543. function CubeTextureAssetTask(
  85544. /**
  85545. * Defines the name of the task
  85546. */
  85547. name,
  85548. /**
  85549. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85550. */
  85551. url,
  85552. /**
  85553. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85554. */
  85555. extensions,
  85556. /**
  85557. * Defines if mipmaps should not be generated (default is false)
  85558. */
  85559. noMipmap,
  85560. /**
  85561. * Defines the explicit list of files (undefined by default)
  85562. */
  85563. files) {
  85564. var _this = _super.call(this, name) || this;
  85565. _this.name = name;
  85566. _this.url = url;
  85567. _this.extensions = extensions;
  85568. _this.noMipmap = noMipmap;
  85569. _this.files = files;
  85570. return _this;
  85571. }
  85572. /**
  85573. * Execute the current task
  85574. * @param scene defines the scene where you want your assets to be loaded
  85575. * @param onSuccess is a callback called when the task is successfully executed
  85576. * @param onError is a callback called if an error occurs
  85577. */
  85578. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85579. var onload = function () {
  85580. onSuccess();
  85581. };
  85582. var onerror = function (message, exception) {
  85583. onError(message, exception);
  85584. };
  85585. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85586. };
  85587. return CubeTextureAssetTask;
  85588. }(AbstractAssetTask));
  85589. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85590. /**
  85591. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85592. */
  85593. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85594. __extends(HDRCubeTextureAssetTask, _super);
  85595. /**
  85596. * Creates a new HDRCubeTextureAssetTask object
  85597. * @param name defines the name of the task
  85598. * @param url defines the location of the file to load
  85599. * @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.
  85600. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85601. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85602. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  85603. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85604. */
  85605. function HDRCubeTextureAssetTask(
  85606. /**
  85607. * Defines the name of the task
  85608. */
  85609. name,
  85610. /**
  85611. * Defines the location of the file to load
  85612. */
  85613. url,
  85614. /**
  85615. * 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.
  85616. */
  85617. size,
  85618. /**
  85619. * Defines if mipmaps should not be generated (default is false)
  85620. */
  85621. noMipmap,
  85622. /**
  85623. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85624. */
  85625. generateHarmonics,
  85626. /**
  85627. * 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)
  85628. */
  85629. useInGammaSpace,
  85630. /**
  85631. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85632. */
  85633. usePMREMGenerator) {
  85634. if (noMipmap === void 0) { noMipmap = false; }
  85635. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85636. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85637. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85638. var _this = _super.call(this, name) || this;
  85639. _this.name = name;
  85640. _this.url = url;
  85641. _this.size = size;
  85642. _this.noMipmap = noMipmap;
  85643. _this.generateHarmonics = generateHarmonics;
  85644. _this.useInGammaSpace = useInGammaSpace;
  85645. _this.usePMREMGenerator = usePMREMGenerator;
  85646. return _this;
  85647. }
  85648. /**
  85649. * Execute the current task
  85650. * @param scene defines the scene where you want your assets to be loaded
  85651. * @param onSuccess is a callback called when the task is successfully executed
  85652. * @param onError is a callback called if an error occurs
  85653. */
  85654. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85655. var onload = function () {
  85656. onSuccess();
  85657. };
  85658. var onerror = function (message, exception) {
  85659. onError(message, exception);
  85660. };
  85661. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85662. };
  85663. return HDRCubeTextureAssetTask;
  85664. }(AbstractAssetTask));
  85665. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85666. /**
  85667. * This class can be used to easily import assets into a scene
  85668. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85669. */
  85670. var AssetsManager = /** @class */ (function () {
  85671. /**
  85672. * Creates a new AssetsManager
  85673. * @param scene defines the scene to work on
  85674. */
  85675. function AssetsManager(scene) {
  85676. this._isLoading = false;
  85677. this._tasks = new Array();
  85678. this._waitingTasksCount = 0;
  85679. this._totalTasksCount = 0;
  85680. /**
  85681. * Observable called when all tasks are processed
  85682. */
  85683. this.onTaskSuccessObservable = new BABYLON.Observable();
  85684. /**
  85685. * Observable called when a task had an error
  85686. */
  85687. this.onTaskErrorObservable = new BABYLON.Observable();
  85688. /**
  85689. * Observable called when a task is successful
  85690. */
  85691. this.onTasksDoneObservable = new BABYLON.Observable();
  85692. /**
  85693. * Observable called when a task is done (whatever the result is)
  85694. */
  85695. this.onProgressObservable = new BABYLON.Observable();
  85696. /**
  85697. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85698. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85699. */
  85700. this.useDefaultLoadingScreen = true;
  85701. this._scene = scene;
  85702. }
  85703. /**
  85704. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85705. * @param taskName defines the name of the new task
  85706. * @param meshesNames defines the name of meshes to load
  85707. * @param rootUrl defines the root url to use to locate files
  85708. * @param sceneFilename defines the filename of the scene file
  85709. * @returns a new {BABYLON.MeshAssetTask} object
  85710. */
  85711. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85712. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85713. this._tasks.push(task);
  85714. return task;
  85715. };
  85716. /**
  85717. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85718. * @param taskName defines the name of the new task
  85719. * @param url defines the url of the file to load
  85720. * @returns a new {BABYLON.TextFileAssetTask} object
  85721. */
  85722. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85723. var task = new TextFileAssetTask(taskName, url);
  85724. this._tasks.push(task);
  85725. return task;
  85726. };
  85727. /**
  85728. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85729. * @param taskName defines the name of the new task
  85730. * @param url defines the url of the file to load
  85731. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85732. */
  85733. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85734. var task = new BinaryFileAssetTask(taskName, url);
  85735. this._tasks.push(task);
  85736. return task;
  85737. };
  85738. /**
  85739. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85740. * @param taskName defines the name of the new task
  85741. * @param url defines the url of the file to load
  85742. * @returns a new {BABYLON.ImageAssetTask} object
  85743. */
  85744. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85745. var task = new ImageAssetTask(taskName, url);
  85746. this._tasks.push(task);
  85747. return task;
  85748. };
  85749. /**
  85750. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85751. * @param taskName defines the name of the new task
  85752. * @param url defines the url of the file to load
  85753. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85754. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85755. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85756. * @returns a new {BABYLON.TextureAssetTask} object
  85757. */
  85758. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85759. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85760. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85761. this._tasks.push(task);
  85762. return task;
  85763. };
  85764. /**
  85765. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85766. * @param taskName defines the name of the new task
  85767. * @param url defines the url of the file to load
  85768. * @param extensions defines the extension to use to load the cube map (can be null)
  85769. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85770. * @param files defines the list of files to load (can be null)
  85771. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85772. */
  85773. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85774. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85775. this._tasks.push(task);
  85776. return task;
  85777. };
  85778. /**
  85779. *
  85780. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85781. * @param taskName defines the name of the new task
  85782. * @param url defines the url of the file to load
  85783. * @param size defines the size you want for the cubemap (can be null)
  85784. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85785. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85786. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85787. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85788. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85789. */
  85790. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85791. if (noMipmap === void 0) { noMipmap = false; }
  85792. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85793. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85794. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85795. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85796. this._tasks.push(task);
  85797. return task;
  85798. };
  85799. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85800. var _this = this;
  85801. this._waitingTasksCount--;
  85802. try {
  85803. if (task.taskState === AssetTaskState.DONE) {
  85804. // Let's remove successfull tasks
  85805. BABYLON.Tools.SetImmediate(function () {
  85806. var index = _this._tasks.indexOf(task);
  85807. if (index > -1) {
  85808. _this._tasks.splice(index, 1);
  85809. }
  85810. });
  85811. }
  85812. if (this.onProgress) {
  85813. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85814. }
  85815. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85816. }
  85817. catch (e) {
  85818. BABYLON.Tools.Error("Error running progress callbacks.");
  85819. console.log(e);
  85820. }
  85821. if (this._waitingTasksCount === 0) {
  85822. try {
  85823. if (this.onFinish) {
  85824. this.onFinish(this._tasks);
  85825. }
  85826. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85827. }
  85828. catch (e) {
  85829. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85830. console.log(e);
  85831. }
  85832. this._isLoading = false;
  85833. this._scene.getEngine().hideLoadingUI();
  85834. }
  85835. };
  85836. AssetsManager.prototype._runTask = function (task) {
  85837. var _this = this;
  85838. var done = function () {
  85839. try {
  85840. if (_this.onTaskSuccess) {
  85841. _this.onTaskSuccess(task);
  85842. }
  85843. _this.onTaskSuccessObservable.notifyObservers(task);
  85844. _this._decreaseWaitingTasksCount(task);
  85845. }
  85846. catch (e) {
  85847. error("Error executing task success callbacks", e);
  85848. }
  85849. };
  85850. var error = function (message, exception) {
  85851. task._setErrorObject(message, exception);
  85852. if (_this.onTaskError) {
  85853. _this.onTaskError(task);
  85854. }
  85855. _this.onTaskErrorObservable.notifyObservers(task);
  85856. _this._decreaseWaitingTasksCount(task);
  85857. };
  85858. task.run(this._scene, done, error);
  85859. };
  85860. /**
  85861. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85862. * @return the current instance of the {BABYLON.AssetsManager}
  85863. */
  85864. AssetsManager.prototype.reset = function () {
  85865. this._isLoading = false;
  85866. this._tasks = new Array();
  85867. return this;
  85868. };
  85869. /**
  85870. * Start the loading process
  85871. * @return the current instance of the {BABYLON.AssetsManager}
  85872. */
  85873. AssetsManager.prototype.load = function () {
  85874. if (this._isLoading) {
  85875. return this;
  85876. }
  85877. this._isLoading = true;
  85878. this._waitingTasksCount = this._tasks.length;
  85879. this._totalTasksCount = this._tasks.length;
  85880. if (this._waitingTasksCount === 0) {
  85881. this._isLoading = false;
  85882. if (this.onFinish) {
  85883. this.onFinish(this._tasks);
  85884. }
  85885. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85886. return this;
  85887. }
  85888. if (this.useDefaultLoadingScreen) {
  85889. this._scene.getEngine().displayLoadingUI();
  85890. }
  85891. for (var index = 0; index < this._tasks.length; index++) {
  85892. var task = this._tasks[index];
  85893. this._runTask(task);
  85894. }
  85895. return this;
  85896. };
  85897. return AssetsManager;
  85898. }());
  85899. BABYLON.AssetsManager = AssetsManager;
  85900. })(BABYLON || (BABYLON = {}));
  85901. //# sourceMappingURL=babylon.assetsManager.js.map
  85902. var BABYLON;
  85903. (function (BABYLON) {
  85904. var serializedGeometries = [];
  85905. var serializeGeometry = function (geometry, serializationGeometries) {
  85906. if (serializedGeometries[geometry.id]) {
  85907. return;
  85908. }
  85909. if (geometry.doNotSerialize) {
  85910. return;
  85911. }
  85912. if (geometry instanceof BABYLON.BoxGeometry) {
  85913. serializationGeometries.boxes.push(geometry.serialize());
  85914. }
  85915. else if (geometry instanceof BABYLON.SphereGeometry) {
  85916. serializationGeometries.spheres.push(geometry.serialize());
  85917. }
  85918. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85919. serializationGeometries.cylinders.push(geometry.serialize());
  85920. }
  85921. else if (geometry instanceof BABYLON.TorusGeometry) {
  85922. serializationGeometries.toruses.push(geometry.serialize());
  85923. }
  85924. else if (geometry instanceof BABYLON.GroundGeometry) {
  85925. serializationGeometries.grounds.push(geometry.serialize());
  85926. }
  85927. else if (geometry instanceof BABYLON.Plane) {
  85928. serializationGeometries.planes.push(geometry.serialize());
  85929. }
  85930. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85931. serializationGeometries.torusKnots.push(geometry.serialize());
  85932. }
  85933. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85934. throw new Error("Unknown primitive type");
  85935. }
  85936. else {
  85937. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85938. }
  85939. serializedGeometries[geometry.id] = true;
  85940. };
  85941. var serializeMesh = function (mesh, serializationScene) {
  85942. var serializationObject = {};
  85943. // Geometry
  85944. var geometry = mesh._geometry;
  85945. if (geometry) {
  85946. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85947. // 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
  85948. serializeGeometry(geometry, serializationScene.geometries);
  85949. }
  85950. }
  85951. // Custom
  85952. if (mesh.serialize) {
  85953. mesh.serialize(serializationObject);
  85954. }
  85955. return serializationObject;
  85956. };
  85957. var finalizeSingleMesh = function (mesh, serializationObject) {
  85958. //only works if the mesh is already loaded
  85959. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85960. //serialize material
  85961. if (mesh.material) {
  85962. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85963. serializationObject.materials = serializationObject.materials || [];
  85964. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85965. serializationObject.materials.push(mesh.material.serialize());
  85966. }
  85967. }
  85968. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85969. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85970. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85971. serializationObject.multiMaterials.push(mesh.material.serialize());
  85972. }
  85973. }
  85974. }
  85975. //serialize geometry
  85976. var geometry = mesh._geometry;
  85977. if (geometry) {
  85978. if (!serializationObject.geometries) {
  85979. serializationObject.geometries = {};
  85980. serializationObject.geometries.boxes = [];
  85981. serializationObject.geometries.spheres = [];
  85982. serializationObject.geometries.cylinders = [];
  85983. serializationObject.geometries.toruses = [];
  85984. serializationObject.geometries.grounds = [];
  85985. serializationObject.geometries.planes = [];
  85986. serializationObject.geometries.torusKnots = [];
  85987. serializationObject.geometries.vertexData = [];
  85988. }
  85989. serializeGeometry(geometry, serializationObject.geometries);
  85990. }
  85991. // Skeletons
  85992. if (mesh.skeleton) {
  85993. serializationObject.skeletons = serializationObject.skeletons || [];
  85994. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85995. }
  85996. //serialize the actual mesh
  85997. serializationObject.meshes = serializationObject.meshes || [];
  85998. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85999. }
  86000. };
  86001. var SceneSerializer = /** @class */ (function () {
  86002. function SceneSerializer() {
  86003. }
  86004. SceneSerializer.ClearCache = function () {
  86005. serializedGeometries = [];
  86006. };
  86007. SceneSerializer.Serialize = function (scene) {
  86008. var serializationObject = {};
  86009. SceneSerializer.ClearCache();
  86010. // Scene
  86011. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  86012. serializationObject.autoClear = scene.autoClear;
  86013. serializationObject.clearColor = scene.clearColor.asArray();
  86014. serializationObject.ambientColor = scene.ambientColor.asArray();
  86015. serializationObject.gravity = scene.gravity.asArray();
  86016. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  86017. serializationObject.workerCollisions = scene.workerCollisions;
  86018. // Fog
  86019. if (scene.fogMode && scene.fogMode !== 0) {
  86020. serializationObject.fogMode = scene.fogMode;
  86021. serializationObject.fogColor = scene.fogColor.asArray();
  86022. serializationObject.fogStart = scene.fogStart;
  86023. serializationObject.fogEnd = scene.fogEnd;
  86024. serializationObject.fogDensity = scene.fogDensity;
  86025. }
  86026. //Physics
  86027. if (scene.isPhysicsEnabled()) {
  86028. var physicEngine = scene.getPhysicsEngine();
  86029. if (physicEngine) {
  86030. serializationObject.physicsEnabled = true;
  86031. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  86032. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  86033. }
  86034. }
  86035. // Metadata
  86036. if (scene.metadata) {
  86037. serializationObject.metadata = scene.metadata;
  86038. }
  86039. // Morph targets
  86040. serializationObject.morphTargetManagers = [];
  86041. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  86042. var abstractMesh = _a[_i];
  86043. var manager = abstractMesh.morphTargetManager;
  86044. if (manager) {
  86045. serializationObject.morphTargetManagers.push(manager.serialize());
  86046. }
  86047. }
  86048. // Lights
  86049. serializationObject.lights = [];
  86050. var index;
  86051. var light;
  86052. for (index = 0; index < scene.lights.length; index++) {
  86053. light = scene.lights[index];
  86054. if (!light.doNotSerialize) {
  86055. serializationObject.lights.push(light.serialize());
  86056. }
  86057. }
  86058. // Cameras
  86059. serializationObject.cameras = [];
  86060. for (index = 0; index < scene.cameras.length; index++) {
  86061. var camera = scene.cameras[index];
  86062. if (!camera.doNotSerialize) {
  86063. serializationObject.cameras.push(camera.serialize());
  86064. }
  86065. }
  86066. if (scene.activeCamera) {
  86067. serializationObject.activeCameraID = scene.activeCamera.id;
  86068. }
  86069. // Animations
  86070. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  86071. // Materials
  86072. serializationObject.materials = [];
  86073. serializationObject.multiMaterials = [];
  86074. var material;
  86075. for (index = 0; index < scene.materials.length; index++) {
  86076. material = scene.materials[index];
  86077. if (!material.doNotSerialize) {
  86078. serializationObject.materials.push(material.serialize());
  86079. }
  86080. }
  86081. // MultiMaterials
  86082. serializationObject.multiMaterials = [];
  86083. for (index = 0; index < scene.multiMaterials.length; index++) {
  86084. var multiMaterial = scene.multiMaterials[index];
  86085. serializationObject.multiMaterials.push(multiMaterial.serialize());
  86086. }
  86087. // Environment texture
  86088. if (scene.environmentTexture) {
  86089. serializationObject.environmentTexture = scene.environmentTexture.name;
  86090. }
  86091. // Skeletons
  86092. serializationObject.skeletons = [];
  86093. for (index = 0; index < scene.skeletons.length; index++) {
  86094. var skeleton = scene.skeletons[index];
  86095. if (!skeleton.doNotSerialize) {
  86096. serializationObject.skeletons.push(skeleton.serialize());
  86097. }
  86098. }
  86099. // Transform nodes
  86100. serializationObject.transformNodes = [];
  86101. for (index = 0; index < scene.transformNodes.length; index++) {
  86102. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  86103. }
  86104. // Geometries
  86105. serializationObject.geometries = {};
  86106. serializationObject.geometries.boxes = [];
  86107. serializationObject.geometries.spheres = [];
  86108. serializationObject.geometries.cylinders = [];
  86109. serializationObject.geometries.toruses = [];
  86110. serializationObject.geometries.grounds = [];
  86111. serializationObject.geometries.planes = [];
  86112. serializationObject.geometries.torusKnots = [];
  86113. serializationObject.geometries.vertexData = [];
  86114. serializedGeometries = [];
  86115. var geometries = scene.getGeometries();
  86116. for (index = 0; index < geometries.length; index++) {
  86117. var geometry = geometries[index];
  86118. if (geometry.isReady()) {
  86119. serializeGeometry(geometry, serializationObject.geometries);
  86120. }
  86121. }
  86122. // Meshes
  86123. serializationObject.meshes = [];
  86124. for (index = 0; index < scene.meshes.length; index++) {
  86125. var abstractMesh = scene.meshes[index];
  86126. if (abstractMesh instanceof BABYLON.Mesh) {
  86127. var mesh = abstractMesh;
  86128. if (!mesh.doNotSerialize) {
  86129. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  86130. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  86131. }
  86132. }
  86133. }
  86134. }
  86135. // Particles Systems
  86136. serializationObject.particleSystems = [];
  86137. for (index = 0; index < scene.particleSystems.length; index++) {
  86138. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  86139. }
  86140. // Lens flares
  86141. serializationObject.lensFlareSystems = [];
  86142. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  86143. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  86144. }
  86145. // Shadows
  86146. serializationObject.shadowGenerators = [];
  86147. for (index = 0; index < scene.lights.length; index++) {
  86148. light = scene.lights[index];
  86149. var shadowGenerator = light.getShadowGenerator();
  86150. if (shadowGenerator) {
  86151. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  86152. }
  86153. }
  86154. // Action Manager
  86155. if (scene.actionManager) {
  86156. serializationObject.actions = scene.actionManager.serialize("scene");
  86157. }
  86158. // Audio
  86159. serializationObject.sounds = [];
  86160. for (index = 0; index < scene.soundTracks.length; index++) {
  86161. var soundtrack = scene.soundTracks[index];
  86162. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  86163. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  86164. }
  86165. }
  86166. return serializationObject;
  86167. };
  86168. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  86169. if (withParents === void 0) { withParents = false; }
  86170. if (withChildren === void 0) { withChildren = false; }
  86171. var serializationObject = {};
  86172. SceneSerializer.ClearCache();
  86173. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  86174. if (withParents || withChildren) {
  86175. //deliberate for loop! not for each, appended should be processed as well.
  86176. for (var i = 0; i < toSerialize.length; ++i) {
  86177. if (withChildren) {
  86178. toSerialize[i].getDescendants().forEach(function (node) {
  86179. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  86180. toSerialize.push(node);
  86181. }
  86182. });
  86183. }
  86184. //make sure the array doesn't contain the object already
  86185. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  86186. toSerialize.push(toSerialize[i].parent);
  86187. }
  86188. }
  86189. }
  86190. toSerialize.forEach(function (mesh) {
  86191. finalizeSingleMesh(mesh, serializationObject);
  86192. });
  86193. return serializationObject;
  86194. };
  86195. return SceneSerializer;
  86196. }());
  86197. BABYLON.SceneSerializer = SceneSerializer;
  86198. })(BABYLON || (BABYLON = {}));
  86199. //# sourceMappingURL=babylon.sceneSerializer.js.map
  86200. var BABYLON;
  86201. (function (BABYLON) {
  86202. var ReflectionProbe = /** @class */ (function () {
  86203. function ReflectionProbe(name, size, scene, generateMipMaps) {
  86204. if (generateMipMaps === void 0) { generateMipMaps = true; }
  86205. var _this = this;
  86206. this.name = name;
  86207. this._viewMatrix = BABYLON.Matrix.Identity();
  86208. this._target = BABYLON.Vector3.Zero();
  86209. this._add = BABYLON.Vector3.Zero();
  86210. this._invertYAxis = false;
  86211. this.position = BABYLON.Vector3.Zero();
  86212. this._scene = scene;
  86213. this._scene.reflectionProbes.push(this);
  86214. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  86215. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  86216. switch (faceIndex) {
  86217. case 0:
  86218. _this._add.copyFromFloats(1, 0, 0);
  86219. break;
  86220. case 1:
  86221. _this._add.copyFromFloats(-1, 0, 0);
  86222. break;
  86223. case 2:
  86224. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  86225. break;
  86226. case 3:
  86227. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  86228. break;
  86229. case 4:
  86230. _this._add.copyFromFloats(0, 0, 1);
  86231. break;
  86232. case 5:
  86233. _this._add.copyFromFloats(0, 0, -1);
  86234. break;
  86235. }
  86236. if (_this._attachedMesh) {
  86237. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  86238. }
  86239. _this.position.addToRef(_this._add, _this._target);
  86240. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86241. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86242. scene._forcedViewPosition = _this.position;
  86243. });
  86244. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86245. scene._forcedViewPosition = null;
  86246. scene.updateTransformMatrix(true);
  86247. });
  86248. if (scene.activeCamera) {
  86249. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86250. }
  86251. }
  86252. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86253. get: function () {
  86254. return this._renderTargetTexture.samples;
  86255. },
  86256. set: function (value) {
  86257. this._renderTargetTexture.samples = value;
  86258. },
  86259. enumerable: true,
  86260. configurable: true
  86261. });
  86262. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86263. get: function () {
  86264. return this._renderTargetTexture.refreshRate;
  86265. },
  86266. set: function (value) {
  86267. this._renderTargetTexture.refreshRate = value;
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. ReflectionProbe.prototype.getScene = function () {
  86273. return this._scene;
  86274. };
  86275. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86276. get: function () {
  86277. return this._renderTargetTexture;
  86278. },
  86279. enumerable: true,
  86280. configurable: true
  86281. });
  86282. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86283. get: function () {
  86284. return this._renderTargetTexture.renderList;
  86285. },
  86286. enumerable: true,
  86287. configurable: true
  86288. });
  86289. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86290. this._attachedMesh = mesh;
  86291. };
  86292. /**
  86293. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86294. *
  86295. * @param renderingGroupId The rendering group id corresponding to its index
  86296. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86297. */
  86298. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86299. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86300. };
  86301. ReflectionProbe.prototype.dispose = function () {
  86302. var index = this._scene.reflectionProbes.indexOf(this);
  86303. if (index !== -1) {
  86304. // Remove from the scene if found
  86305. this._scene.reflectionProbes.splice(index, 1);
  86306. }
  86307. if (this._renderTargetTexture) {
  86308. this._renderTargetTexture.dispose();
  86309. this._renderTargetTexture = null;
  86310. }
  86311. };
  86312. return ReflectionProbe;
  86313. }());
  86314. BABYLON.ReflectionProbe = ReflectionProbe;
  86315. })(BABYLON || (BABYLON = {}));
  86316. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86317. var BABYLON;
  86318. (function (BABYLON) {
  86319. var Layer = /** @class */ (function () {
  86320. function Layer(name, imgUrl, scene, isBackground, color) {
  86321. this.name = name;
  86322. this.scale = new BABYLON.Vector2(1, 1);
  86323. this.offset = new BABYLON.Vector2(0, 0);
  86324. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86325. this.layerMask = 0x0FFFFFFF;
  86326. this._vertexBuffers = {};
  86327. // Events
  86328. /**
  86329. * An event triggered when the layer is disposed.
  86330. * @type {BABYLON.Observable}
  86331. */
  86332. this.onDisposeObservable = new BABYLON.Observable();
  86333. /**
  86334. * An event triggered before rendering the scene
  86335. * @type {BABYLON.Observable}
  86336. */
  86337. this.onBeforeRenderObservable = new BABYLON.Observable();
  86338. /**
  86339. * An event triggered after rendering the scene
  86340. * @type {BABYLON.Observable}
  86341. */
  86342. this.onAfterRenderObservable = new BABYLON.Observable();
  86343. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86344. this.isBackground = isBackground === undefined ? true : isBackground;
  86345. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86346. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86347. this._scene.layers.push(this);
  86348. var engine = this._scene.getEngine();
  86349. // VBO
  86350. var vertices = [];
  86351. vertices.push(1, 1);
  86352. vertices.push(-1, 1);
  86353. vertices.push(-1, -1);
  86354. vertices.push(1, -1);
  86355. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86356. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86357. this._createIndexBuffer();
  86358. // Effects
  86359. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86360. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86361. }
  86362. Object.defineProperty(Layer.prototype, "onDispose", {
  86363. set: function (callback) {
  86364. if (this._onDisposeObserver) {
  86365. this.onDisposeObservable.remove(this._onDisposeObserver);
  86366. }
  86367. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86368. },
  86369. enumerable: true,
  86370. configurable: true
  86371. });
  86372. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86373. set: function (callback) {
  86374. if (this._onBeforeRenderObserver) {
  86375. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86376. }
  86377. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86378. },
  86379. enumerable: true,
  86380. configurable: true
  86381. });
  86382. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86383. set: function (callback) {
  86384. if (this._onAfterRenderObserver) {
  86385. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86386. }
  86387. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86388. },
  86389. enumerable: true,
  86390. configurable: true
  86391. });
  86392. Layer.prototype._createIndexBuffer = function () {
  86393. var engine = this._scene.getEngine();
  86394. // Indices
  86395. var indices = [];
  86396. indices.push(0);
  86397. indices.push(1);
  86398. indices.push(2);
  86399. indices.push(0);
  86400. indices.push(2);
  86401. indices.push(3);
  86402. this._indexBuffer = engine.createIndexBuffer(indices);
  86403. };
  86404. Layer.prototype._rebuild = function () {
  86405. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86406. if (vb) {
  86407. vb._rebuild();
  86408. }
  86409. this._createIndexBuffer();
  86410. };
  86411. Layer.prototype.render = function () {
  86412. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86413. // Check
  86414. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86415. return;
  86416. var engine = this._scene.getEngine();
  86417. this.onBeforeRenderObservable.notifyObservers(this);
  86418. // Render
  86419. engine.enableEffect(currentEffect);
  86420. engine.setState(false);
  86421. // Texture
  86422. currentEffect.setTexture("textureSampler", this.texture);
  86423. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86424. // Color
  86425. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86426. // Scale / offset
  86427. currentEffect.setVector2("offset", this.offset);
  86428. currentEffect.setVector2("scale", this.scale);
  86429. // VBOs
  86430. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86431. // Draw order
  86432. if (!this.alphaTest) {
  86433. engine.setAlphaMode(this.alphaBlendingMode);
  86434. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86435. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86436. }
  86437. else {
  86438. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86439. }
  86440. this.onAfterRenderObservable.notifyObservers(this);
  86441. };
  86442. Layer.prototype.dispose = function () {
  86443. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86444. if (vertexBuffer) {
  86445. vertexBuffer.dispose();
  86446. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86447. }
  86448. if (this._indexBuffer) {
  86449. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86450. this._indexBuffer = null;
  86451. }
  86452. if (this.texture) {
  86453. this.texture.dispose();
  86454. this.texture = null;
  86455. }
  86456. // Remove from scene
  86457. var index = this._scene.layers.indexOf(this);
  86458. this._scene.layers.splice(index, 1);
  86459. // Callback
  86460. this.onDisposeObservable.notifyObservers(this);
  86461. this.onDisposeObservable.clear();
  86462. this.onAfterRenderObservable.clear();
  86463. this.onBeforeRenderObservable.clear();
  86464. };
  86465. return Layer;
  86466. }());
  86467. BABYLON.Layer = Layer;
  86468. })(BABYLON || (BABYLON = {}));
  86469. //# sourceMappingURL=babylon.layer.js.map
  86470. var BABYLON;
  86471. (function (BABYLON) {
  86472. var TextureTools = /** @class */ (function () {
  86473. function TextureTools() {
  86474. }
  86475. /**
  86476. * Uses the GPU to create a copy texture rescaled at a given size
  86477. * @param texture Texture to copy from
  86478. * @param width Desired width
  86479. * @param height Desired height
  86480. * @return Generated texture
  86481. */
  86482. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86483. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86484. var scene = texture.getScene();
  86485. var engine = scene.getEngine();
  86486. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86487. rtt.wrapU = texture.wrapU;
  86488. rtt.wrapV = texture.wrapV;
  86489. rtt.uOffset = texture.uOffset;
  86490. rtt.vOffset = texture.vOffset;
  86491. rtt.uScale = texture.uScale;
  86492. rtt.vScale = texture.vScale;
  86493. rtt.uAng = texture.uAng;
  86494. rtt.vAng = texture.vAng;
  86495. rtt.wAng = texture.wAng;
  86496. rtt.coordinatesIndex = texture.coordinatesIndex;
  86497. rtt.level = texture.level;
  86498. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86499. rtt._texture.isReady = false;
  86500. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86501. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86502. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86503. passPostProcess.getEffect().executeWhenCompiled(function () {
  86504. passPostProcess.onApply = function (effect) {
  86505. effect.setTexture("textureSampler", texture);
  86506. };
  86507. var internalTexture = rtt.getInternalTexture();
  86508. if (internalTexture) {
  86509. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86510. engine.unBindFramebuffer(internalTexture);
  86511. rtt.disposeFramebufferObjects();
  86512. passPostProcess.dispose();
  86513. internalTexture.isReady = true;
  86514. }
  86515. });
  86516. return rtt;
  86517. };
  86518. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86519. if (!scene._environmentBRDFTexture) {
  86520. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86521. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86522. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86523. scene._environmentBRDFTexture = texture;
  86524. }
  86525. return scene._environmentBRDFTexture;
  86526. };
  86527. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  86528. return TextureTools;
  86529. }());
  86530. BABYLON.TextureTools = TextureTools;
  86531. })(BABYLON || (BABYLON = {}));
  86532. //# sourceMappingURL=babylon.textureTools.js.map
  86533. var BABYLON;
  86534. (function (BABYLON) {
  86535. var FramingBehavior = /** @class */ (function () {
  86536. function FramingBehavior() {
  86537. this._mode = FramingBehavior.FitFrustumSidesMode;
  86538. this._radiusScale = 1.0;
  86539. this._positionScale = 0.5;
  86540. this._defaultElevation = 0.3;
  86541. this._elevationReturnTime = 1500;
  86542. this._elevationReturnWaitTime = 1000;
  86543. this._zoomStopsAnimation = false;
  86544. this._framingTime = 1500;
  86545. this._isPointerDown = false;
  86546. this._lastInteractionTime = -Infinity;
  86547. // Framing control
  86548. this._animatables = new Array();
  86549. this._betaIsAnimating = false;
  86550. }
  86551. Object.defineProperty(FramingBehavior.prototype, "name", {
  86552. get: function () {
  86553. return "Framing";
  86554. },
  86555. enumerable: true,
  86556. configurable: true
  86557. });
  86558. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86559. /**
  86560. * Gets current mode used by the behavior.
  86561. */
  86562. get: function () {
  86563. return this._mode;
  86564. },
  86565. /**
  86566. * Sets the current mode used by the behavior
  86567. */
  86568. set: function (mode) {
  86569. this._mode = mode;
  86570. },
  86571. enumerable: true,
  86572. configurable: true
  86573. });
  86574. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86575. /**
  86576. * Gets the scale applied to the radius
  86577. */
  86578. get: function () {
  86579. return this._radiusScale;
  86580. },
  86581. /**
  86582. * Sets the scale applied to the radius (1 by default)
  86583. */
  86584. set: function (radius) {
  86585. this._radiusScale = radius;
  86586. },
  86587. enumerable: true,
  86588. configurable: true
  86589. });
  86590. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86591. /**
  86592. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86593. */
  86594. get: function () {
  86595. return this._positionScale;
  86596. },
  86597. /**
  86598. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86599. */
  86600. set: function (scale) {
  86601. this._positionScale = scale;
  86602. },
  86603. enumerable: true,
  86604. configurable: true
  86605. });
  86606. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86607. /**
  86608. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86609. * behaviour is triggered, in radians.
  86610. */
  86611. get: function () {
  86612. return this._defaultElevation;
  86613. },
  86614. /**
  86615. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86616. * behaviour is triggered, in radians.
  86617. */
  86618. set: function (elevation) {
  86619. this._defaultElevation = elevation;
  86620. },
  86621. enumerable: true,
  86622. configurable: true
  86623. });
  86624. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86625. /**
  86626. * Gets the time (in milliseconds) taken to return to the default beta position.
  86627. * Negative value indicates camera should not return to default.
  86628. */
  86629. get: function () {
  86630. return this._elevationReturnTime;
  86631. },
  86632. /**
  86633. * Sets the time (in milliseconds) taken to return to the default beta position.
  86634. * Negative value indicates camera should not return to default.
  86635. */
  86636. set: function (speed) {
  86637. this._elevationReturnTime = speed;
  86638. },
  86639. enumerable: true,
  86640. configurable: true
  86641. });
  86642. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86643. /**
  86644. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86645. */
  86646. get: function () {
  86647. return this._elevationReturnWaitTime;
  86648. },
  86649. /**
  86650. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86651. */
  86652. set: function (time) {
  86653. this._elevationReturnWaitTime = time;
  86654. },
  86655. enumerable: true,
  86656. configurable: true
  86657. });
  86658. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86659. /**
  86660. * Gets the flag that indicates if user zooming should stop animation.
  86661. */
  86662. get: function () {
  86663. return this._zoomStopsAnimation;
  86664. },
  86665. /**
  86666. * Sets the flag that indicates if user zooming should stop animation.
  86667. */
  86668. set: function (flag) {
  86669. this._zoomStopsAnimation = flag;
  86670. },
  86671. enumerable: true,
  86672. configurable: true
  86673. });
  86674. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86675. /**
  86676. * Gets the transition time when framing the mesh, in milliseconds
  86677. */
  86678. get: function () {
  86679. return this._framingTime;
  86680. },
  86681. /**
  86682. * Sets the transition time when framing the mesh, in milliseconds
  86683. */
  86684. set: function (time) {
  86685. this._framingTime = time;
  86686. },
  86687. enumerable: true,
  86688. configurable: true
  86689. });
  86690. FramingBehavior.prototype.init = function () {
  86691. // Do notihng
  86692. };
  86693. FramingBehavior.prototype.attach = function (camera) {
  86694. var _this = this;
  86695. this._attachedCamera = camera;
  86696. var scene = this._attachedCamera.getScene();
  86697. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86698. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86699. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86700. _this._isPointerDown = true;
  86701. return;
  86702. }
  86703. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86704. _this._isPointerDown = false;
  86705. }
  86706. });
  86707. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86708. if (mesh) {
  86709. _this.zoomOnMesh(mesh);
  86710. }
  86711. });
  86712. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86713. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86714. _this._applyUserInteraction();
  86715. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86716. // back to the default position after a given timeout
  86717. _this._maintainCameraAboveGround();
  86718. });
  86719. };
  86720. FramingBehavior.prototype.detach = function () {
  86721. if (!this._attachedCamera) {
  86722. return;
  86723. }
  86724. var scene = this._attachedCamera.getScene();
  86725. if (this._onPrePointerObservableObserver) {
  86726. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86727. }
  86728. if (this._onAfterCheckInputsObserver) {
  86729. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86730. }
  86731. if (this._onMeshTargetChangedObserver) {
  86732. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86733. }
  86734. this._attachedCamera = null;
  86735. };
  86736. /**
  86737. * Targets the given mesh and updates zoom level accordingly.
  86738. * @param mesh The mesh to target.
  86739. * @param radius Optional. If a cached radius position already exists, overrides default.
  86740. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86741. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86742. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86743. */
  86744. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86745. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86746. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86747. mesh.computeWorldMatrix(true);
  86748. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86749. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86750. };
  86751. /**
  86752. * Targets the given mesh with its children and updates zoom level accordingly.
  86753. * @param mesh The mesh to target.
  86754. * @param radius Optional. If a cached radius position already exists, overrides default.
  86755. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86756. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86757. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86758. */
  86759. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86760. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86761. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86762. mesh.computeWorldMatrix(true);
  86763. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86764. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86765. };
  86766. /**
  86767. * Targets the given meshes with their children and updates zoom level accordingly.
  86768. * @param meshes The mesh to target.
  86769. * @param radius Optional. If a cached radius position already exists, overrides default.
  86770. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86771. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86772. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86773. */
  86774. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86775. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86776. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86777. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86778. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86779. for (var i = 0; i < meshes.length; i++) {
  86780. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86781. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86782. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86783. }
  86784. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86785. };
  86786. /**
  86787. * Targets the given mesh and updates zoom level accordingly.
  86788. * @param mesh The mesh to target.
  86789. * @param radius Optional. If a cached radius position already exists, overrides default.
  86790. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86791. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86792. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86793. */
  86794. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86795. var _this = this;
  86796. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86797. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86798. var zoomTarget;
  86799. if (!this._attachedCamera) {
  86800. return;
  86801. }
  86802. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86803. var bottom = minimumWorld.y;
  86804. var top = maximumWorld.y;
  86805. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86806. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86807. if (focusOnOriginXZ) {
  86808. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86809. }
  86810. else {
  86811. var centerWorld = minimumWorld.add(radiusWorld);
  86812. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86813. }
  86814. if (!this._vectorTransition) {
  86815. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86816. }
  86817. this._betaIsAnimating = true;
  86818. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86819. if (animatable) {
  86820. this._animatables.push(animatable);
  86821. }
  86822. // sets the radius and lower radius bounds
  86823. // Small delta ensures camera is not always at lower zoom limit.
  86824. var radius = 0;
  86825. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86826. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86827. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86828. radius = position;
  86829. }
  86830. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86831. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86832. if (this._attachedCamera.lowerRadiusLimit === null) {
  86833. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86834. }
  86835. }
  86836. // Set sensibilities
  86837. var extend = maximumWorld.subtract(minimumWorld).length();
  86838. this._attachedCamera.panningSensibility = 5000 / extend;
  86839. this._attachedCamera.wheelPrecision = 100 / radius;
  86840. // transition to new radius
  86841. if (!this._radiusTransition) {
  86842. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86843. }
  86844. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86845. if (onAnimationEnd) {
  86846. onAnimationEnd();
  86847. }
  86848. if (_this._attachedCamera) {
  86849. _this._attachedCamera.storeState();
  86850. }
  86851. });
  86852. if (animatable) {
  86853. this._animatables.push(animatable);
  86854. }
  86855. };
  86856. /**
  86857. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86858. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86859. * frustum width.
  86860. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86861. * to fully enclose the mesh in the viewing frustum.
  86862. */
  86863. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86864. var size = maximumWorld.subtract(minimumWorld);
  86865. var boxVectorGlobalDiagonal = size.length();
  86866. var frustumSlope = this._getFrustumSlope();
  86867. // Formula for setting distance
  86868. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86869. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86870. // Horizon distance
  86871. var radius = radiusWithoutFraming * this._radiusScale;
  86872. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86873. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86874. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86875. var camera = this._attachedCamera;
  86876. if (!camera) {
  86877. return 0;
  86878. }
  86879. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86880. // Don't exceed the requested limit
  86881. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86882. }
  86883. // Don't exceed the upper radius limit
  86884. if (camera.upperRadiusLimit) {
  86885. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86886. }
  86887. return distance;
  86888. };
  86889. /**
  86890. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86891. * is automatically returned to its default position (expected to be above ground plane).
  86892. */
  86893. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86894. var _this = this;
  86895. if (this._elevationReturnTime < 0) {
  86896. return;
  86897. }
  86898. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86899. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86900. var limitBeta = Math.PI * 0.5;
  86901. // Bring the camera back up if below the ground plane
  86902. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86903. this._betaIsAnimating = true;
  86904. //Transition to new position
  86905. this.stopAllAnimations();
  86906. if (!this._betaTransition) {
  86907. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86908. }
  86909. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86910. _this._clearAnimationLocks();
  86911. _this.stopAllAnimations();
  86912. });
  86913. if (animatabe) {
  86914. this._animatables.push(animatabe);
  86915. }
  86916. }
  86917. };
  86918. /**
  86919. * Returns the frustum slope based on the canvas ratio and camera FOV
  86920. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86921. */
  86922. FramingBehavior.prototype._getFrustumSlope = function () {
  86923. // Calculate the viewport ratio
  86924. // Aspect Ratio is Height/Width.
  86925. var camera = this._attachedCamera;
  86926. if (!camera) {
  86927. return BABYLON.Vector2.Zero();
  86928. }
  86929. var engine = camera.getScene().getEngine();
  86930. var aspectRatio = engine.getAspectRatio(camera);
  86931. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86932. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86933. var frustumSlopeY = Math.tan(camera.fov / 2);
  86934. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86935. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86936. // along the forward vector.
  86937. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86938. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86939. };
  86940. /**
  86941. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86942. */
  86943. FramingBehavior.prototype._clearAnimationLocks = function () {
  86944. this._betaIsAnimating = false;
  86945. };
  86946. /**
  86947. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86948. */
  86949. FramingBehavior.prototype._applyUserInteraction = function () {
  86950. if (this.isUserIsMoving) {
  86951. this._lastInteractionTime = BABYLON.Tools.Now;
  86952. this.stopAllAnimations();
  86953. this._clearAnimationLocks();
  86954. }
  86955. };
  86956. /**
  86957. * Stops and removes all animations that have been applied to the camera
  86958. */
  86959. FramingBehavior.prototype.stopAllAnimations = function () {
  86960. if (this._attachedCamera) {
  86961. this._attachedCamera.animations = [];
  86962. }
  86963. while (this._animatables.length) {
  86964. if (this._animatables[0]) {
  86965. this._animatables[0].onAnimationEnd = null;
  86966. this._animatables[0].stop();
  86967. }
  86968. this._animatables.shift();
  86969. }
  86970. };
  86971. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86972. /**
  86973. * Gets a value indicating if the user is moving the camera
  86974. */
  86975. get: function () {
  86976. if (!this._attachedCamera) {
  86977. return false;
  86978. }
  86979. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86980. this._attachedCamera.inertialBetaOffset !== 0 ||
  86981. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86982. this._attachedCamera.inertialPanningX !== 0 ||
  86983. this._attachedCamera.inertialPanningY !== 0 ||
  86984. this._isPointerDown;
  86985. },
  86986. enumerable: true,
  86987. configurable: true
  86988. });
  86989. /**
  86990. * The easing function used by animations
  86991. */
  86992. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86993. /**
  86994. * The easing mode used by animations
  86995. */
  86996. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86997. // Statics
  86998. /**
  86999. * The camera can move all the way towards the mesh.
  87000. */
  87001. FramingBehavior.IgnoreBoundsSizeMode = 0;
  87002. /**
  87003. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  87004. */
  87005. FramingBehavior.FitFrustumSidesMode = 1;
  87006. return FramingBehavior;
  87007. }());
  87008. BABYLON.FramingBehavior = FramingBehavior;
  87009. })(BABYLON || (BABYLON = {}));
  87010. //# sourceMappingURL=babylon.framingBehavior.js.map
  87011. var BABYLON;
  87012. (function (BABYLON) {
  87013. /**
  87014. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  87015. */
  87016. var BouncingBehavior = /** @class */ (function () {
  87017. function BouncingBehavior() {
  87018. /**
  87019. * The duration of the animation, in milliseconds
  87020. */
  87021. this.transitionDuration = 450;
  87022. /**
  87023. * Length of the distance animated by the transition when lower radius is reached
  87024. */
  87025. this.lowerRadiusTransitionRange = 2;
  87026. /**
  87027. * Length of the distance animated by the transition when upper radius is reached
  87028. */
  87029. this.upperRadiusTransitionRange = -2;
  87030. this._autoTransitionRange = false;
  87031. // Animations
  87032. this._radiusIsAnimating = false;
  87033. this._radiusBounceTransition = null;
  87034. this._animatables = new Array();
  87035. }
  87036. Object.defineProperty(BouncingBehavior.prototype, "name", {
  87037. get: function () {
  87038. return "Bouncing";
  87039. },
  87040. enumerable: true,
  87041. configurable: true
  87042. });
  87043. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  87044. /**
  87045. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87046. */
  87047. get: function () {
  87048. return this._autoTransitionRange;
  87049. },
  87050. /**
  87051. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  87052. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  87053. */
  87054. set: function (value) {
  87055. var _this = this;
  87056. if (this._autoTransitionRange === value) {
  87057. return;
  87058. }
  87059. this._autoTransitionRange = value;
  87060. var camera = this._attachedCamera;
  87061. if (!camera) {
  87062. return;
  87063. }
  87064. if (value) {
  87065. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  87066. if (!mesh) {
  87067. return;
  87068. }
  87069. mesh.computeWorldMatrix(true);
  87070. var diagonal = mesh.getBoundingInfo().diagonalLength;
  87071. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  87072. _this.upperRadiusTransitionRange = diagonal * 0.05;
  87073. });
  87074. }
  87075. else if (this._onMeshTargetChangedObserver) {
  87076. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87077. }
  87078. },
  87079. enumerable: true,
  87080. configurable: true
  87081. });
  87082. BouncingBehavior.prototype.init = function () {
  87083. // Do notihng
  87084. };
  87085. BouncingBehavior.prototype.attach = function (camera) {
  87086. var _this = this;
  87087. this._attachedCamera = camera;
  87088. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87089. if (!_this._attachedCamera) {
  87090. return;
  87091. }
  87092. // Add the bounce animation to the lower radius limit
  87093. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  87094. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  87095. }
  87096. // Add the bounce animation to the upper radius limit
  87097. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  87098. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  87099. }
  87100. });
  87101. };
  87102. BouncingBehavior.prototype.detach = function () {
  87103. if (!this._attachedCamera) {
  87104. return;
  87105. }
  87106. if (this._onAfterCheckInputsObserver) {
  87107. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87108. }
  87109. if (this._onMeshTargetChangedObserver) {
  87110. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  87111. }
  87112. this._attachedCamera = null;
  87113. };
  87114. /**
  87115. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  87116. * @param radiusLimit The limit to check against.
  87117. * @return Bool to indicate if at limit.
  87118. */
  87119. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  87120. if (!this._attachedCamera) {
  87121. return false;
  87122. }
  87123. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  87124. return true;
  87125. }
  87126. return false;
  87127. };
  87128. /**
  87129. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  87130. * @param radiusDelta The delta by which to animate to. Can be negative.
  87131. */
  87132. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  87133. var _this = this;
  87134. if (!this._attachedCamera) {
  87135. return;
  87136. }
  87137. if (!this._radiusBounceTransition) {
  87138. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  87139. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  87140. }
  87141. // Prevent zoom until bounce has completed
  87142. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  87143. this._attachedCamera.wheelPrecision = Infinity;
  87144. this._attachedCamera.inertialRadiusOffset = 0;
  87145. // Animate to the radius limit
  87146. this.stopAllAnimations();
  87147. this._radiusIsAnimating = true;
  87148. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  87149. if (animatable) {
  87150. this._animatables.push(animatable);
  87151. }
  87152. };
  87153. /**
  87154. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  87155. */
  87156. BouncingBehavior.prototype._clearAnimationLocks = function () {
  87157. this._radiusIsAnimating = false;
  87158. if (this._attachedCamera) {
  87159. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  87160. }
  87161. };
  87162. /**
  87163. * Stops and removes all animations that have been applied to the camera
  87164. */
  87165. BouncingBehavior.prototype.stopAllAnimations = function () {
  87166. if (this._attachedCamera) {
  87167. this._attachedCamera.animations = [];
  87168. }
  87169. while (this._animatables.length) {
  87170. this._animatables[0].onAnimationEnd = null;
  87171. this._animatables[0].stop();
  87172. this._animatables.shift();
  87173. }
  87174. };
  87175. /**
  87176. * The easing function used by animations
  87177. */
  87178. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  87179. /**
  87180. * The easing mode used by animations
  87181. */
  87182. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  87183. return BouncingBehavior;
  87184. }());
  87185. BABYLON.BouncingBehavior = BouncingBehavior;
  87186. })(BABYLON || (BABYLON = {}));
  87187. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  87188. var BABYLON;
  87189. (function (BABYLON) {
  87190. var AutoRotationBehavior = /** @class */ (function () {
  87191. function AutoRotationBehavior() {
  87192. this._zoomStopsAnimation = false;
  87193. this._idleRotationSpeed = 0.05;
  87194. this._idleRotationWaitTime = 2000;
  87195. this._idleRotationSpinupTime = 2000;
  87196. this._isPointerDown = false;
  87197. this._lastFrameTime = null;
  87198. this._lastInteractionTime = -Infinity;
  87199. this._cameraRotationSpeed = 0;
  87200. this._lastFrameRadius = 0;
  87201. }
  87202. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  87203. get: function () {
  87204. return "AutoRotation";
  87205. },
  87206. enumerable: true,
  87207. configurable: true
  87208. });
  87209. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  87210. /**
  87211. * Gets the flag that indicates if user zooming should stop animation.
  87212. */
  87213. get: function () {
  87214. return this._zoomStopsAnimation;
  87215. },
  87216. /**
  87217. * Sets the flag that indicates if user zooming should stop animation.
  87218. */
  87219. set: function (flag) {
  87220. this._zoomStopsAnimation = flag;
  87221. },
  87222. enumerable: true,
  87223. configurable: true
  87224. });
  87225. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  87226. /**
  87227. * Gets the default speed at which the camera rotates around the model.
  87228. */
  87229. get: function () {
  87230. return this._idleRotationSpeed;
  87231. },
  87232. /**
  87233. * Sets the default speed at which the camera rotates around the model.
  87234. */
  87235. set: function (speed) {
  87236. this._idleRotationSpeed = speed;
  87237. },
  87238. enumerable: true,
  87239. configurable: true
  87240. });
  87241. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87242. /**
  87243. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87244. */
  87245. get: function () {
  87246. return this._idleRotationWaitTime;
  87247. },
  87248. /**
  87249. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87250. */
  87251. set: function (time) {
  87252. this._idleRotationWaitTime = time;
  87253. },
  87254. enumerable: true,
  87255. configurable: true
  87256. });
  87257. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87258. /**
  87259. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87260. */
  87261. get: function () {
  87262. return this._idleRotationSpinupTime;
  87263. },
  87264. /**
  87265. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87266. */
  87267. set: function (time) {
  87268. this._idleRotationSpinupTime = time;
  87269. },
  87270. enumerable: true,
  87271. configurable: true
  87272. });
  87273. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87274. /**
  87275. * Gets a value indicating if the camera is currently rotating because of this behavior
  87276. */
  87277. get: function () {
  87278. return Math.abs(this._cameraRotationSpeed) > 0;
  87279. },
  87280. enumerable: true,
  87281. configurable: true
  87282. });
  87283. AutoRotationBehavior.prototype.init = function () {
  87284. // Do notihng
  87285. };
  87286. AutoRotationBehavior.prototype.attach = function (camera) {
  87287. var _this = this;
  87288. this._attachedCamera = camera;
  87289. var scene = this._attachedCamera.getScene();
  87290. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87291. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87292. _this._isPointerDown = true;
  87293. return;
  87294. }
  87295. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87296. _this._isPointerDown = false;
  87297. }
  87298. });
  87299. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87300. var now = BABYLON.Tools.Now;
  87301. var dt = 0;
  87302. if (_this._lastFrameTime != null) {
  87303. dt = now - _this._lastFrameTime;
  87304. }
  87305. _this._lastFrameTime = now;
  87306. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87307. _this._applyUserInteraction();
  87308. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87309. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87310. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87311. // Step camera rotation by rotation speed
  87312. if (_this._attachedCamera) {
  87313. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87314. }
  87315. });
  87316. };
  87317. AutoRotationBehavior.prototype.detach = function () {
  87318. if (!this._attachedCamera) {
  87319. return;
  87320. }
  87321. var scene = this._attachedCamera.getScene();
  87322. if (this._onPrePointerObservableObserver) {
  87323. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87324. }
  87325. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87326. this._attachedCamera = null;
  87327. };
  87328. /**
  87329. * Returns true if user is scrolling.
  87330. * @return true if user is scrolling.
  87331. */
  87332. AutoRotationBehavior.prototype._userIsZooming = function () {
  87333. if (!this._attachedCamera) {
  87334. return false;
  87335. }
  87336. return this._attachedCamera.inertialRadiusOffset !== 0;
  87337. };
  87338. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87339. if (!this._attachedCamera) {
  87340. return false;
  87341. }
  87342. var zoomHasHitLimit = false;
  87343. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87344. zoomHasHitLimit = true;
  87345. }
  87346. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87347. this._lastFrameRadius = this._attachedCamera.radius;
  87348. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87349. };
  87350. /**
  87351. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87352. */
  87353. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87354. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87355. this._lastInteractionTime = BABYLON.Tools.Now;
  87356. }
  87357. };
  87358. // Tools
  87359. AutoRotationBehavior.prototype._userIsMoving = function () {
  87360. if (!this._attachedCamera) {
  87361. return false;
  87362. }
  87363. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87364. this._attachedCamera.inertialBetaOffset !== 0 ||
  87365. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87366. this._attachedCamera.inertialPanningX !== 0 ||
  87367. this._attachedCamera.inertialPanningY !== 0 ||
  87368. this._isPointerDown;
  87369. };
  87370. return AutoRotationBehavior;
  87371. }());
  87372. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87373. })(BABYLON || (BABYLON = {}));
  87374. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87375. var BABYLON;
  87376. (function (BABYLON) {
  87377. /**
  87378. * This class can be used to get instrumentation data from a Babylon engine
  87379. */
  87380. var EngineInstrumentation = /** @class */ (function () {
  87381. function EngineInstrumentation(engine) {
  87382. this.engine = engine;
  87383. this._captureGPUFrameTime = false;
  87384. this._gpuFrameTime = new BABYLON.PerfCounter();
  87385. this._captureShaderCompilationTime = false;
  87386. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87387. // Observers
  87388. this._onBeginFrameObserver = null;
  87389. this._onEndFrameObserver = null;
  87390. this._onBeforeShaderCompilationObserver = null;
  87391. this._onAfterShaderCompilationObserver = null;
  87392. }
  87393. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87394. // Properties
  87395. /**
  87396. * Gets the perf counter used for GPU frame time
  87397. */
  87398. get: function () {
  87399. return this._gpuFrameTime;
  87400. },
  87401. enumerable: true,
  87402. configurable: true
  87403. });
  87404. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87405. /**
  87406. * Gets the GPU frame time capture status
  87407. */
  87408. get: function () {
  87409. return this._captureGPUFrameTime;
  87410. },
  87411. /**
  87412. * Enable or disable the GPU frame time capture
  87413. */
  87414. set: function (value) {
  87415. var _this = this;
  87416. if (value === this._captureGPUFrameTime) {
  87417. return;
  87418. }
  87419. this._captureGPUFrameTime = value;
  87420. if (value) {
  87421. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87422. if (!_this._gpuFrameTimeToken) {
  87423. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87424. }
  87425. });
  87426. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87427. if (!_this._gpuFrameTimeToken) {
  87428. return;
  87429. }
  87430. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87431. if (time > -1) {
  87432. _this._gpuFrameTimeToken = null;
  87433. _this._gpuFrameTime.fetchNewFrame();
  87434. _this._gpuFrameTime.addCount(time, true);
  87435. }
  87436. });
  87437. }
  87438. else {
  87439. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87440. this._onBeginFrameObserver = null;
  87441. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87442. this._onEndFrameObserver = null;
  87443. }
  87444. },
  87445. enumerable: true,
  87446. configurable: true
  87447. });
  87448. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87449. /**
  87450. * Gets the perf counter used for shader compilation time
  87451. */
  87452. get: function () {
  87453. return this._shaderCompilationTime;
  87454. },
  87455. enumerable: true,
  87456. configurable: true
  87457. });
  87458. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87459. /**
  87460. * Gets the shader compilation time capture status
  87461. */
  87462. get: function () {
  87463. return this._captureShaderCompilationTime;
  87464. },
  87465. /**
  87466. * Enable or disable the shader compilation time capture
  87467. */
  87468. set: function (value) {
  87469. var _this = this;
  87470. if (value === this._captureShaderCompilationTime) {
  87471. return;
  87472. }
  87473. this._captureShaderCompilationTime = value;
  87474. if (value) {
  87475. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87476. _this._shaderCompilationTime.fetchNewFrame();
  87477. _this._shaderCompilationTime.beginMonitoring();
  87478. });
  87479. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87480. _this._shaderCompilationTime.endMonitoring();
  87481. });
  87482. }
  87483. else {
  87484. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87485. this._onBeforeShaderCompilationObserver = null;
  87486. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87487. this._onAfterShaderCompilationObserver = null;
  87488. }
  87489. },
  87490. enumerable: true,
  87491. configurable: true
  87492. });
  87493. EngineInstrumentation.prototype.dispose = function () {
  87494. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87495. this._onBeginFrameObserver = null;
  87496. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87497. this._onEndFrameObserver = null;
  87498. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87499. this._onBeforeShaderCompilationObserver = null;
  87500. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87501. this._onAfterShaderCompilationObserver = null;
  87502. this.engine = null;
  87503. };
  87504. return EngineInstrumentation;
  87505. }());
  87506. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87507. })(BABYLON || (BABYLON = {}));
  87508. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87509. var BABYLON;
  87510. (function (BABYLON) {
  87511. /**
  87512. * This class can be used to get instrumentation data from a Babylon engine
  87513. */
  87514. var SceneInstrumentation = /** @class */ (function () {
  87515. function SceneInstrumentation(scene) {
  87516. var _this = this;
  87517. this.scene = scene;
  87518. this._captureActiveMeshesEvaluationTime = false;
  87519. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87520. this._captureRenderTargetsRenderTime = false;
  87521. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87522. this._captureFrameTime = false;
  87523. this._frameTime = new BABYLON.PerfCounter();
  87524. this._captureRenderTime = false;
  87525. this._renderTime = new BABYLON.PerfCounter();
  87526. this._captureInterFrameTime = false;
  87527. this._interFrameTime = new BABYLON.PerfCounter();
  87528. this._captureParticlesRenderTime = false;
  87529. this._particlesRenderTime = new BABYLON.PerfCounter();
  87530. this._captureSpritesRenderTime = false;
  87531. this._spritesRenderTime = new BABYLON.PerfCounter();
  87532. this._capturePhysicsTime = false;
  87533. this._physicsTime = new BABYLON.PerfCounter();
  87534. this._captureAnimationsTime = false;
  87535. this._animationsTime = new BABYLON.PerfCounter();
  87536. // Observers
  87537. this._onBeforeActiveMeshesEvaluationObserver = null;
  87538. this._onAfterActiveMeshesEvaluationObserver = null;
  87539. this._onBeforeRenderTargetsRenderObserver = null;
  87540. this._onAfterRenderTargetsRenderObserver = null;
  87541. this._onAfterRenderObserver = null;
  87542. this._onBeforeDrawPhaseObserver = null;
  87543. this._onAfterDrawPhaseObserver = null;
  87544. this._onBeforeAnimationsObserver = null;
  87545. this._onBeforeParticlesRenderingObserver = null;
  87546. this._onAfterParticlesRenderingObserver = null;
  87547. this._onBeforeSpritesRenderingObserver = null;
  87548. this._onAfterSpritesRenderingObserver = null;
  87549. this._onBeforePhysicsObserver = null;
  87550. this._onAfterPhysicsObserver = null;
  87551. this._onAfterAnimationsObserver = null;
  87552. // Before render
  87553. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87554. if (_this._captureActiveMeshesEvaluationTime) {
  87555. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87556. }
  87557. if (_this._captureRenderTargetsRenderTime) {
  87558. _this._renderTargetsRenderTime.fetchNewFrame();
  87559. }
  87560. if (_this._captureFrameTime) {
  87561. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87562. _this._frameTime.beginMonitoring();
  87563. }
  87564. if (_this._captureInterFrameTime) {
  87565. _this._interFrameTime.endMonitoring();
  87566. }
  87567. if (_this._captureParticlesRenderTime) {
  87568. _this._particlesRenderTime.fetchNewFrame();
  87569. }
  87570. if (_this._captureSpritesRenderTime) {
  87571. _this._spritesRenderTime.fetchNewFrame();
  87572. }
  87573. if (_this._captureAnimationsTime) {
  87574. _this._animationsTime.beginMonitoring();
  87575. }
  87576. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87577. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87578. });
  87579. // After render
  87580. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87581. if (_this._captureFrameTime) {
  87582. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87583. _this._frameTime.endMonitoring();
  87584. }
  87585. if (_this._captureRenderTime) {
  87586. _this._renderTime.endMonitoring(false);
  87587. }
  87588. if (_this._captureInterFrameTime) {
  87589. _this._interFrameTime.beginMonitoring();
  87590. }
  87591. });
  87592. }
  87593. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87594. // Properties
  87595. /**
  87596. * Gets the perf counter used for active meshes evaluation time
  87597. */
  87598. get: function () {
  87599. return this._activeMeshesEvaluationTime;
  87600. },
  87601. enumerable: true,
  87602. configurable: true
  87603. });
  87604. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87605. /**
  87606. * Gets the active meshes evaluation time capture status
  87607. */
  87608. get: function () {
  87609. return this._captureActiveMeshesEvaluationTime;
  87610. },
  87611. /**
  87612. * Enable or disable the active meshes evaluation time capture
  87613. */
  87614. set: function (value) {
  87615. var _this = this;
  87616. if (value === this._captureActiveMeshesEvaluationTime) {
  87617. return;
  87618. }
  87619. this._captureActiveMeshesEvaluationTime = value;
  87620. if (value) {
  87621. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87622. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87623. _this._activeMeshesEvaluationTime.beginMonitoring();
  87624. });
  87625. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87626. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87627. _this._activeMeshesEvaluationTime.endMonitoring();
  87628. });
  87629. }
  87630. else {
  87631. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87632. this._onBeforeActiveMeshesEvaluationObserver = null;
  87633. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87634. this._onAfterActiveMeshesEvaluationObserver = null;
  87635. }
  87636. },
  87637. enumerable: true,
  87638. configurable: true
  87639. });
  87640. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87641. /**
  87642. * Gets the perf counter used for render targets render time
  87643. */
  87644. get: function () {
  87645. return this._renderTargetsRenderTime;
  87646. },
  87647. enumerable: true,
  87648. configurable: true
  87649. });
  87650. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87651. /**
  87652. * Gets the render targets render time capture status
  87653. */
  87654. get: function () {
  87655. return this._captureRenderTargetsRenderTime;
  87656. },
  87657. /**
  87658. * Enable or disable the render targets render time capture
  87659. */
  87660. set: function (value) {
  87661. var _this = this;
  87662. if (value === this._captureRenderTargetsRenderTime) {
  87663. return;
  87664. }
  87665. this._captureRenderTargetsRenderTime = value;
  87666. if (value) {
  87667. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87668. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87669. _this._renderTargetsRenderTime.beginMonitoring();
  87670. });
  87671. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87672. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87673. _this._renderTargetsRenderTime.endMonitoring(false);
  87674. });
  87675. }
  87676. else {
  87677. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87678. this._onBeforeRenderTargetsRenderObserver = null;
  87679. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87680. this._onAfterRenderTargetsRenderObserver = null;
  87681. }
  87682. },
  87683. enumerable: true,
  87684. configurable: true
  87685. });
  87686. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87687. /**
  87688. * Gets the perf counter used for particles render time
  87689. */
  87690. get: function () {
  87691. return this._particlesRenderTime;
  87692. },
  87693. enumerable: true,
  87694. configurable: true
  87695. });
  87696. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87697. /**
  87698. * Gets the particles render time capture status
  87699. */
  87700. get: function () {
  87701. return this._captureParticlesRenderTime;
  87702. },
  87703. /**
  87704. * Enable or disable the particles render time capture
  87705. */
  87706. set: function (value) {
  87707. var _this = this;
  87708. if (value === this._captureParticlesRenderTime) {
  87709. return;
  87710. }
  87711. this._captureParticlesRenderTime = value;
  87712. if (value) {
  87713. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87714. BABYLON.Tools.StartPerformanceCounter("Particles");
  87715. _this._particlesRenderTime.beginMonitoring();
  87716. });
  87717. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87718. BABYLON.Tools.EndPerformanceCounter("Particles");
  87719. _this._particlesRenderTime.endMonitoring(false);
  87720. });
  87721. }
  87722. else {
  87723. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87724. this._onBeforeParticlesRenderingObserver = null;
  87725. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87726. this._onAfterParticlesRenderingObserver = null;
  87727. }
  87728. },
  87729. enumerable: true,
  87730. configurable: true
  87731. });
  87732. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87733. /**
  87734. * Gets the perf counter used for sprites render time
  87735. */
  87736. get: function () {
  87737. return this._spritesRenderTime;
  87738. },
  87739. enumerable: true,
  87740. configurable: true
  87741. });
  87742. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87743. /**
  87744. * Gets the sprites render time capture status
  87745. */
  87746. get: function () {
  87747. return this._captureSpritesRenderTime;
  87748. },
  87749. /**
  87750. * Enable or disable the sprites render time capture
  87751. */
  87752. set: function (value) {
  87753. var _this = this;
  87754. if (value === this._captureSpritesRenderTime) {
  87755. return;
  87756. }
  87757. this._captureSpritesRenderTime = value;
  87758. if (value) {
  87759. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87760. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87761. _this._spritesRenderTime.beginMonitoring();
  87762. });
  87763. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87764. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87765. _this._spritesRenderTime.endMonitoring(false);
  87766. });
  87767. }
  87768. else {
  87769. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87770. this._onBeforeSpritesRenderingObserver = null;
  87771. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87772. this._onAfterSpritesRenderingObserver = null;
  87773. }
  87774. },
  87775. enumerable: true,
  87776. configurable: true
  87777. });
  87778. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87779. /**
  87780. * Gets the perf counter used for physics time
  87781. */
  87782. get: function () {
  87783. return this._physicsTime;
  87784. },
  87785. enumerable: true,
  87786. configurable: true
  87787. });
  87788. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87789. /**
  87790. * Gets the physics time capture status
  87791. */
  87792. get: function () {
  87793. return this._capturePhysicsTime;
  87794. },
  87795. /**
  87796. * Enable or disable the physics time capture
  87797. */
  87798. set: function (value) {
  87799. var _this = this;
  87800. if (value === this._capturePhysicsTime) {
  87801. return;
  87802. }
  87803. this._capturePhysicsTime = value;
  87804. if (value) {
  87805. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87806. BABYLON.Tools.StartPerformanceCounter("Physics");
  87807. _this._physicsTime.beginMonitoring();
  87808. });
  87809. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87810. BABYLON.Tools.EndPerformanceCounter("Physics");
  87811. _this._physicsTime.endMonitoring();
  87812. });
  87813. }
  87814. else {
  87815. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87816. this._onBeforePhysicsObserver = null;
  87817. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87818. this._onAfterPhysicsObserver = null;
  87819. }
  87820. },
  87821. enumerable: true,
  87822. configurable: true
  87823. });
  87824. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87825. /**
  87826. * Gets the perf counter used for animations time
  87827. */
  87828. get: function () {
  87829. return this._animationsTime;
  87830. },
  87831. enumerable: true,
  87832. configurable: true
  87833. });
  87834. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87835. /**
  87836. * Gets the animations time capture status
  87837. */
  87838. get: function () {
  87839. return this._captureAnimationsTime;
  87840. },
  87841. /**
  87842. * Enable or disable the animations time capture
  87843. */
  87844. set: function (value) {
  87845. var _this = this;
  87846. if (value === this._captureAnimationsTime) {
  87847. return;
  87848. }
  87849. this._captureAnimationsTime = value;
  87850. if (value) {
  87851. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87852. _this._animationsTime.endMonitoring();
  87853. });
  87854. }
  87855. else {
  87856. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87857. this._onAfterAnimationsObserver = null;
  87858. }
  87859. },
  87860. enumerable: true,
  87861. configurable: true
  87862. });
  87863. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87864. /**
  87865. * Gets the perf counter used for frame time capture
  87866. */
  87867. get: function () {
  87868. return this._frameTime;
  87869. },
  87870. enumerable: true,
  87871. configurable: true
  87872. });
  87873. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87874. /**
  87875. * Gets the frame time capture status
  87876. */
  87877. get: function () {
  87878. return this._captureFrameTime;
  87879. },
  87880. /**
  87881. * Enable or disable the frame time capture
  87882. */
  87883. set: function (value) {
  87884. this._captureFrameTime = value;
  87885. },
  87886. enumerable: true,
  87887. configurable: true
  87888. });
  87889. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87890. /**
  87891. * Gets the perf counter used for inter-frames time capture
  87892. */
  87893. get: function () {
  87894. return this._interFrameTime;
  87895. },
  87896. enumerable: true,
  87897. configurable: true
  87898. });
  87899. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87900. /**
  87901. * Gets the inter-frames time capture status
  87902. */
  87903. get: function () {
  87904. return this._captureInterFrameTime;
  87905. },
  87906. /**
  87907. * Enable or disable the inter-frames time capture
  87908. */
  87909. set: function (value) {
  87910. this._captureInterFrameTime = value;
  87911. },
  87912. enumerable: true,
  87913. configurable: true
  87914. });
  87915. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87916. /**
  87917. * Gets the perf counter used for render time capture
  87918. */
  87919. get: function () {
  87920. return this._renderTime;
  87921. },
  87922. enumerable: true,
  87923. configurable: true
  87924. });
  87925. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87926. /**
  87927. * Gets the render time capture status
  87928. */
  87929. get: function () {
  87930. return this._captureRenderTime;
  87931. },
  87932. /**
  87933. * Enable or disable the render time capture
  87934. */
  87935. set: function (value) {
  87936. var _this = this;
  87937. if (value === this._captureRenderTime) {
  87938. return;
  87939. }
  87940. this._captureRenderTime = value;
  87941. if (value) {
  87942. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87943. _this._renderTime.beginMonitoring();
  87944. BABYLON.Tools.StartPerformanceCounter("Main render");
  87945. });
  87946. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87947. _this._renderTime.endMonitoring(false);
  87948. BABYLON.Tools.EndPerformanceCounter("Main render");
  87949. });
  87950. }
  87951. else {
  87952. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87953. this._onBeforeDrawPhaseObserver = null;
  87954. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87955. this._onAfterDrawPhaseObserver = null;
  87956. }
  87957. },
  87958. enumerable: true,
  87959. configurable: true
  87960. });
  87961. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87962. /**
  87963. * Gets the perf counter used for draw calls
  87964. */
  87965. get: function () {
  87966. return this.scene.getEngine()._drawCalls;
  87967. },
  87968. enumerable: true,
  87969. configurable: true
  87970. });
  87971. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87972. /**
  87973. * Gets the perf counter used for texture collisions
  87974. */
  87975. get: function () {
  87976. return this.scene.getEngine()._textureCollisions;
  87977. },
  87978. enumerable: true,
  87979. configurable: true
  87980. });
  87981. SceneInstrumentation.prototype.dispose = function () {
  87982. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87983. this._onAfterRenderObserver = null;
  87984. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87985. this._onBeforeActiveMeshesEvaluationObserver = null;
  87986. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87987. this._onAfterActiveMeshesEvaluationObserver = null;
  87988. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87989. this._onBeforeRenderTargetsRenderObserver = null;
  87990. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87991. this._onAfterRenderTargetsRenderObserver = null;
  87992. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87993. this._onBeforeAnimationsObserver = null;
  87994. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87995. this._onBeforeParticlesRenderingObserver = null;
  87996. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87997. this._onAfterParticlesRenderingObserver = null;
  87998. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87999. this._onBeforeSpritesRenderingObserver = null;
  88000. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  88001. this._onAfterSpritesRenderingObserver = null;
  88002. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  88003. this._onBeforeDrawPhaseObserver = null;
  88004. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  88005. this._onAfterDrawPhaseObserver = null;
  88006. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  88007. this._onBeforePhysicsObserver = null;
  88008. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88009. this._onAfterPhysicsObserver = null;
  88010. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88011. this._onAfterAnimationsObserver = null;
  88012. this.scene = null;
  88013. };
  88014. return SceneInstrumentation;
  88015. }());
  88016. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88017. })(BABYLON || (BABYLON = {}));
  88018. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88019. var BABYLON;
  88020. (function (BABYLON) {
  88021. var _TimeToken = /** @class */ (function () {
  88022. function _TimeToken() {
  88023. this._timeElapsedQueryEnded = false;
  88024. }
  88025. return _TimeToken;
  88026. }());
  88027. BABYLON._TimeToken = _TimeToken;
  88028. })(BABYLON || (BABYLON = {}));
  88029. //# sourceMappingURL=babylon.timeToken.js.map
  88030. var BABYLON;
  88031. (function (BABYLON) {
  88032. /**
  88033. * Background material defines definition.
  88034. * @ignore Mainly internal Use
  88035. */
  88036. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88037. __extends(BackgroundMaterialDefines, _super);
  88038. /**
  88039. * Constructor of the defines.
  88040. */
  88041. function BackgroundMaterialDefines() {
  88042. var _this = _super.call(this) || this;
  88043. /**
  88044. * True if the diffuse texture is in use.
  88045. */
  88046. _this.DIFFUSE = false;
  88047. /**
  88048. * The direct UV channel to use.
  88049. */
  88050. _this.DIFFUSEDIRECTUV = 0;
  88051. /**
  88052. * True if the diffuse texture is in gamma space.
  88053. */
  88054. _this.GAMMADIFFUSE = false;
  88055. /**
  88056. * True if the diffuse texture has opacity in the alpha channel.
  88057. */
  88058. _this.DIFFUSEHASALPHA = false;
  88059. /**
  88060. * True if you want the material to fade to transparent at grazing angle.
  88061. */
  88062. _this.OPACITYFRESNEL = false;
  88063. /**
  88064. * True if an extra blur needs to be added in the reflection.
  88065. */
  88066. _this.REFLECTIONBLUR = false;
  88067. /**
  88068. * True if you want the material to fade to reflection at grazing angle.
  88069. */
  88070. _this.REFLECTIONFRESNEL = false;
  88071. /**
  88072. * True if you want the material to falloff as far as you move away from the scene center.
  88073. */
  88074. _this.REFLECTIONFALLOFF = false;
  88075. /**
  88076. * False if the current Webgl implementation does not support the texture lod extension.
  88077. */
  88078. _this.TEXTURELODSUPPORT = false;
  88079. /**
  88080. * True to ensure the data are premultiplied.
  88081. */
  88082. _this.PREMULTIPLYALPHA = false;
  88083. /**
  88084. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88085. */
  88086. _this.USERGBCOLOR = false;
  88087. /**
  88088. * True to add noise in order to reduce the banding effect.
  88089. */
  88090. _this.NOISE = false;
  88091. /**
  88092. * is the reflection texture in BGR color scheme?
  88093. * Mainly used to solve a bug in ios10 video tag
  88094. */
  88095. _this.REFLECTIONBGR = false;
  88096. _this.IMAGEPROCESSING = false;
  88097. _this.VIGNETTE = false;
  88098. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88099. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88100. _this.TONEMAPPING = false;
  88101. _this.CONTRAST = false;
  88102. _this.COLORCURVES = false;
  88103. _this.COLORGRADING = false;
  88104. _this.COLORGRADING3D = false;
  88105. _this.SAMPLER3DGREENDEPTH = false;
  88106. _this.SAMPLER3DBGRMAP = false;
  88107. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88108. _this.EXPOSURE = false;
  88109. _this.GRAIN = false;
  88110. // Reflection.
  88111. _this.REFLECTION = false;
  88112. _this.REFLECTIONMAP_3D = false;
  88113. _this.REFLECTIONMAP_SPHERICAL = false;
  88114. _this.REFLECTIONMAP_PLANAR = false;
  88115. _this.REFLECTIONMAP_CUBIC = false;
  88116. _this.REFLECTIONMAP_PROJECTION = false;
  88117. _this.REFLECTIONMAP_SKYBOX = false;
  88118. _this.REFLECTIONMAP_EXPLICIT = false;
  88119. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88120. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88121. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88122. _this.INVERTCUBICMAP = false;
  88123. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88124. _this.LODINREFLECTIONALPHA = false;
  88125. _this.GAMMAREFLECTION = false;
  88126. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88127. // Default BJS.
  88128. _this.MAINUV1 = false;
  88129. _this.MAINUV2 = false;
  88130. _this.UV1 = false;
  88131. _this.UV2 = false;
  88132. _this.CLIPPLANE = false;
  88133. _this.POINTSIZE = false;
  88134. _this.FOG = false;
  88135. _this.NORMAL = false;
  88136. _this.NUM_BONE_INFLUENCERS = 0;
  88137. _this.BonesPerMesh = 0;
  88138. _this.INSTANCES = false;
  88139. _this.SHADOWFLOAT = false;
  88140. _this.rebuild();
  88141. return _this;
  88142. }
  88143. return BackgroundMaterialDefines;
  88144. }(BABYLON.MaterialDefines));
  88145. /**
  88146. * Background material used to create an efficient environement around your scene.
  88147. */
  88148. var BackgroundMaterial = /** @class */ (function (_super) {
  88149. __extends(BackgroundMaterial, _super);
  88150. /**
  88151. * Instantiates a Background Material in the given scene
  88152. * @param name The friendly name of the material
  88153. * @param scene The scene to add the material to
  88154. */
  88155. function BackgroundMaterial(name, scene) {
  88156. var _this = _super.call(this, name, scene) || this;
  88157. /**
  88158. * Key light Color (multiply against the R channel of the environement texture)
  88159. */
  88160. _this.primaryColor = BABYLON.Color3.White();
  88161. /**
  88162. * Key light Level (allowing HDR output of the background)
  88163. */
  88164. _this.primaryLevel = 1;
  88165. /**
  88166. * Secondary light Color (multiply against the G channel of the environement texture)
  88167. */
  88168. _this.secondaryColor = BABYLON.Color3.Gray();
  88169. /**
  88170. * Secondary light Level (allowing HDR output of the background)
  88171. */
  88172. _this.secondaryLevel = 1;
  88173. /**
  88174. * Tertiary light Color (multiply against the B channel of the environement texture)
  88175. */
  88176. _this.tertiaryColor = BABYLON.Color3.Black();
  88177. /**
  88178. * Tertiary light Level (allowing HDR output of the background)
  88179. */
  88180. _this.tertiaryLevel = 1;
  88181. /**
  88182. * Reflection Texture used in the material.
  88183. * Should be author in a specific way for the best result (refer to the documentation).
  88184. */
  88185. _this.reflectionTexture = null;
  88186. /**
  88187. * Reflection Texture level of blur.
  88188. *
  88189. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88190. * texture twice.
  88191. */
  88192. _this.reflectionBlur = 0;
  88193. /**
  88194. * Diffuse Texture used in the material.
  88195. * Should be author in a specific way for the best result (refer to the documentation).
  88196. */
  88197. _this.diffuseTexture = null;
  88198. _this._shadowLights = null;
  88199. /**
  88200. * Specify the list of lights casting shadow on the material.
  88201. * All scene shadow lights will be included if null.
  88202. */
  88203. _this.shadowLights = null;
  88204. /**
  88205. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88206. * soft lighting on the background.
  88207. */
  88208. _this.shadowBlurScale = 1;
  88209. /**
  88210. * Helps adjusting the shadow to a softer level if required.
  88211. * 0 means black shadows and 1 means no shadows.
  88212. */
  88213. _this.shadowLevel = 0;
  88214. /**
  88215. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88216. * It is usually zero but might be interesting to modify according to your setup.
  88217. */
  88218. _this.sceneCenter = BABYLON.Vector3.Zero();
  88219. /**
  88220. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88221. * This helps ensuring a nice transition when the camera goes under the ground.
  88222. */
  88223. _this.opacityFresnel = true;
  88224. /**
  88225. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88226. * This helps adding a mirror texture on the ground.
  88227. */
  88228. _this.reflectionFresnel = false;
  88229. /**
  88230. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88231. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88232. */
  88233. _this.reflectionFalloffDistance = 0.0;
  88234. /**
  88235. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88236. */
  88237. _this.reflectionAmount = 1.0;
  88238. /**
  88239. * This specifies the weight of the reflection at grazing angle.
  88240. */
  88241. _this.reflectionReflectance0 = 0.05;
  88242. /**
  88243. * This specifies the weight of the reflection at a perpendicular point of view.
  88244. */
  88245. _this.reflectionReflectance90 = 0.5;
  88246. /**
  88247. * Helps to directly use the maps channels instead of their level.
  88248. */
  88249. _this.useRGBColor = true;
  88250. /**
  88251. * This helps reducing the banding effect that could occur on the background.
  88252. */
  88253. _this.enableNoise = false;
  88254. _this._fovMultiplier = 1.0;
  88255. /**
  88256. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88257. * @type {boolean}
  88258. */
  88259. _this.useEquirectangularFOV = false;
  88260. _this._maxSimultaneousLights = 4;
  88261. /**
  88262. * Number of Simultaneous lights allowed on the material.
  88263. */
  88264. _this.maxSimultaneousLights = 4;
  88265. /**
  88266. * Keep track of the image processing observer to allow dispose and replace.
  88267. */
  88268. _this._imageProcessingObserver = null;
  88269. /**
  88270. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88271. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88272. */
  88273. _this.switchToBGR = false;
  88274. // Temp values kept as cache in the material.
  88275. _this._renderTargets = new BABYLON.SmartArray(16);
  88276. _this._reflectionControls = BABYLON.Vector4.Zero();
  88277. // Setup the default processing configuration to the scene.
  88278. _this._attachImageProcessingConfiguration(null);
  88279. _this.getRenderTargetTextures = function () {
  88280. _this._renderTargets.reset();
  88281. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88282. _this._renderTargets.push(_this._diffuseTexture);
  88283. }
  88284. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88285. _this._renderTargets.push(_this._reflectionTexture);
  88286. }
  88287. return _this._renderTargets;
  88288. };
  88289. return _this;
  88290. }
  88291. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88292. /**
  88293. * Sets the reflection reflectance fresnel values according to the default standard
  88294. * empirically know to work well :-)
  88295. */
  88296. set: function (value) {
  88297. var reflectionWeight = value;
  88298. if (reflectionWeight < 0.5) {
  88299. reflectionWeight = reflectionWeight * 2.0;
  88300. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88301. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88302. }
  88303. else {
  88304. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88305. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88306. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88307. }
  88308. },
  88309. enumerable: true,
  88310. configurable: true
  88311. });
  88312. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88313. /**
  88314. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88315. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88316. * Recommended to be keep at 1.0 except for special cases.
  88317. */
  88318. get: function () {
  88319. return this._fovMultiplier;
  88320. },
  88321. set: function (value) {
  88322. if (isNaN(value)) {
  88323. value = 1.0;
  88324. }
  88325. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88326. },
  88327. enumerable: true,
  88328. configurable: true
  88329. });
  88330. /**
  88331. * Attaches a new image processing configuration to the PBR Material.
  88332. * @param configuration (if null the scene configuration will be use)
  88333. */
  88334. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88335. var _this = this;
  88336. if (configuration === this._imageProcessingConfiguration) {
  88337. return;
  88338. }
  88339. // Detaches observer.
  88340. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88341. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88342. }
  88343. // Pick the scene configuration if needed.
  88344. if (!configuration) {
  88345. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88346. }
  88347. else {
  88348. this._imageProcessingConfiguration = configuration;
  88349. }
  88350. // Attaches observer.
  88351. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88352. _this._markAllSubMeshesAsImageProcessingDirty();
  88353. });
  88354. };
  88355. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88356. /**
  88357. * Gets the image processing configuration used either in this material.
  88358. */
  88359. get: function () {
  88360. return this._imageProcessingConfiguration;
  88361. },
  88362. /**
  88363. * Sets the Default image processing configuration used either in the this material.
  88364. *
  88365. * If sets to null, the scene one is in use.
  88366. */
  88367. set: function (value) {
  88368. this._attachImageProcessingConfiguration(value);
  88369. // Ensure the effect will be rebuilt.
  88370. this._markAllSubMeshesAsTexturesDirty();
  88371. },
  88372. enumerable: true,
  88373. configurable: true
  88374. });
  88375. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88376. /**
  88377. * Gets wether the color curves effect is enabled.
  88378. */
  88379. get: function () {
  88380. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88381. },
  88382. /**
  88383. * Sets wether the color curves effect is enabled.
  88384. */
  88385. set: function (value) {
  88386. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88387. },
  88388. enumerable: true,
  88389. configurable: true
  88390. });
  88391. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88392. /**
  88393. * Gets wether the color grading effect is enabled.
  88394. */
  88395. get: function () {
  88396. return this.imageProcessingConfiguration.colorGradingEnabled;
  88397. },
  88398. /**
  88399. * Gets wether the color grading effect is enabled.
  88400. */
  88401. set: function (value) {
  88402. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88403. },
  88404. enumerable: true,
  88405. configurable: true
  88406. });
  88407. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88408. /**
  88409. * Gets wether tonemapping is enabled or not.
  88410. */
  88411. get: function () {
  88412. return this._imageProcessingConfiguration.toneMappingEnabled;
  88413. },
  88414. /**
  88415. * Sets wether tonemapping is enabled or not
  88416. */
  88417. set: function (value) {
  88418. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88419. },
  88420. enumerable: true,
  88421. configurable: true
  88422. });
  88423. ;
  88424. ;
  88425. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88426. /**
  88427. * The camera exposure used on this material.
  88428. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88429. * This corresponds to a photographic exposure.
  88430. */
  88431. get: function () {
  88432. return this._imageProcessingConfiguration.exposure;
  88433. },
  88434. /**
  88435. * The camera exposure used on this material.
  88436. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88437. * This corresponds to a photographic exposure.
  88438. */
  88439. set: function (value) {
  88440. this._imageProcessingConfiguration.exposure = value;
  88441. },
  88442. enumerable: true,
  88443. configurable: true
  88444. });
  88445. ;
  88446. ;
  88447. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88448. /**
  88449. * Gets The camera contrast used on this material.
  88450. */
  88451. get: function () {
  88452. return this._imageProcessingConfiguration.contrast;
  88453. },
  88454. /**
  88455. * Sets The camera contrast used on this material.
  88456. */
  88457. set: function (value) {
  88458. this._imageProcessingConfiguration.contrast = value;
  88459. },
  88460. enumerable: true,
  88461. configurable: true
  88462. });
  88463. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88464. /**
  88465. * Gets the Color Grading 2D Lookup Texture.
  88466. */
  88467. get: function () {
  88468. return this._imageProcessingConfiguration.colorGradingTexture;
  88469. },
  88470. /**
  88471. * Sets the Color Grading 2D Lookup Texture.
  88472. */
  88473. set: function (value) {
  88474. this.imageProcessingConfiguration.colorGradingTexture = value;
  88475. },
  88476. enumerable: true,
  88477. configurable: true
  88478. });
  88479. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88480. /**
  88481. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88482. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88483. * 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;
  88484. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88485. */
  88486. get: function () {
  88487. return this.imageProcessingConfiguration.colorCurves;
  88488. },
  88489. /**
  88490. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88491. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88492. * 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;
  88493. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88494. */
  88495. set: function (value) {
  88496. this.imageProcessingConfiguration.colorCurves = value;
  88497. },
  88498. enumerable: true,
  88499. configurable: true
  88500. });
  88501. /**
  88502. * The entire material has been created in order to prevent overdraw.
  88503. * @returns false
  88504. */
  88505. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88506. return true;
  88507. };
  88508. /**
  88509. * The entire material has been created in order to prevent overdraw.
  88510. * @returns true if blending is enable
  88511. */
  88512. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88513. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88514. };
  88515. /**
  88516. * Checks wether the material is ready to be rendered for a given mesh.
  88517. * @param mesh The mesh to render
  88518. * @param subMesh The submesh to check against
  88519. * @param useInstances Specify wether or not the material is used with instances
  88520. * @returns true if all the dependencies are ready (Textures, Effects...)
  88521. */
  88522. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88523. var _this = this;
  88524. if (useInstances === void 0) { useInstances = false; }
  88525. if (subMesh.effect && this.isFrozen) {
  88526. if (this._wasPreviouslyReady) {
  88527. return true;
  88528. }
  88529. }
  88530. if (!subMesh._materialDefines) {
  88531. subMesh._materialDefines = new BackgroundMaterialDefines();
  88532. }
  88533. var scene = this.getScene();
  88534. var defines = subMesh._materialDefines;
  88535. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88536. if (defines._renderId === scene.getRenderId()) {
  88537. return true;
  88538. }
  88539. }
  88540. var engine = scene.getEngine();
  88541. // Lights
  88542. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88543. defines._needNormals = true;
  88544. // Textures
  88545. if (defines._areTexturesDirty) {
  88546. defines._needUVs = false;
  88547. if (scene.texturesEnabled) {
  88548. if (scene.getEngine().getCaps().textureLOD) {
  88549. defines.TEXTURELODSUPPORT = true;
  88550. }
  88551. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88552. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88553. return false;
  88554. }
  88555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88556. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88557. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88558. defines.OPACITYFRESNEL = this._opacityFresnel;
  88559. }
  88560. else {
  88561. defines.DIFFUSE = false;
  88562. defines.DIFFUSEHASALPHA = false;
  88563. defines.GAMMADIFFUSE = false;
  88564. defines.OPACITYFRESNEL = false;
  88565. }
  88566. var reflectionTexture = this._reflectionTexture;
  88567. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88568. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88569. return false;
  88570. }
  88571. defines.REFLECTION = true;
  88572. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88573. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88574. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88575. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88576. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88577. defines.REFLECTIONBGR = this.switchToBGR;
  88578. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88579. defines.INVERTCUBICMAP = true;
  88580. }
  88581. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88582. switch (reflectionTexture.coordinatesMode) {
  88583. case BABYLON.Texture.CUBIC_MODE:
  88584. case BABYLON.Texture.INVCUBIC_MODE:
  88585. defines.REFLECTIONMAP_CUBIC = true;
  88586. break;
  88587. case BABYLON.Texture.EXPLICIT_MODE:
  88588. defines.REFLECTIONMAP_EXPLICIT = true;
  88589. break;
  88590. case BABYLON.Texture.PLANAR_MODE:
  88591. defines.REFLECTIONMAP_PLANAR = true;
  88592. break;
  88593. case BABYLON.Texture.PROJECTION_MODE:
  88594. defines.REFLECTIONMAP_PROJECTION = true;
  88595. break;
  88596. case BABYLON.Texture.SKYBOX_MODE:
  88597. defines.REFLECTIONMAP_SKYBOX = true;
  88598. break;
  88599. case BABYLON.Texture.SPHERICAL_MODE:
  88600. defines.REFLECTIONMAP_SPHERICAL = true;
  88601. break;
  88602. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88603. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88604. break;
  88605. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88606. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88607. break;
  88608. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88609. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88610. break;
  88611. }
  88612. if (this.reflectionFresnel) {
  88613. defines.REFLECTIONFRESNEL = true;
  88614. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88615. this._reflectionControls.x = this.reflectionAmount;
  88616. this._reflectionControls.y = this.reflectionReflectance0;
  88617. this._reflectionControls.z = this.reflectionReflectance90;
  88618. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88619. }
  88620. else {
  88621. defines.REFLECTIONFRESNEL = false;
  88622. defines.REFLECTIONFALLOFF = false;
  88623. }
  88624. }
  88625. else {
  88626. defines.REFLECTION = false;
  88627. defines.REFLECTIONFALLOFF = false;
  88628. defines.REFLECTIONBLUR = false;
  88629. defines.REFLECTIONMAP_3D = false;
  88630. defines.REFLECTIONMAP_SPHERICAL = false;
  88631. defines.REFLECTIONMAP_PLANAR = false;
  88632. defines.REFLECTIONMAP_CUBIC = false;
  88633. defines.REFLECTIONMAP_PROJECTION = false;
  88634. defines.REFLECTIONMAP_SKYBOX = false;
  88635. defines.REFLECTIONMAP_EXPLICIT = false;
  88636. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88637. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88638. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88639. defines.INVERTCUBICMAP = false;
  88640. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88641. defines.LODINREFLECTIONALPHA = false;
  88642. defines.GAMMAREFLECTION = false;
  88643. }
  88644. }
  88645. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88646. defines.USERGBCOLOR = this._useRGBColor;
  88647. defines.NOISE = this._enableNoise;
  88648. }
  88649. if (defines._areImageProcessingDirty) {
  88650. if (!this._imageProcessingConfiguration.isReady()) {
  88651. return false;
  88652. }
  88653. this._imageProcessingConfiguration.prepareDefines(defines);
  88654. }
  88655. // Misc.
  88656. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88657. // Values that need to be evaluated on every frame
  88658. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88659. // Attribs
  88660. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88661. if (mesh) {
  88662. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88663. mesh.createNormals(true);
  88664. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88665. }
  88666. }
  88667. }
  88668. // Get correct effect
  88669. if (defines.isDirty) {
  88670. defines.markAsProcessed();
  88671. scene.resetCachedMaterial();
  88672. // Fallbacks
  88673. var fallbacks = new BABYLON.EffectFallbacks();
  88674. if (defines.FOG) {
  88675. fallbacks.addFallback(0, "FOG");
  88676. }
  88677. if (defines.POINTSIZE) {
  88678. fallbacks.addFallback(1, "POINTSIZE");
  88679. }
  88680. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88681. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88682. fallbacks.addCPUSkinningFallback(0, mesh);
  88683. }
  88684. //Attributes
  88685. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88686. if (defines.NORMAL) {
  88687. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88688. }
  88689. if (defines.UV1) {
  88690. attribs.push(BABYLON.VertexBuffer.UVKind);
  88691. }
  88692. if (defines.UV2) {
  88693. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88694. }
  88695. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88696. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88697. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88698. "vFogInfos", "vFogColor", "pointSize",
  88699. "vClipPlane", "mBones",
  88700. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88701. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88702. "shadowLevel", "alpha",
  88703. "vBackgroundCenter", "vReflectionControl",
  88704. "vDiffuseInfos", "diffuseMatrix",
  88705. ];
  88706. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88707. var uniformBuffers = ["Material", "Scene"];
  88708. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88709. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88710. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88711. uniformsNames: uniforms,
  88712. uniformBuffersNames: uniformBuffers,
  88713. samplers: samplers,
  88714. defines: defines,
  88715. maxSimultaneousLights: this._maxSimultaneousLights
  88716. });
  88717. var onCompiled = function (effect) {
  88718. if (_this.onCompiled) {
  88719. _this.onCompiled(effect);
  88720. }
  88721. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88722. };
  88723. var join = defines.toString();
  88724. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88725. attributes: attribs,
  88726. uniformsNames: uniforms,
  88727. uniformBuffersNames: uniformBuffers,
  88728. samplers: samplers,
  88729. defines: join,
  88730. fallbacks: fallbacks,
  88731. onCompiled: onCompiled,
  88732. onError: this.onError,
  88733. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88734. }, engine), defines);
  88735. this.buildUniformLayout();
  88736. }
  88737. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88738. return false;
  88739. }
  88740. defines._renderId = scene.getRenderId();
  88741. this._wasPreviouslyReady = true;
  88742. return true;
  88743. };
  88744. /**
  88745. * Build the uniform buffer used in the material.
  88746. */
  88747. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88748. // Order is important !
  88749. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88750. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88751. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88752. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88753. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88754. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88755. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88756. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88757. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88758. this._uniformBuffer.addUniform("pointSize", 1);
  88759. this._uniformBuffer.addUniform("shadowLevel", 1);
  88760. this._uniformBuffer.addUniform("alpha", 1);
  88761. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88762. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88763. this._uniformBuffer.create();
  88764. };
  88765. /**
  88766. * Unbind the material.
  88767. */
  88768. BackgroundMaterial.prototype.unbind = function () {
  88769. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88770. this._uniformBuffer.setTexture("diffuseSampler", null);
  88771. }
  88772. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88773. this._uniformBuffer.setTexture("reflectionSampler", null);
  88774. }
  88775. _super.prototype.unbind.call(this);
  88776. };
  88777. /**
  88778. * Bind only the world matrix to the material.
  88779. * @param world The world matrix to bind.
  88780. */
  88781. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88782. this._activeEffect.setMatrix("world", world);
  88783. };
  88784. /**
  88785. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88786. * @param world The world matrix to bind.
  88787. * @param subMesh The submesh to bind for.
  88788. */
  88789. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88790. var scene = this.getScene();
  88791. var defines = subMesh._materialDefines;
  88792. if (!defines) {
  88793. return;
  88794. }
  88795. var effect = subMesh.effect;
  88796. if (!effect) {
  88797. return;
  88798. }
  88799. this._activeEffect = effect;
  88800. // Matrices
  88801. this.bindOnlyWorldMatrix(world);
  88802. // Bones
  88803. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88804. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88805. if (mustRebind) {
  88806. this._uniformBuffer.bindToEffect(effect, "Material");
  88807. this.bindViewProjection(effect);
  88808. var reflectionTexture = this._reflectionTexture;
  88809. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88810. // Texture uniforms
  88811. if (scene.texturesEnabled) {
  88812. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88813. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88814. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88815. }
  88816. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88817. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88818. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88819. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88820. }
  88821. }
  88822. if (this.shadowLevel > 0) {
  88823. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88824. }
  88825. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88826. // Point size
  88827. if (this.pointsCloud) {
  88828. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88829. }
  88830. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88831. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88832. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88833. }
  88834. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88835. // Textures
  88836. if (scene.texturesEnabled) {
  88837. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88838. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88839. }
  88840. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88841. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88842. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88843. }
  88844. else if (!defines.REFLECTIONBLUR) {
  88845. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88846. }
  88847. else {
  88848. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88849. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88850. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88851. }
  88852. if (defines.REFLECTIONFRESNEL) {
  88853. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88854. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88855. }
  88856. }
  88857. }
  88858. // Clip plane
  88859. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88860. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88861. }
  88862. if (mustRebind || !this.isFrozen) {
  88863. if (scene.lightsEnabled) {
  88864. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88865. }
  88866. // View
  88867. this.bindView(effect);
  88868. // Fog
  88869. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88870. // image processing
  88871. this._imageProcessingConfiguration.bind(this._activeEffect);
  88872. }
  88873. this._uniformBuffer.update();
  88874. this._afterBind(mesh);
  88875. };
  88876. /**
  88877. * Dispose the material.
  88878. * @param forceDisposeEffect Force disposal of the associated effect.
  88879. * @param forceDisposeTextures Force disposal of the associated textures.
  88880. */
  88881. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88882. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88883. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88884. if (forceDisposeTextures) {
  88885. if (this.diffuseTexture) {
  88886. this.diffuseTexture.dispose();
  88887. }
  88888. if (this.reflectionTexture) {
  88889. this.reflectionTexture.dispose();
  88890. }
  88891. }
  88892. this._renderTargets.dispose();
  88893. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88894. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88895. }
  88896. _super.prototype.dispose.call(this, forceDisposeEffect);
  88897. };
  88898. /**
  88899. * Clones the material.
  88900. * @param name The cloned name.
  88901. * @returns The cloned material.
  88902. */
  88903. BackgroundMaterial.prototype.clone = function (name) {
  88904. var _this = this;
  88905. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88906. };
  88907. /**
  88908. * Serializes the current material to its JSON representation.
  88909. * @returns The JSON representation.
  88910. */
  88911. BackgroundMaterial.prototype.serialize = function () {
  88912. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88913. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88914. return serializationObject;
  88915. };
  88916. /**
  88917. * Gets the class name of the material
  88918. * @returns "BackgroundMaterial"
  88919. */
  88920. BackgroundMaterial.prototype.getClassName = function () {
  88921. return "BackgroundMaterial";
  88922. };
  88923. /**
  88924. * Parse a JSON input to create back a background material.
  88925. * @param source The JSON data to parse
  88926. * @param scene The scene to create the parsed material in
  88927. * @param rootUrl The root url of the assets the material depends upon
  88928. * @returns the instantiated BackgroundMaterial.
  88929. */
  88930. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88931. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88932. };
  88933. /**
  88934. * Standard reflectance value at parallel view angle.
  88935. */
  88936. BackgroundMaterial.StandardReflectance0 = 0.05;
  88937. /**
  88938. * Standard reflectance value at grazing angle.
  88939. */
  88940. BackgroundMaterial.StandardReflectance90 = 0.5;
  88941. __decorate([
  88942. BABYLON.serializeAsColor3()
  88943. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88944. __decorate([
  88945. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88946. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88947. __decorate([
  88948. BABYLON.serialize()
  88949. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88950. __decorate([
  88951. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88952. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88953. __decorate([
  88954. BABYLON.serializeAsColor3()
  88955. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88956. __decorate([
  88957. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88958. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88959. __decorate([
  88960. BABYLON.serialize()
  88961. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88962. __decorate([
  88963. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88964. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88965. __decorate([
  88966. BABYLON.serializeAsColor3()
  88967. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88968. __decorate([
  88969. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88970. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88971. __decorate([
  88972. BABYLON.serialize()
  88973. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88974. __decorate([
  88975. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88976. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88977. __decorate([
  88978. BABYLON.serializeAsTexture()
  88979. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88980. __decorate([
  88981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88982. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88983. __decorate([
  88984. BABYLON.serialize()
  88985. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88986. __decorate([
  88987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88988. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88989. __decorate([
  88990. BABYLON.serializeAsTexture()
  88991. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88992. __decorate([
  88993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88994. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88995. __decorate([
  88996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88997. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88998. __decorate([
  88999. BABYLON.serialize()
  89000. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  89001. __decorate([
  89002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89003. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  89004. __decorate([
  89005. BABYLON.serialize()
  89006. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  89007. __decorate([
  89008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89009. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  89010. __decorate([
  89011. BABYLON.serializeAsVector3()
  89012. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  89013. __decorate([
  89014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89015. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  89016. __decorate([
  89017. BABYLON.serialize()
  89018. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89019. __decorate([
  89020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89021. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89022. __decorate([
  89023. BABYLON.serialize()
  89024. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89025. __decorate([
  89026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89027. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89028. __decorate([
  89029. BABYLON.serialize()
  89030. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89031. __decorate([
  89032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89033. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89034. __decorate([
  89035. BABYLON.serialize()
  89036. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89037. __decorate([
  89038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89039. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89040. __decorate([
  89041. BABYLON.serialize()
  89042. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89043. __decorate([
  89044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89045. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89046. __decorate([
  89047. BABYLON.serialize()
  89048. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89049. __decorate([
  89050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89051. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89052. __decorate([
  89053. BABYLON.serialize()
  89054. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89055. __decorate([
  89056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89057. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89058. __decorate([
  89059. BABYLON.serialize()
  89060. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89061. __decorate([
  89062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89063. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89064. __decorate([
  89065. BABYLON.serialize()
  89066. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89067. __decorate([
  89068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89069. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89070. __decorate([
  89071. BABYLON.serializeAsImageProcessingConfiguration()
  89072. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89073. return BackgroundMaterial;
  89074. }(BABYLON.PushMaterial));
  89075. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89076. })(BABYLON || (BABYLON = {}));
  89077. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89078. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89079. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89080. s = arguments[i];
  89081. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89082. t[p] = s[p];
  89083. }
  89084. return t;
  89085. };
  89086. var BABYLON;
  89087. (function (BABYLON) {
  89088. /**
  89089. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89090. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89091. * It also helps with the default setup of your imageProcessing configuration.
  89092. */
  89093. var EnvironmentHelper = /** @class */ (function () {
  89094. /**
  89095. * constructor
  89096. * @param options
  89097. * @param scene The scene to add the material to
  89098. */
  89099. function EnvironmentHelper(options, scene) {
  89100. var _this = this;
  89101. this._errorHandler = function (message, exception) {
  89102. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  89103. };
  89104. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89105. this._scene = scene;
  89106. this.onErrorObservable = new BABYLON.Observable();
  89107. this._setupBackground();
  89108. this._setupImageProcessing();
  89109. }
  89110. /**
  89111. * Creates the default options for the helper.
  89112. */
  89113. EnvironmentHelper._getDefaultOptions = function () {
  89114. return {
  89115. createGround: true,
  89116. groundSize: 15,
  89117. groundTexture: this._groundTextureCDNUrl,
  89118. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89119. groundOpacity: 0.9,
  89120. enableGroundShadow: true,
  89121. groundShadowLevel: 0.5,
  89122. enableGroundMirror: false,
  89123. groundMirrorSizeRatio: 0.3,
  89124. groundMirrorBlurKernel: 64,
  89125. groundMirrorAmount: 1,
  89126. groundMirrorFresnelWeight: 1,
  89127. groundMirrorFallOffDistance: 0,
  89128. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89129. groundYBias: 0.00001,
  89130. createSkybox: true,
  89131. skyboxSize: 20,
  89132. skyboxTexture: this._skyboxTextureCDNUrl,
  89133. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89134. backgroundYRotation: 0,
  89135. sizeAuto: true,
  89136. rootPosition: BABYLON.Vector3.Zero(),
  89137. setupImageProcessing: true,
  89138. environmentTexture: this._environmentTextureCDNUrl,
  89139. cameraExposure: 0.8,
  89140. cameraContrast: 1.2,
  89141. toneMappingEnabled: true,
  89142. };
  89143. };
  89144. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89145. /**
  89146. * Gets the root mesh created by the helper.
  89147. */
  89148. get: function () {
  89149. return this._rootMesh;
  89150. },
  89151. enumerable: true,
  89152. configurable: true
  89153. });
  89154. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89155. /**
  89156. * Gets the skybox created by the helper.
  89157. */
  89158. get: function () {
  89159. return this._skybox;
  89160. },
  89161. enumerable: true,
  89162. configurable: true
  89163. });
  89164. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89165. /**
  89166. * Gets the skybox texture created by the helper.
  89167. */
  89168. get: function () {
  89169. return this._skyboxTexture;
  89170. },
  89171. enumerable: true,
  89172. configurable: true
  89173. });
  89174. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89175. /**
  89176. * Gets the skybox material created by the helper.
  89177. */
  89178. get: function () {
  89179. return this._skyboxMaterial;
  89180. },
  89181. enumerable: true,
  89182. configurable: true
  89183. });
  89184. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89185. /**
  89186. * Gets the ground mesh created by the helper.
  89187. */
  89188. get: function () {
  89189. return this._ground;
  89190. },
  89191. enumerable: true,
  89192. configurable: true
  89193. });
  89194. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89195. /**
  89196. * Gets the ground texture created by the helper.
  89197. */
  89198. get: function () {
  89199. return this._groundTexture;
  89200. },
  89201. enumerable: true,
  89202. configurable: true
  89203. });
  89204. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89205. /**
  89206. * Gets the ground mirror created by the helper.
  89207. */
  89208. get: function () {
  89209. return this._groundMirror;
  89210. },
  89211. enumerable: true,
  89212. configurable: true
  89213. });
  89214. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89215. /**
  89216. * Gets the ground mirror render list to helps pushing the meshes
  89217. * you wish in the ground reflection.
  89218. */
  89219. get: function () {
  89220. if (this._groundMirror) {
  89221. return this._groundMirror.renderList;
  89222. }
  89223. return null;
  89224. },
  89225. enumerable: true,
  89226. configurable: true
  89227. });
  89228. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89229. /**
  89230. * Gets the ground material created by the helper.
  89231. */
  89232. get: function () {
  89233. return this._groundMaterial;
  89234. },
  89235. enumerable: true,
  89236. configurable: true
  89237. });
  89238. /**
  89239. * Updates the background according to the new options
  89240. * @param options
  89241. */
  89242. EnvironmentHelper.prototype.updateOptions = function (options) {
  89243. var newOptions = __assign({}, this._options, options);
  89244. if (this._ground && !newOptions.createGround) {
  89245. this._ground.dispose();
  89246. this._ground = null;
  89247. }
  89248. if (this._groundMaterial && !newOptions.createGround) {
  89249. this._groundMaterial.dispose();
  89250. this._groundMaterial = null;
  89251. }
  89252. if (this._groundTexture) {
  89253. if (this._options.groundTexture != newOptions.groundTexture) {
  89254. this._groundTexture.dispose();
  89255. this._groundTexture = null;
  89256. }
  89257. }
  89258. if (this._skybox && !newOptions.createSkybox) {
  89259. this._skybox.dispose();
  89260. this._skybox = null;
  89261. }
  89262. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89263. this._skyboxMaterial.dispose();
  89264. this._skyboxMaterial = null;
  89265. }
  89266. if (this._skyboxTexture) {
  89267. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89268. this._skyboxTexture.dispose();
  89269. this._skyboxTexture = null;
  89270. }
  89271. }
  89272. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89273. this._groundMirror.dispose();
  89274. this._groundMirror = null;
  89275. }
  89276. if (this._scene.environmentTexture) {
  89277. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89278. this._scene.environmentTexture.dispose();
  89279. }
  89280. }
  89281. this._options = newOptions;
  89282. this._setupBackground();
  89283. this._setupImageProcessing();
  89284. };
  89285. /**
  89286. * Sets the primary color of all the available elements.
  89287. * @param color
  89288. */
  89289. EnvironmentHelper.prototype.setMainColor = function (color) {
  89290. if (this.groundMaterial) {
  89291. this.groundMaterial.primaryColor = color;
  89292. }
  89293. if (this.skyboxMaterial) {
  89294. this.skyboxMaterial.primaryColor = color;
  89295. }
  89296. if (this.groundMirror) {
  89297. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89298. }
  89299. };
  89300. /**
  89301. * Setup the image processing according to the specified options.
  89302. */
  89303. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89304. if (this._options.setupImageProcessing) {
  89305. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89306. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89307. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89308. this._setupEnvironmentTexture();
  89309. }
  89310. };
  89311. /**
  89312. * Setup the environment texture according to the specified options.
  89313. */
  89314. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89315. if (this._scene.environmentTexture) {
  89316. return;
  89317. }
  89318. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89319. this._scene.environmentTexture = this._options.environmentTexture;
  89320. return;
  89321. }
  89322. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89323. this._scene.environmentTexture = environmentTexture;
  89324. };
  89325. /**
  89326. * Setup the background according to the specified options.
  89327. */
  89328. EnvironmentHelper.prototype._setupBackground = function () {
  89329. if (!this._rootMesh) {
  89330. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89331. }
  89332. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89333. var sceneSize = this._getSceneSize();
  89334. if (this._options.createGround) {
  89335. this._setupGround(sceneSize);
  89336. this._setupGroundMaterial();
  89337. this._setupGroundDiffuseTexture();
  89338. if (this._options.enableGroundMirror) {
  89339. this._setupGroundMirrorTexture(sceneSize);
  89340. }
  89341. this._setupMirrorInGroundMaterial();
  89342. }
  89343. if (this._options.createSkybox) {
  89344. this._setupSkybox(sceneSize);
  89345. this._setupSkyboxMaterial();
  89346. this._setupSkyboxReflectionTexture();
  89347. }
  89348. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89349. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89350. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89351. };
  89352. /**
  89353. * Get the scene sizes according to the setup.
  89354. */
  89355. EnvironmentHelper.prototype._getSceneSize = function () {
  89356. var _this = this;
  89357. var groundSize = this._options.groundSize;
  89358. var skyboxSize = this._options.skyboxSize;
  89359. var rootPosition = this._options.rootPosition;
  89360. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89361. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89362. }
  89363. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89364. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89365. });
  89366. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89367. if (this._options.sizeAuto) {
  89368. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89369. this._scene.activeCamera.upperRadiusLimit) {
  89370. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89371. skyboxSize = groundSize;
  89372. }
  89373. var sceneDiagonalLenght = sceneDiagonal.length();
  89374. if (sceneDiagonalLenght > groundSize) {
  89375. groundSize = sceneDiagonalLenght * 2;
  89376. skyboxSize = groundSize;
  89377. }
  89378. // 10 % bigger.
  89379. groundSize *= 1.1;
  89380. skyboxSize *= 1.5;
  89381. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89382. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89383. }
  89384. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89385. };
  89386. /**
  89387. * Setup the ground according to the specified options.
  89388. */
  89389. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89390. var _this = this;
  89391. if (!this._ground) {
  89392. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89393. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89394. this._ground.parent = this._rootMesh;
  89395. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89396. }
  89397. this._ground.receiveShadows = this._options.enableGroundShadow;
  89398. };
  89399. /**
  89400. * Setup the ground material according to the specified options.
  89401. */
  89402. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89403. if (!this._groundMaterial) {
  89404. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89405. }
  89406. this._groundMaterial.alpha = this._options.groundOpacity;
  89407. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89408. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89409. this._groundMaterial.primaryLevel = 1;
  89410. this._groundMaterial.primaryColor = this._options.groundColor;
  89411. this._groundMaterial.secondaryLevel = 0;
  89412. this._groundMaterial.tertiaryLevel = 0;
  89413. this._groundMaterial.useRGBColor = false;
  89414. this._groundMaterial.enableNoise = true;
  89415. if (this._ground) {
  89416. this._ground.material = this._groundMaterial;
  89417. }
  89418. };
  89419. /**
  89420. * Setup the ground diffuse texture according to the specified options.
  89421. */
  89422. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89423. if (!this._groundMaterial) {
  89424. return;
  89425. }
  89426. if (this._groundTexture) {
  89427. return;
  89428. }
  89429. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89430. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89431. return;
  89432. }
  89433. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89434. diffuseTexture.gammaSpace = false;
  89435. diffuseTexture.hasAlpha = true;
  89436. this._groundMaterial.diffuseTexture = diffuseTexture;
  89437. };
  89438. /**
  89439. * Setup the ground mirror texture according to the specified options.
  89440. */
  89441. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89442. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89443. if (!this._groundMirror) {
  89444. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89445. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89446. this._groundMirror.anisotropicFilteringLevel = 1;
  89447. this._groundMirror.wrapU = wrapping;
  89448. this._groundMirror.wrapV = wrapping;
  89449. this._groundMirror.gammaSpace = false;
  89450. if (this._groundMirror.renderList) {
  89451. for (var i = 0; i < this._scene.meshes.length; i++) {
  89452. var mesh = this._scene.meshes[i];
  89453. if (mesh !== this._ground &&
  89454. mesh !== this._skybox &&
  89455. mesh !== this._rootMesh) {
  89456. this._groundMirror.renderList.push(mesh);
  89457. }
  89458. }
  89459. }
  89460. }
  89461. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89462. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89463. };
  89464. /**
  89465. * Setup the ground to receive the mirror texture.
  89466. */
  89467. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89468. if (this._groundMaterial) {
  89469. this._groundMaterial.reflectionTexture = this._groundMirror;
  89470. this._groundMaterial.reflectionFresnel = true;
  89471. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89472. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89473. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89474. }
  89475. };
  89476. /**
  89477. * Setup the skybox according to the specified options.
  89478. */
  89479. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89480. var _this = this;
  89481. if (!this._skybox) {
  89482. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89483. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89484. }
  89485. this._skybox.parent = this._rootMesh;
  89486. };
  89487. /**
  89488. * Setup the skybox material according to the specified options.
  89489. */
  89490. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89491. if (!this._skybox) {
  89492. return;
  89493. }
  89494. if (!this._skyboxMaterial) {
  89495. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89496. }
  89497. this._skyboxMaterial.useRGBColor = false;
  89498. this._skyboxMaterial.primaryLevel = 1;
  89499. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89500. this._skyboxMaterial.secondaryLevel = 0;
  89501. this._skyboxMaterial.tertiaryLevel = 0;
  89502. this._skyboxMaterial.enableNoise = true;
  89503. this._skybox.material = this._skyboxMaterial;
  89504. };
  89505. /**
  89506. * Setup the skybox reflection texture according to the specified options.
  89507. */
  89508. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89509. if (!this._skyboxMaterial) {
  89510. return;
  89511. }
  89512. if (this._skyboxTexture) {
  89513. return;
  89514. }
  89515. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89516. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89517. return;
  89518. }
  89519. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  89520. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89521. this._skyboxTexture.gammaSpace = false;
  89522. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89523. };
  89524. /**
  89525. * Dispose all the elements created by the Helper.
  89526. */
  89527. EnvironmentHelper.prototype.dispose = function () {
  89528. if (this._groundMaterial) {
  89529. this._groundMaterial.dispose(true, true);
  89530. }
  89531. if (this._skyboxMaterial) {
  89532. this._skyboxMaterial.dispose(true, true);
  89533. }
  89534. this._rootMesh.dispose(false);
  89535. };
  89536. /**
  89537. * Default ground texture URL.
  89538. */
  89539. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89540. /**
  89541. * Default skybox texture URL.
  89542. */
  89543. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89544. /**
  89545. * Default environment texture URL.
  89546. */
  89547. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89548. return EnvironmentHelper;
  89549. }());
  89550. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89551. })(BABYLON || (BABYLON = {}));
  89552. //# sourceMappingURL=babylon.environmentHelper.js.map
  89553. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","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}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  89554. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  89555. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89556. var BABYLON;
  89557. (function (BABYLON) {
  89558. var GridMaterialDefines = /** @class */ (function (_super) {
  89559. __extends(GridMaterialDefines, _super);
  89560. function GridMaterialDefines() {
  89561. var _this = _super.call(this) || this;
  89562. _this.TRANSPARENT = false;
  89563. _this.FOG = false;
  89564. _this.PREMULTIPLYALPHA = false;
  89565. _this.rebuild();
  89566. return _this;
  89567. }
  89568. return GridMaterialDefines;
  89569. }(BABYLON.MaterialDefines));
  89570. /**
  89571. * The grid materials allows you to wrap any shape with a grid.
  89572. * Colors are customizable.
  89573. */
  89574. var GridMaterial = /** @class */ (function (_super) {
  89575. __extends(GridMaterial, _super);
  89576. /**
  89577. * constructor
  89578. * @param name The name given to the material in order to identify it afterwards.
  89579. * @param scene The scene the material is used in.
  89580. */
  89581. function GridMaterial(name, scene) {
  89582. var _this = _super.call(this, name, scene) || this;
  89583. /**
  89584. * Main color of the grid (e.g. between lines)
  89585. */
  89586. _this.mainColor = BABYLON.Color3.Black();
  89587. /**
  89588. * Color of the grid lines.
  89589. */
  89590. _this.lineColor = BABYLON.Color3.Teal();
  89591. /**
  89592. * The scale of the grid compared to unit.
  89593. */
  89594. _this.gridRatio = 1.0;
  89595. /**
  89596. * Allows setting an offset for the grid lines.
  89597. */
  89598. _this.gridOffset = BABYLON.Vector3.Zero();
  89599. /**
  89600. * The frequency of thicker lines.
  89601. */
  89602. _this.majorUnitFrequency = 10;
  89603. /**
  89604. * The visibility of minor units in the grid.
  89605. */
  89606. _this.minorUnitVisibility = 0.33;
  89607. /**
  89608. * The grid opacity outside of the lines.
  89609. */
  89610. _this.opacity = 1.0;
  89611. /**
  89612. * Determine RBG output is premultiplied by alpha value.
  89613. */
  89614. _this.preMultiplyAlpha = false;
  89615. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89616. return _this;
  89617. }
  89618. /**
  89619. * Returns wehter or not the grid requires alpha blending.
  89620. */
  89621. GridMaterial.prototype.needAlphaBlending = function () {
  89622. return this.opacity < 1.0;
  89623. };
  89624. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89625. return this.needAlphaBlending();
  89626. };
  89627. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89628. if (this.isFrozen) {
  89629. if (this._wasPreviouslyReady && subMesh.effect) {
  89630. return true;
  89631. }
  89632. }
  89633. if (!subMesh._materialDefines) {
  89634. subMesh._materialDefines = new GridMaterialDefines();
  89635. }
  89636. var defines = subMesh._materialDefines;
  89637. var scene = this.getScene();
  89638. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89639. if (this._renderId === scene.getRenderId()) {
  89640. return true;
  89641. }
  89642. }
  89643. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89644. defines.TRANSPARENT = !defines.TRANSPARENT;
  89645. defines.markAsUnprocessed();
  89646. }
  89647. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89648. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89649. defines.markAsUnprocessed();
  89650. }
  89651. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89652. // Get correct effect
  89653. if (defines.isDirty) {
  89654. defines.markAsProcessed();
  89655. scene.resetCachedMaterial();
  89656. // Attributes
  89657. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89658. // Defines
  89659. var join = defines.toString();
  89660. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89661. }
  89662. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89663. return false;
  89664. }
  89665. this._renderId = scene.getRenderId();
  89666. this._wasPreviouslyReady = true;
  89667. return true;
  89668. };
  89669. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89670. var scene = this.getScene();
  89671. var defines = subMesh._materialDefines;
  89672. if (!defines) {
  89673. return;
  89674. }
  89675. var effect = subMesh.effect;
  89676. if (!effect) {
  89677. return;
  89678. }
  89679. this._activeEffect = effect;
  89680. // Matrices
  89681. this.bindOnlyWorldMatrix(world);
  89682. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89683. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89684. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89685. // Uniforms
  89686. if (this._mustRebind(scene, effect)) {
  89687. this._activeEffect.setColor3("mainColor", this.mainColor);
  89688. this._activeEffect.setColor3("lineColor", this.lineColor);
  89689. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89690. this._gridControl.x = this.gridRatio;
  89691. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89692. this._gridControl.z = this.minorUnitVisibility;
  89693. this._gridControl.w = this.opacity;
  89694. this._activeEffect.setVector4("gridControl", this._gridControl);
  89695. }
  89696. // Fog
  89697. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89698. this._afterBind(mesh, this._activeEffect);
  89699. };
  89700. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89701. _super.prototype.dispose.call(this, forceDisposeEffect);
  89702. };
  89703. GridMaterial.prototype.clone = function (name) {
  89704. var _this = this;
  89705. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89706. };
  89707. GridMaterial.prototype.serialize = function () {
  89708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89709. serializationObject.customType = "BABYLON.GridMaterial";
  89710. return serializationObject;
  89711. };
  89712. GridMaterial.prototype.getClassName = function () {
  89713. return "GridMaterial";
  89714. };
  89715. GridMaterial.Parse = function (source, scene, rootUrl) {
  89716. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89717. };
  89718. __decorate([
  89719. BABYLON.serializeAsColor3()
  89720. ], GridMaterial.prototype, "mainColor", void 0);
  89721. __decorate([
  89722. BABYLON.serializeAsColor3()
  89723. ], GridMaterial.prototype, "lineColor", void 0);
  89724. __decorate([
  89725. BABYLON.serialize()
  89726. ], GridMaterial.prototype, "gridRatio", void 0);
  89727. __decorate([
  89728. BABYLON.serializeAsColor3()
  89729. ], GridMaterial.prototype, "gridOffset", void 0);
  89730. __decorate([
  89731. BABYLON.serialize()
  89732. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89733. __decorate([
  89734. BABYLON.serialize()
  89735. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89736. __decorate([
  89737. BABYLON.serialize()
  89738. ], GridMaterial.prototype, "opacity", void 0);
  89739. __decorate([
  89740. BABYLON.serialize()
  89741. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89742. return GridMaterial;
  89743. }(BABYLON.PushMaterial));
  89744. BABYLON.GridMaterial = GridMaterial;
  89745. })(BABYLON || (BABYLON = {}));
  89746. //# sourceMappingURL=babylon.gridmaterial.js.map
  89747. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  89748. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  89749. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89750. var BABYLON;
  89751. (function (BABYLON) {
  89752. var GLTFLoaderCoordinateSystemMode;
  89753. (function (GLTFLoaderCoordinateSystemMode) {
  89754. /**
  89755. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89756. */
  89757. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89758. /**
  89759. * Sets the useRightHandedSystem flag on the scene.
  89760. */
  89761. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89762. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89763. var GLTFLoaderAnimationStartMode;
  89764. (function (GLTFLoaderAnimationStartMode) {
  89765. /**
  89766. * No animation will start.
  89767. */
  89768. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89769. /**
  89770. * The first animation will start.
  89771. */
  89772. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89773. /**
  89774. * All animations will start.
  89775. */
  89776. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89777. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89778. var GLTFLoaderState;
  89779. (function (GLTFLoaderState) {
  89780. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89781. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89782. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89783. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89784. var GLTFFileLoader = /** @class */ (function () {
  89785. function GLTFFileLoader() {
  89786. // #region Common options
  89787. /**
  89788. * Raised when the asset has been parsed.
  89789. * The data.json property stores the glTF JSON.
  89790. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89791. */
  89792. this.onParsedObservable = new BABYLON.Observable();
  89793. // #endregion
  89794. // #region V2 options
  89795. /**
  89796. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89797. */
  89798. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89799. /**
  89800. * The animation start mode (NONE, FIRST, ALL).
  89801. */
  89802. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  89803. /**
  89804. * Set to true to compile materials before raising the success callback.
  89805. */
  89806. this.compileMaterials = false;
  89807. /**
  89808. * Set to true to also compile materials with clip planes.
  89809. */
  89810. this.useClipPlane = false;
  89811. /**
  89812. * Set to true to compile shadow generators before raising the success callback.
  89813. */
  89814. this.compileShadowGenerators = false;
  89815. /**
  89816. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  89817. */
  89818. this.onMeshLoadedObservable = new BABYLON.Observable();
  89819. /**
  89820. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  89821. */
  89822. this.onTextureLoadedObservable = new BABYLON.Observable();
  89823. /**
  89824. * Raised when the loader creates a material after parsing the glTF properties of the material.
  89825. */
  89826. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89827. /**
  89828. * Raised when the loader creates an animation group after parsing the glTF properties of the material.
  89829. */
  89830. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  89831. /**
  89832. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  89833. * For assets with LODs, raised when all of the LODs are complete.
  89834. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  89835. */
  89836. this.onCompleteObservable = new BABYLON.Observable();
  89837. /**
  89838. * Raised when the loader is disposed.
  89839. */
  89840. this.onDisposeObservable = new BABYLON.Observable();
  89841. /**
  89842. * Raised after a loader extension is created.
  89843. * Set additional options for a loader extension in this event.
  89844. */
  89845. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89846. // #endregion
  89847. this._loader = null;
  89848. this.name = "gltf";
  89849. this.extensions = {
  89850. ".gltf": { isBinary: false },
  89851. ".glb": { isBinary: true }
  89852. };
  89853. }
  89854. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  89855. set: function (callback) {
  89856. if (this._onParsedObserver) {
  89857. this.onParsedObservable.remove(this._onParsedObserver);
  89858. }
  89859. this._onParsedObserver = this.onParsedObservable.add(callback);
  89860. },
  89861. enumerable: true,
  89862. configurable: true
  89863. });
  89864. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  89865. set: function (callback) {
  89866. if (this._onMeshLoadedObserver) {
  89867. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  89868. }
  89869. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  89870. },
  89871. enumerable: true,
  89872. configurable: true
  89873. });
  89874. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  89875. set: function (callback) {
  89876. if (this._onTextureLoadedObserver) {
  89877. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  89878. }
  89879. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  89880. },
  89881. enumerable: true,
  89882. configurable: true
  89883. });
  89884. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  89885. set: function (callback) {
  89886. if (this._onMaterialLoadedObserver) {
  89887. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  89888. }
  89889. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  89890. },
  89891. enumerable: true,
  89892. configurable: true
  89893. });
  89894. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  89895. set: function (callback) {
  89896. if (this._onAnimationGroupLoadedObserver) {
  89897. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  89898. }
  89899. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  89900. },
  89901. enumerable: true,
  89902. configurable: true
  89903. });
  89904. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  89905. set: function (callback) {
  89906. if (this._onCompleteObserver) {
  89907. this.onCompleteObservable.remove(this._onCompleteObserver);
  89908. }
  89909. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  89910. },
  89911. enumerable: true,
  89912. configurable: true
  89913. });
  89914. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  89915. set: function (callback) {
  89916. if (this._onDisposeObserver) {
  89917. this.onDisposeObservable.remove(this._onDisposeObserver);
  89918. }
  89919. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89920. },
  89921. enumerable: true,
  89922. configurable: true
  89923. });
  89924. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  89925. set: function (callback) {
  89926. if (this._onExtensionLoadedObserver) {
  89927. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  89928. }
  89929. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  89930. },
  89931. enumerable: true,
  89932. configurable: true
  89933. });
  89934. /**
  89935. * Gets a promise that resolves when the asset to be completely loaded.
  89936. * @returns A promise that resolves when the asset is completely loaded.
  89937. */
  89938. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  89939. var _this = this;
  89940. return new Promise(function (resolve) {
  89941. _this.onCompleteObservable.add(function () {
  89942. resolve();
  89943. }, undefined, undefined, undefined, true);
  89944. });
  89945. };
  89946. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  89947. /**
  89948. * The loader state or null if not active.
  89949. */
  89950. get: function () {
  89951. return this._loader ? this._loader.state : null;
  89952. },
  89953. enumerable: true,
  89954. configurable: true
  89955. });
  89956. /**
  89957. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  89958. */
  89959. GLTFFileLoader.prototype.dispose = function () {
  89960. if (this._loader) {
  89961. this._loader.dispose();
  89962. this._loader = null;
  89963. }
  89964. this.onMeshLoadedObservable.clear();
  89965. this.onTextureLoadedObservable.clear();
  89966. this.onMaterialLoadedObservable.clear();
  89967. this.onDisposeObservable.notifyObservers(this);
  89968. this.onDisposeObservable.clear();
  89969. };
  89970. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89971. var _this = this;
  89972. return Promise.resolve().then(function () {
  89973. var loaderData = _this._parse(data);
  89974. _this._loader = _this._getLoader(loaderData);
  89975. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  89976. });
  89977. };
  89978. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89979. var _this = this;
  89980. return Promise.resolve().then(function () {
  89981. var loaderData = _this._parse(data);
  89982. _this._loader = _this._getLoader(loaderData);
  89983. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  89984. });
  89985. };
  89986. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  89987. var _this = this;
  89988. return Promise.resolve().then(function () {
  89989. var loaderData = _this._parse(data);
  89990. _this._loader = _this._getLoader(loaderData);
  89991. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  89992. var container = new BABYLON.AssetContainer(scene);
  89993. Array.prototype.push.apply(container.meshes, result.meshes);
  89994. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  89995. Array.prototype.push.apply(container.skeletons, result.skeletons);
  89996. container.removeAllFromScene();
  89997. return container;
  89998. });
  89999. });
  90000. };
  90001. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  90002. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  90003. };
  90004. GLTFFileLoader.prototype.createPlugin = function () {
  90005. return new GLTFFileLoader();
  90006. };
  90007. GLTFFileLoader.prototype._parse = function (data) {
  90008. var parsedData;
  90009. if (data instanceof ArrayBuffer) {
  90010. parsedData = GLTFFileLoader._parseBinary(data);
  90011. }
  90012. else {
  90013. parsedData = {
  90014. json: JSON.parse(data),
  90015. bin: null
  90016. };
  90017. }
  90018. this.onParsedObservable.notifyObservers(parsedData);
  90019. this.onParsedObservable.clear();
  90020. return parsedData;
  90021. };
  90022. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  90023. var _this = this;
  90024. var loaderVersion = { major: 2, minor: 0 };
  90025. var asset = loaderData.json.asset || {};
  90026. var version = GLTFFileLoader._parseVersion(asset.version);
  90027. if (!version) {
  90028. throw new Error("Invalid version: " + asset.version);
  90029. }
  90030. if (asset.minVersion !== undefined) {
  90031. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  90032. if (!minVersion) {
  90033. throw new Error("Invalid minimum version: " + asset.minVersion);
  90034. }
  90035. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  90036. throw new Error("Incompatible minimum version: " + asset.minVersion);
  90037. }
  90038. }
  90039. var createLoaders = {
  90040. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  90041. 2: GLTFFileLoader.CreateGLTFLoaderV2
  90042. };
  90043. var createLoader = createLoaders[version.major];
  90044. if (!createLoader) {
  90045. throw new Error("Unsupported version: " + asset.version);
  90046. }
  90047. var loader = createLoader();
  90048. loader.coordinateSystemMode = this.coordinateSystemMode;
  90049. loader.animationStartMode = this.animationStartMode;
  90050. loader.compileMaterials = this.compileMaterials;
  90051. loader.useClipPlane = this.useClipPlane;
  90052. loader.compileShadowGenerators = this.compileShadowGenerators;
  90053. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  90054. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  90055. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  90056. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  90057. loader.onCompleteObservable.add(function () {
  90058. _this.onMeshLoadedObservable.clear();
  90059. _this.onTextureLoadedObservable.clear();
  90060. _this.onMaterialLoadedObservable.clear();
  90061. _this.onCompleteObservable.notifyObservers(_this);
  90062. _this.onCompleteObservable.clear();
  90063. });
  90064. return loader;
  90065. };
  90066. GLTFFileLoader._parseBinary = function (data) {
  90067. var Binary = {
  90068. Magic: 0x46546C67
  90069. };
  90070. var binaryReader = new BinaryReader(data);
  90071. var magic = binaryReader.readUint32();
  90072. if (magic !== Binary.Magic) {
  90073. throw new Error("Unexpected magic: " + magic);
  90074. }
  90075. var version = binaryReader.readUint32();
  90076. switch (version) {
  90077. case 1: return GLTFFileLoader._parseV1(binaryReader);
  90078. case 2: return GLTFFileLoader._parseV2(binaryReader);
  90079. }
  90080. throw new Error("Unsupported version: " + version);
  90081. };
  90082. GLTFFileLoader._parseV1 = function (binaryReader) {
  90083. var ContentFormat = {
  90084. JSON: 0
  90085. };
  90086. var length = binaryReader.readUint32();
  90087. if (length != binaryReader.getLength()) {
  90088. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90089. }
  90090. var contentLength = binaryReader.readUint32();
  90091. var contentFormat = binaryReader.readUint32();
  90092. var content;
  90093. switch (contentFormat) {
  90094. case ContentFormat.JSON: {
  90095. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  90096. break;
  90097. }
  90098. default: {
  90099. throw new Error("Unexpected content format: " + contentFormat);
  90100. }
  90101. }
  90102. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  90103. var body = binaryReader.readUint8Array(bytesRemaining);
  90104. return {
  90105. json: content,
  90106. bin: body
  90107. };
  90108. };
  90109. GLTFFileLoader._parseV2 = function (binaryReader) {
  90110. var ChunkFormat = {
  90111. JSON: 0x4E4F534A,
  90112. BIN: 0x004E4942
  90113. };
  90114. var length = binaryReader.readUint32();
  90115. if (length !== binaryReader.getLength()) {
  90116. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  90117. }
  90118. // JSON chunk
  90119. var chunkLength = binaryReader.readUint32();
  90120. var chunkFormat = binaryReader.readUint32();
  90121. if (chunkFormat !== ChunkFormat.JSON) {
  90122. throw new Error("First chunk format is not JSON");
  90123. }
  90124. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  90125. // Look for BIN chunk
  90126. var bin = null;
  90127. while (binaryReader.getPosition() < binaryReader.getLength()) {
  90128. var chunkLength_1 = binaryReader.readUint32();
  90129. var chunkFormat_1 = binaryReader.readUint32();
  90130. switch (chunkFormat_1) {
  90131. case ChunkFormat.JSON: {
  90132. throw new Error("Unexpected JSON chunk");
  90133. }
  90134. case ChunkFormat.BIN: {
  90135. bin = binaryReader.readUint8Array(chunkLength_1);
  90136. break;
  90137. }
  90138. default: {
  90139. // ignore unrecognized chunkFormat
  90140. binaryReader.skipBytes(chunkLength_1);
  90141. break;
  90142. }
  90143. }
  90144. }
  90145. return {
  90146. json: json,
  90147. bin: bin
  90148. };
  90149. };
  90150. GLTFFileLoader._parseVersion = function (version) {
  90151. if (version === "1.0" || version === "1.0.1") {
  90152. return {
  90153. major: 1,
  90154. minor: 0
  90155. };
  90156. }
  90157. var match = (version + "").match(/^(\d+)\.(\d+)/);
  90158. if (!match) {
  90159. return null;
  90160. }
  90161. return {
  90162. major: parseInt(match[1]),
  90163. minor: parseInt(match[2])
  90164. };
  90165. };
  90166. GLTFFileLoader._compareVersion = function (a, b) {
  90167. if (a.major > b.major)
  90168. return 1;
  90169. if (a.major < b.major)
  90170. return -1;
  90171. if (a.minor > b.minor)
  90172. return 1;
  90173. if (a.minor < b.minor)
  90174. return -1;
  90175. return 0;
  90176. };
  90177. GLTFFileLoader._decodeBufferToText = function (buffer) {
  90178. var result = "";
  90179. var length = buffer.byteLength;
  90180. for (var i = 0; i < length; i++) {
  90181. result += String.fromCharCode(buffer[i]);
  90182. }
  90183. return result;
  90184. };
  90185. // #endregion
  90186. // #region V1 options
  90187. GLTFFileLoader.IncrementalLoading = true;
  90188. GLTFFileLoader.HomogeneousCoordinates = false;
  90189. return GLTFFileLoader;
  90190. }());
  90191. BABYLON.GLTFFileLoader = GLTFFileLoader;
  90192. var BinaryReader = /** @class */ (function () {
  90193. function BinaryReader(arrayBuffer) {
  90194. this._arrayBuffer = arrayBuffer;
  90195. this._dataView = new DataView(arrayBuffer);
  90196. this._byteOffset = 0;
  90197. }
  90198. BinaryReader.prototype.getPosition = function () {
  90199. return this._byteOffset;
  90200. };
  90201. BinaryReader.prototype.getLength = function () {
  90202. return this._arrayBuffer.byteLength;
  90203. };
  90204. BinaryReader.prototype.readUint32 = function () {
  90205. var value = this._dataView.getUint32(this._byteOffset, true);
  90206. this._byteOffset += 4;
  90207. return value;
  90208. };
  90209. BinaryReader.prototype.readUint8Array = function (length) {
  90210. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  90211. this._byteOffset += length;
  90212. return value;
  90213. };
  90214. BinaryReader.prototype.skipBytes = function (length) {
  90215. this._byteOffset += length;
  90216. };
  90217. return BinaryReader;
  90218. }());
  90219. if (BABYLON.SceneLoader) {
  90220. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  90221. }
  90222. })(BABYLON || (BABYLON = {}));
  90223. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  90224. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90225. var BABYLON;
  90226. (function (BABYLON) {
  90227. var GLTF1;
  90228. (function (GLTF1) {
  90229. /**
  90230. * Enums
  90231. */
  90232. var EComponentType;
  90233. (function (EComponentType) {
  90234. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  90235. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90236. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  90237. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90238. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  90239. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  90240. var EShaderType;
  90241. (function (EShaderType) {
  90242. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  90243. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  90244. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  90245. var EParameterType;
  90246. (function (EParameterType) {
  90247. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  90248. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  90249. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  90250. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  90251. EParameterType[EParameterType["INT"] = 5124] = "INT";
  90252. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  90253. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  90254. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  90255. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  90256. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  90257. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  90258. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  90259. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  90260. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  90261. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  90262. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  90263. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  90264. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  90265. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  90266. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  90267. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  90268. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  90269. var ETextureWrapMode;
  90270. (function (ETextureWrapMode) {
  90271. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90272. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90273. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90274. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90275. var ETextureFilterType;
  90276. (function (ETextureFilterType) {
  90277. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90278. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90279. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90280. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90281. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90282. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90283. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90284. var ETextureFormat;
  90285. (function (ETextureFormat) {
  90286. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90287. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90288. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90289. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90290. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90291. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90292. var ECullingType;
  90293. (function (ECullingType) {
  90294. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90295. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90296. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90297. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90298. var EBlendingFunction;
  90299. (function (EBlendingFunction) {
  90300. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90301. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90302. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90303. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90304. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90305. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90306. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90307. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90308. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90309. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90310. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90311. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90312. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90313. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90314. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90315. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90316. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90317. })(BABYLON || (BABYLON = {}));
  90318. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90319. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90320. var BABYLON;
  90321. (function (BABYLON) {
  90322. var GLTF1;
  90323. (function (GLTF1) {
  90324. /**
  90325. * Tokenizer. Used for shaders compatibility
  90326. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90327. */
  90328. var ETokenType;
  90329. (function (ETokenType) {
  90330. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90331. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90332. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90333. })(ETokenType || (ETokenType = {}));
  90334. var Tokenizer = /** @class */ (function () {
  90335. function Tokenizer(toParse) {
  90336. this._pos = 0;
  90337. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90338. this._toParse = toParse;
  90339. this._maxPos = toParse.length;
  90340. }
  90341. Tokenizer.prototype.getNextToken = function () {
  90342. if (this.isEnd())
  90343. return ETokenType.END_OF_INPUT;
  90344. this.currentString = this.read();
  90345. this.currentToken = ETokenType.UNKNOWN;
  90346. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90347. this.currentToken = ETokenType.IDENTIFIER;
  90348. this.currentIdentifier = this.currentString;
  90349. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90350. this.currentIdentifier += this.currentString;
  90351. this.forward();
  90352. }
  90353. }
  90354. return this.currentToken;
  90355. };
  90356. Tokenizer.prototype.peek = function () {
  90357. return this._toParse[this._pos];
  90358. };
  90359. Tokenizer.prototype.read = function () {
  90360. return this._toParse[this._pos++];
  90361. };
  90362. Tokenizer.prototype.forward = function () {
  90363. this._pos++;
  90364. };
  90365. Tokenizer.prototype.isEnd = function () {
  90366. return this._pos >= this._maxPos;
  90367. };
  90368. return Tokenizer;
  90369. }());
  90370. /**
  90371. * Values
  90372. */
  90373. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90374. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90375. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90376. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90377. /**
  90378. * Parse
  90379. */
  90380. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90381. for (var buf in parsedBuffers) {
  90382. var parsedBuffer = parsedBuffers[buf];
  90383. gltfRuntime.buffers[buf] = parsedBuffer;
  90384. gltfRuntime.buffersCount++;
  90385. }
  90386. };
  90387. var parseShaders = function (parsedShaders, gltfRuntime) {
  90388. for (var sha in parsedShaders) {
  90389. var parsedShader = parsedShaders[sha];
  90390. gltfRuntime.shaders[sha] = parsedShader;
  90391. gltfRuntime.shaderscount++;
  90392. }
  90393. };
  90394. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90395. for (var object in parsedObjects) {
  90396. var parsedObject = parsedObjects[object];
  90397. gltfRuntime[runtimeProperty][object] = parsedObject;
  90398. }
  90399. };
  90400. /**
  90401. * Utils
  90402. */
  90403. var normalizeUVs = function (buffer) {
  90404. if (!buffer) {
  90405. return;
  90406. }
  90407. for (var i = 0; i < buffer.length / 2; i++) {
  90408. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90409. }
  90410. };
  90411. var getAttribute = function (attributeParameter) {
  90412. if (attributeParameter.semantic === "NORMAL") {
  90413. return "normal";
  90414. }
  90415. else if (attributeParameter.semantic === "POSITION") {
  90416. return "position";
  90417. }
  90418. else if (attributeParameter.semantic === "JOINT") {
  90419. return "matricesIndices";
  90420. }
  90421. else if (attributeParameter.semantic === "WEIGHT") {
  90422. return "matricesWeights";
  90423. }
  90424. else if (attributeParameter.semantic === "COLOR") {
  90425. return "color";
  90426. }
  90427. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90428. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90429. return "uv" + (channel === 0 ? "" : channel + 1);
  90430. }
  90431. return null;
  90432. };
  90433. /**
  90434. * Loads and creates animations
  90435. */
  90436. var loadAnimations = function (gltfRuntime) {
  90437. for (var anim in gltfRuntime.animations) {
  90438. var animation = gltfRuntime.animations[anim];
  90439. if (!animation.channels || !animation.samplers) {
  90440. continue;
  90441. }
  90442. var lastAnimation = null;
  90443. for (var i = 0; i < animation.channels.length; i++) {
  90444. // Get parameters and load buffers
  90445. var channel = animation.channels[i];
  90446. var sampler = animation.samplers[channel.sampler];
  90447. if (!sampler) {
  90448. continue;
  90449. }
  90450. var inputData = null;
  90451. var outputData = null;
  90452. if (animation.parameters) {
  90453. inputData = animation.parameters[sampler.input];
  90454. outputData = animation.parameters[sampler.output];
  90455. }
  90456. else {
  90457. inputData = sampler.input;
  90458. outputData = sampler.output;
  90459. }
  90460. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90461. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90462. var targetID = channel.target.id;
  90463. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90464. if (targetNode === null) {
  90465. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90466. }
  90467. if (targetNode === null) {
  90468. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90469. continue;
  90470. }
  90471. var isBone = targetNode instanceof BABYLON.Bone;
  90472. // Get target path (position, rotation or scaling)
  90473. var targetPath = channel.target.path;
  90474. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90475. if (targetPathIndex !== -1) {
  90476. targetPath = babylonAnimationPaths[targetPathIndex];
  90477. }
  90478. // Determine animation type
  90479. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90480. if (!isBone) {
  90481. if (targetPath === "rotationQuaternion") {
  90482. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90483. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90484. }
  90485. else {
  90486. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90487. }
  90488. }
  90489. // Create animation and key frames
  90490. var babylonAnimation = null;
  90491. var keys = [];
  90492. var arrayOffset = 0;
  90493. var modifyKey = false;
  90494. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90495. babylonAnimation = lastAnimation;
  90496. modifyKey = true;
  90497. }
  90498. if (!modifyKey) {
  90499. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90500. }
  90501. // For each frame
  90502. for (var j = 0; j < bufferInput.length; j++) {
  90503. var value = null;
  90504. if (targetPath === "rotationQuaternion") {
  90505. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90506. arrayOffset += 4;
  90507. }
  90508. else {
  90509. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90510. arrayOffset += 3;
  90511. }
  90512. if (isBone) {
  90513. var bone = targetNode;
  90514. var translation = BABYLON.Vector3.Zero();
  90515. var rotationQuaternion = new BABYLON.Quaternion();
  90516. var scaling = BABYLON.Vector3.Zero();
  90517. // Warning on decompose
  90518. var mat = bone.getBaseMatrix();
  90519. if (modifyKey && lastAnimation) {
  90520. mat = lastAnimation.getKeys()[j].value;
  90521. }
  90522. mat.decompose(scaling, rotationQuaternion, translation);
  90523. if (targetPath === "position") {
  90524. translation = value;
  90525. }
  90526. else if (targetPath === "rotationQuaternion") {
  90527. rotationQuaternion = value;
  90528. }
  90529. else {
  90530. scaling = value;
  90531. }
  90532. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90533. }
  90534. if (!modifyKey) {
  90535. keys.push({
  90536. frame: bufferInput[j],
  90537. value: value
  90538. });
  90539. }
  90540. else if (lastAnimation) {
  90541. lastAnimation.getKeys()[j].value = value;
  90542. }
  90543. }
  90544. // Finish
  90545. if (!modifyKey && babylonAnimation) {
  90546. babylonAnimation.setKeys(keys);
  90547. targetNode.animations.push(babylonAnimation);
  90548. }
  90549. lastAnimation = babylonAnimation;
  90550. gltfRuntime.scene.stopAnimation(targetNode);
  90551. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90552. }
  90553. }
  90554. };
  90555. /**
  90556. * Returns the bones transformation matrix
  90557. */
  90558. var configureBoneTransformation = function (node) {
  90559. var mat = null;
  90560. if (node.translation || node.rotation || node.scale) {
  90561. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90562. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90563. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90564. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90565. }
  90566. else {
  90567. mat = BABYLON.Matrix.FromArray(node.matrix);
  90568. }
  90569. return mat;
  90570. };
  90571. /**
  90572. * Returns the parent bone
  90573. */
  90574. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90575. // Try to find
  90576. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90577. if (newSkeleton.bones[i].name === jointName) {
  90578. return newSkeleton.bones[i];
  90579. }
  90580. }
  90581. // Not found, search in gltf nodes
  90582. var nodes = gltfRuntime.nodes;
  90583. for (var nde in nodes) {
  90584. var node = nodes[nde];
  90585. if (!node.jointName) {
  90586. continue;
  90587. }
  90588. var children = node.children;
  90589. for (var i = 0; i < children.length; i++) {
  90590. var child = gltfRuntime.nodes[children[i]];
  90591. if (!child.jointName) {
  90592. continue;
  90593. }
  90594. if (child.jointName === jointName) {
  90595. var mat = configureBoneTransformation(node);
  90596. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90597. bone.id = nde;
  90598. return bone;
  90599. }
  90600. }
  90601. }
  90602. return null;
  90603. };
  90604. /**
  90605. * Returns the appropriate root node
  90606. */
  90607. var getNodeToRoot = function (nodesToRoot, id) {
  90608. for (var i = 0; i < nodesToRoot.length; i++) {
  90609. var nodeToRoot = nodesToRoot[i];
  90610. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90611. var child = nodeToRoot.node.children[j];
  90612. if (child === id) {
  90613. return nodeToRoot.bone;
  90614. }
  90615. }
  90616. }
  90617. return null;
  90618. };
  90619. /**
  90620. * Returns the node with the joint name
  90621. */
  90622. var getJointNode = function (gltfRuntime, jointName) {
  90623. var nodes = gltfRuntime.nodes;
  90624. var node = nodes[jointName];
  90625. if (node) {
  90626. return {
  90627. node: node,
  90628. id: jointName
  90629. };
  90630. }
  90631. for (var nde in nodes) {
  90632. node = nodes[nde];
  90633. if (node.jointName === jointName) {
  90634. return {
  90635. node: node,
  90636. id: nde
  90637. };
  90638. }
  90639. }
  90640. return null;
  90641. };
  90642. /**
  90643. * Checks if a nodes is in joints
  90644. */
  90645. var nodeIsInJoints = function (skins, id) {
  90646. for (var i = 0; i < skins.jointNames.length; i++) {
  90647. if (skins.jointNames[i] === id) {
  90648. return true;
  90649. }
  90650. }
  90651. return false;
  90652. };
  90653. /**
  90654. * Fills the nodes to root for bones and builds hierarchy
  90655. */
  90656. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90657. // Creates nodes for root
  90658. for (var nde in gltfRuntime.nodes) {
  90659. var node = gltfRuntime.nodes[nde];
  90660. var id = nde;
  90661. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90662. continue;
  90663. }
  90664. // Create node to root bone
  90665. var mat = configureBoneTransformation(node);
  90666. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90667. bone.id = id;
  90668. nodesToRoot.push({ bone: bone, node: node, id: id });
  90669. }
  90670. // Parenting
  90671. for (var i = 0; i < nodesToRoot.length; i++) {
  90672. var nodeToRoot = nodesToRoot[i];
  90673. var children = nodeToRoot.node.children;
  90674. for (var j = 0; j < children.length; j++) {
  90675. var child = null;
  90676. for (var k = 0; k < nodesToRoot.length; k++) {
  90677. if (nodesToRoot[k].id === children[j]) {
  90678. child = nodesToRoot[k];
  90679. break;
  90680. }
  90681. }
  90682. if (child) {
  90683. child.bone._parent = nodeToRoot.bone;
  90684. nodeToRoot.bone.children.push(child.bone);
  90685. }
  90686. }
  90687. }
  90688. };
  90689. /**
  90690. * Imports a skeleton
  90691. */
  90692. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90693. if (!newSkeleton) {
  90694. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90695. }
  90696. if (!skins.babylonSkeleton) {
  90697. return newSkeleton;
  90698. }
  90699. // Find the root bones
  90700. var nodesToRoot = [];
  90701. var nodesToRootToAdd = [];
  90702. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90703. newSkeleton.bones = [];
  90704. // Joints
  90705. for (var i = 0; i < skins.jointNames.length; i++) {
  90706. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90707. if (!jointNode) {
  90708. continue;
  90709. }
  90710. var node = jointNode.node;
  90711. if (!node) {
  90712. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90713. continue;
  90714. }
  90715. var id = jointNode.id;
  90716. // Optimize, if the bone already exists...
  90717. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90718. if (existingBone) {
  90719. newSkeleton.bones.push(existingBone);
  90720. continue;
  90721. }
  90722. // Search for parent bone
  90723. var foundBone = false;
  90724. var parentBone = null;
  90725. for (var j = 0; j < i; j++) {
  90726. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90727. if (!jointNode_1) {
  90728. continue;
  90729. }
  90730. var joint = jointNode_1.node;
  90731. if (!joint) {
  90732. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90733. continue;
  90734. }
  90735. var children = joint.children;
  90736. if (!children) {
  90737. continue;
  90738. }
  90739. foundBone = false;
  90740. for (var k = 0; k < children.length; k++) {
  90741. if (children[k] === id) {
  90742. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90743. foundBone = true;
  90744. break;
  90745. }
  90746. }
  90747. if (foundBone) {
  90748. break;
  90749. }
  90750. }
  90751. // Create bone
  90752. var mat = configureBoneTransformation(node);
  90753. if (!parentBone && nodesToRoot.length > 0) {
  90754. parentBone = getNodeToRoot(nodesToRoot, id);
  90755. if (parentBone) {
  90756. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90757. nodesToRootToAdd.push(parentBone);
  90758. }
  90759. }
  90760. }
  90761. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90762. bone.id = id;
  90763. }
  90764. // Polish
  90765. var bones = newSkeleton.bones;
  90766. newSkeleton.bones = [];
  90767. for (var i = 0; i < skins.jointNames.length; i++) {
  90768. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90769. if (!jointNode) {
  90770. continue;
  90771. }
  90772. for (var j = 0; j < bones.length; j++) {
  90773. if (bones[j].id === jointNode.id) {
  90774. newSkeleton.bones.push(bones[j]);
  90775. break;
  90776. }
  90777. }
  90778. }
  90779. newSkeleton.prepare();
  90780. // Finish
  90781. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90782. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90783. }
  90784. return newSkeleton;
  90785. };
  90786. /**
  90787. * Imports a mesh and its geometries
  90788. */
  90789. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90790. if (!newMesh) {
  90791. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90792. newMesh.id = id;
  90793. }
  90794. if (!node.babylonNode) {
  90795. return newMesh;
  90796. }
  90797. var subMaterials = [];
  90798. var vertexData = null;
  90799. var verticesStarts = new Array();
  90800. var verticesCounts = new Array();
  90801. var indexStarts = new Array();
  90802. var indexCounts = new Array();
  90803. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90804. var meshID = meshes[meshIndex];
  90805. var mesh = gltfRuntime.meshes[meshID];
  90806. if (!mesh) {
  90807. continue;
  90808. }
  90809. // Positions, normals and UVs
  90810. for (var i = 0; i < mesh.primitives.length; i++) {
  90811. // Temporary vertex data
  90812. var tempVertexData = new BABYLON.VertexData();
  90813. var primitive = mesh.primitives[i];
  90814. if (primitive.mode !== 4) {
  90815. // continue;
  90816. }
  90817. var attributes = primitive.attributes;
  90818. var accessor = null;
  90819. var buffer = null;
  90820. // Set positions, normal and uvs
  90821. for (var semantic in attributes) {
  90822. // Link accessor and buffer view
  90823. accessor = gltfRuntime.accessors[attributes[semantic]];
  90824. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90825. if (semantic === "NORMAL") {
  90826. tempVertexData.normals = new Float32Array(buffer.length);
  90827. tempVertexData.normals.set(buffer);
  90828. }
  90829. else if (semantic === "POSITION") {
  90830. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  90831. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  90832. for (var j = 0; j < buffer.length; j += 4) {
  90833. tempVertexData.positions[j] = buffer[j];
  90834. tempVertexData.positions[j + 1] = buffer[j + 1];
  90835. tempVertexData.positions[j + 2] = buffer[j + 2];
  90836. }
  90837. }
  90838. else {
  90839. tempVertexData.positions = new Float32Array(buffer.length);
  90840. tempVertexData.positions.set(buffer);
  90841. }
  90842. verticesCounts.push(tempVertexData.positions.length);
  90843. }
  90844. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  90845. var channel = Number(semantic.split("_")[1]);
  90846. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  90847. var uvs = new Float32Array(buffer.length);
  90848. uvs.set(buffer);
  90849. normalizeUVs(uvs);
  90850. tempVertexData.set(uvs, uvKind);
  90851. }
  90852. else if (semantic === "JOINT") {
  90853. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  90854. tempVertexData.matricesIndices.set(buffer);
  90855. }
  90856. else if (semantic === "WEIGHT") {
  90857. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  90858. tempVertexData.matricesWeights.set(buffer);
  90859. }
  90860. else if (semantic === "COLOR") {
  90861. tempVertexData.colors = new Float32Array(buffer.length);
  90862. tempVertexData.colors.set(buffer);
  90863. }
  90864. }
  90865. // Indices
  90866. accessor = gltfRuntime.accessors[primitive.indices];
  90867. if (accessor) {
  90868. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90869. tempVertexData.indices = new Int32Array(buffer.length);
  90870. tempVertexData.indices.set(buffer);
  90871. indexCounts.push(tempVertexData.indices.length);
  90872. }
  90873. else {
  90874. // Set indices on the fly
  90875. var indices = [];
  90876. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  90877. indices.push(j);
  90878. }
  90879. tempVertexData.indices = new Int32Array(indices);
  90880. indexCounts.push(tempVertexData.indices.length);
  90881. }
  90882. if (!vertexData) {
  90883. vertexData = tempVertexData;
  90884. }
  90885. else {
  90886. vertexData.merge(tempVertexData);
  90887. }
  90888. // Sub material
  90889. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  90890. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  90891. // Update vertices start and index start
  90892. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  90893. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  90894. }
  90895. }
  90896. var material;
  90897. if (subMaterials.length > 1) {
  90898. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  90899. material.subMaterials = subMaterials;
  90900. }
  90901. else {
  90902. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  90903. }
  90904. if (subMaterials.length === 1) {
  90905. material = subMaterials[0];
  90906. }
  90907. if (!newMesh.material) {
  90908. newMesh.material = material;
  90909. }
  90910. // Apply geometry
  90911. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  90912. newMesh.computeWorldMatrix(true);
  90913. // Apply submeshes
  90914. newMesh.subMeshes = [];
  90915. var index = 0;
  90916. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90917. var meshID = meshes[meshIndex];
  90918. var mesh = gltfRuntime.meshes[meshID];
  90919. if (!mesh) {
  90920. continue;
  90921. }
  90922. for (var i = 0; i < mesh.primitives.length; i++) {
  90923. if (mesh.primitives[i].mode !== 4) {
  90924. //continue;
  90925. }
  90926. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  90927. index++;
  90928. }
  90929. }
  90930. // Finish
  90931. return newMesh;
  90932. };
  90933. /**
  90934. * Configure node transformation from position, rotation and scaling
  90935. */
  90936. var configureNode = function (newNode, position, rotation, scaling) {
  90937. if (newNode.position) {
  90938. newNode.position = position;
  90939. }
  90940. if (newNode.rotationQuaternion || newNode.rotation) {
  90941. newNode.rotationQuaternion = rotation;
  90942. }
  90943. if (newNode.scaling) {
  90944. newNode.scaling = scaling;
  90945. }
  90946. };
  90947. /**
  90948. * Configures node from transformation matrix
  90949. */
  90950. var configureNodeFromMatrix = function (newNode, node, parent) {
  90951. if (node.matrix) {
  90952. var position = new BABYLON.Vector3(0, 0, 0);
  90953. var rotation = new BABYLON.Quaternion();
  90954. var scaling = new BABYLON.Vector3(0, 0, 0);
  90955. var mat = BABYLON.Matrix.FromArray(node.matrix);
  90956. mat.decompose(scaling, rotation, position);
  90957. configureNode(newNode, position, rotation, scaling);
  90958. }
  90959. else if (node.translation && node.rotation && node.scale) {
  90960. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  90961. }
  90962. newNode.computeWorldMatrix(true);
  90963. };
  90964. /**
  90965. * Imports a node
  90966. */
  90967. var importNode = function (gltfRuntime, node, id, parent) {
  90968. var lastNode = null;
  90969. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  90970. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  90971. return null;
  90972. }
  90973. }
  90974. // Meshes
  90975. if (node.skin) {
  90976. if (node.meshes) {
  90977. var skin = gltfRuntime.skins[node.skin];
  90978. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  90979. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  90980. if (newMesh.skeleton === null) {
  90981. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  90982. if (!skin.babylonSkeleton) {
  90983. skin.babylonSkeleton = newMesh.skeleton;
  90984. }
  90985. }
  90986. lastNode = newMesh;
  90987. }
  90988. }
  90989. else if (node.meshes) {
  90990. /**
  90991. * Improve meshes property
  90992. */
  90993. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  90994. lastNode = newMesh;
  90995. }
  90996. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90997. var light = gltfRuntime.lights[node.light];
  90998. if (light) {
  90999. if (light.type === "ambient") {
  91000. var ambienLight = light[light.type];
  91001. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91002. hemiLight.name = node.name || "";
  91003. if (ambienLight.color) {
  91004. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  91005. }
  91006. lastNode = hemiLight;
  91007. }
  91008. else if (light.type === "directional") {
  91009. var directionalLight = light[light.type];
  91010. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91011. dirLight.name = node.name || "";
  91012. if (directionalLight.color) {
  91013. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  91014. }
  91015. lastNode = dirLight;
  91016. }
  91017. else if (light.type === "point") {
  91018. var pointLight = light[light.type];
  91019. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91020. ptLight.name = node.name || "";
  91021. if (pointLight.color) {
  91022. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  91023. }
  91024. lastNode = ptLight;
  91025. }
  91026. else if (light.type === "spot") {
  91027. var spotLight = light[light.type];
  91028. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  91029. spLight.name = node.name || "";
  91030. if (spotLight.color) {
  91031. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  91032. }
  91033. if (spotLight.fallOfAngle) {
  91034. spLight.angle = spotLight.fallOfAngle;
  91035. }
  91036. if (spotLight.fallOffExponent) {
  91037. spLight.exponent = spotLight.fallOffExponent;
  91038. }
  91039. lastNode = spLight;
  91040. }
  91041. }
  91042. }
  91043. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  91044. var camera = gltfRuntime.cameras[node.camera];
  91045. if (camera) {
  91046. if (camera.type === "orthographic") {
  91047. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91048. orthoCamera.name = node.name || "";
  91049. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  91050. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91051. lastNode = orthoCamera;
  91052. }
  91053. else if (camera.type === "perspective") {
  91054. var perspectiveCamera = camera[camera.type];
  91055. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  91056. persCamera.name = node.name || "";
  91057. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  91058. if (!perspectiveCamera.aspectRatio) {
  91059. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  91060. }
  91061. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  91062. persCamera.maxZ = perspectiveCamera.zfar;
  91063. persCamera.minZ = perspectiveCamera.znear;
  91064. }
  91065. lastNode = persCamera;
  91066. }
  91067. }
  91068. }
  91069. // Empty node
  91070. if (!node.jointName) {
  91071. if (node.babylonNode) {
  91072. return node.babylonNode;
  91073. }
  91074. else if (lastNode === null) {
  91075. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  91076. node.babylonNode = dummy;
  91077. lastNode = dummy;
  91078. }
  91079. }
  91080. if (lastNode !== null) {
  91081. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  91082. configureNodeFromMatrix(lastNode, node, parent);
  91083. }
  91084. else {
  91085. var translation = node.translation || [0, 0, 0];
  91086. var rotation = node.rotation || [0, 0, 0, 1];
  91087. var scale = node.scale || [1, 1, 1];
  91088. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  91089. }
  91090. lastNode.updateCache(true);
  91091. node.babylonNode = lastNode;
  91092. }
  91093. return lastNode;
  91094. };
  91095. /**
  91096. * Traverses nodes and creates them
  91097. */
  91098. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  91099. if (meshIncluded === void 0) { meshIncluded = false; }
  91100. var node = gltfRuntime.nodes[id];
  91101. var newNode = null;
  91102. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  91103. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  91104. meshIncluded = true;
  91105. }
  91106. else {
  91107. meshIncluded = false;
  91108. }
  91109. }
  91110. else {
  91111. meshIncluded = true;
  91112. }
  91113. if (!node.jointName && meshIncluded) {
  91114. newNode = importNode(gltfRuntime, node, id, parent);
  91115. if (newNode !== null) {
  91116. newNode.id = id;
  91117. newNode.parent = parent;
  91118. }
  91119. }
  91120. if (node.children) {
  91121. for (var i = 0; i < node.children.length; i++) {
  91122. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  91123. }
  91124. }
  91125. };
  91126. /**
  91127. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  91128. */
  91129. var postLoad = function (gltfRuntime) {
  91130. // Nodes
  91131. var currentScene = gltfRuntime.currentScene;
  91132. if (currentScene) {
  91133. for (var i = 0; i < currentScene.nodes.length; i++) {
  91134. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91135. }
  91136. }
  91137. else {
  91138. for (var thing in gltfRuntime.scenes) {
  91139. currentScene = gltfRuntime.scenes[thing];
  91140. for (var i = 0; i < currentScene.nodes.length; i++) {
  91141. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91142. }
  91143. }
  91144. }
  91145. // Set animations
  91146. loadAnimations(gltfRuntime);
  91147. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  91148. var skeleton = gltfRuntime.scene.skeletons[i];
  91149. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  91150. }
  91151. };
  91152. /**
  91153. * onBind shaderrs callback to set uniforms and matrices
  91154. */
  91155. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  91156. var materialValues = material.values || technique.parameters;
  91157. for (var unif in unTreatedUniforms) {
  91158. var uniform = unTreatedUniforms[unif];
  91159. var type = uniform.type;
  91160. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  91161. if (uniform.semantic && !uniform.source && !uniform.node) {
  91162. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  91163. }
  91164. else if (uniform.semantic && (uniform.source || uniform.node)) {
  91165. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  91166. if (source === null) {
  91167. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  91168. }
  91169. if (source === null) {
  91170. continue;
  91171. }
  91172. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  91173. }
  91174. }
  91175. else {
  91176. var value = materialValues[technique.uniforms[unif]];
  91177. if (!value) {
  91178. continue;
  91179. }
  91180. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91181. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  91182. if (texture === null || texture === undefined) {
  91183. continue;
  91184. }
  91185. shaderMaterial.getEffect().setTexture(unif, texture);
  91186. }
  91187. else {
  91188. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  91189. }
  91190. }
  91191. }
  91192. onSuccess(shaderMaterial);
  91193. };
  91194. /**
  91195. * Prepare uniforms to send the only one time
  91196. * Loads the appropriate textures
  91197. */
  91198. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  91199. var materialValues = material.values || technique.parameters;
  91200. var techniqueUniforms = technique.uniforms;
  91201. /**
  91202. * Prepare values here (not matrices)
  91203. */
  91204. for (var unif in unTreatedUniforms) {
  91205. var uniform = unTreatedUniforms[unif];
  91206. var type = uniform.type;
  91207. var value = materialValues[techniqueUniforms[unif]];
  91208. if (value === undefined) {
  91209. // In case the value is the same for all materials
  91210. value = uniform.value;
  91211. }
  91212. if (!value) {
  91213. continue;
  91214. }
  91215. var onLoadTexture = function (uniformName) {
  91216. return function (texture) {
  91217. if (uniform.value && uniformName) {
  91218. // Static uniform
  91219. shaderMaterial.setTexture(uniformName, texture);
  91220. delete unTreatedUniforms[uniformName];
  91221. }
  91222. };
  91223. };
  91224. // Texture (sampler2D)
  91225. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  91226. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  91227. }
  91228. else {
  91229. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  91230. // Static uniform
  91231. delete unTreatedUniforms[unif];
  91232. }
  91233. }
  91234. }
  91235. };
  91236. /**
  91237. * Shader compilation failed
  91238. */
  91239. var onShaderCompileError = function (program, shaderMaterial, onError) {
  91240. return function (effect, error) {
  91241. shaderMaterial.dispose(true);
  91242. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  91243. };
  91244. };
  91245. /**
  91246. * Shader compilation success
  91247. */
  91248. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  91249. return function (_) {
  91250. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  91251. shaderMaterial.onBind = function (mesh) {
  91252. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  91253. };
  91254. };
  91255. };
  91256. /**
  91257. * Returns the appropriate uniform if already handled by babylon
  91258. */
  91259. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  91260. for (var unif in technique.uniforms) {
  91261. var uniform = technique.uniforms[unif];
  91262. var uniformParameter = technique.parameters[uniform];
  91263. if (tokenizer.currentIdentifier === unif) {
  91264. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  91265. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91266. if (transformIndex !== -1) {
  91267. delete unTreatedUniforms[unif];
  91268. return babylonTransforms[transformIndex];
  91269. }
  91270. }
  91271. }
  91272. }
  91273. return tokenizer.currentIdentifier;
  91274. };
  91275. /**
  91276. * All shaders loaded. Create materials one by one
  91277. */
  91278. var importMaterials = function (gltfRuntime) {
  91279. // Create materials
  91280. for (var mat in gltfRuntime.materials) {
  91281. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91282. }
  91283. };
  91284. /**
  91285. * Implementation of the base glTF spec
  91286. */
  91287. var GLTFLoaderBase = /** @class */ (function () {
  91288. function GLTFLoaderBase() {
  91289. }
  91290. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91291. var gltfRuntime = {
  91292. extensions: {},
  91293. accessors: {},
  91294. buffers: {},
  91295. bufferViews: {},
  91296. meshes: {},
  91297. lights: {},
  91298. cameras: {},
  91299. nodes: {},
  91300. images: {},
  91301. textures: {},
  91302. shaders: {},
  91303. programs: {},
  91304. samplers: {},
  91305. techniques: {},
  91306. materials: {},
  91307. animations: {},
  91308. skins: {},
  91309. extensionsUsed: [],
  91310. scenes: {},
  91311. buffersCount: 0,
  91312. shaderscount: 0,
  91313. scene: scene,
  91314. rootUrl: rootUrl,
  91315. loadedBufferCount: 0,
  91316. loadedBufferViews: {},
  91317. loadedShaderCount: 0,
  91318. importOnlyMeshes: false,
  91319. dummyNodes: []
  91320. };
  91321. // Parse
  91322. if (parsedData.extensions) {
  91323. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91324. }
  91325. if (parsedData.extensionsUsed) {
  91326. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91327. }
  91328. if (parsedData.buffers) {
  91329. parseBuffers(parsedData.buffers, gltfRuntime);
  91330. }
  91331. if (parsedData.bufferViews) {
  91332. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91333. }
  91334. if (parsedData.accessors) {
  91335. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91336. }
  91337. if (parsedData.meshes) {
  91338. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91339. }
  91340. if (parsedData.lights) {
  91341. parseObject(parsedData.lights, "lights", gltfRuntime);
  91342. }
  91343. if (parsedData.cameras) {
  91344. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91345. }
  91346. if (parsedData.nodes) {
  91347. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91348. }
  91349. if (parsedData.images) {
  91350. parseObject(parsedData.images, "images", gltfRuntime);
  91351. }
  91352. if (parsedData.textures) {
  91353. parseObject(parsedData.textures, "textures", gltfRuntime);
  91354. }
  91355. if (parsedData.shaders) {
  91356. parseShaders(parsedData.shaders, gltfRuntime);
  91357. }
  91358. if (parsedData.programs) {
  91359. parseObject(parsedData.programs, "programs", gltfRuntime);
  91360. }
  91361. if (parsedData.samplers) {
  91362. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91363. }
  91364. if (parsedData.techniques) {
  91365. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91366. }
  91367. if (parsedData.materials) {
  91368. parseObject(parsedData.materials, "materials", gltfRuntime);
  91369. }
  91370. if (parsedData.animations) {
  91371. parseObject(parsedData.animations, "animations", gltfRuntime);
  91372. }
  91373. if (parsedData.skins) {
  91374. parseObject(parsedData.skins, "skins", gltfRuntime);
  91375. }
  91376. if (parsedData.scenes) {
  91377. gltfRuntime.scenes = parsedData.scenes;
  91378. }
  91379. if (parsedData.scene && parsedData.scenes) {
  91380. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91381. }
  91382. return gltfRuntime;
  91383. };
  91384. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91385. var buffer = gltfRuntime.buffers[id];
  91386. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91387. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91388. }
  91389. else {
  91390. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91391. if (request) {
  91392. onError(request.status + " " + request.statusText);
  91393. }
  91394. });
  91395. }
  91396. };
  91397. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91398. var texture = gltfRuntime.textures[id];
  91399. if (!texture || !texture.source) {
  91400. onError("");
  91401. return;
  91402. }
  91403. if (texture.babylonTexture) {
  91404. onSuccess(null);
  91405. return;
  91406. }
  91407. var source = gltfRuntime.images[texture.source];
  91408. if (BABYLON.Tools.IsBase64(source.uri)) {
  91409. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91410. }
  91411. else {
  91412. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91413. if (request) {
  91414. onError(request.status + " " + request.statusText);
  91415. }
  91416. });
  91417. }
  91418. };
  91419. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91420. var texture = gltfRuntime.textures[id];
  91421. if (texture.babylonTexture) {
  91422. onSuccess(texture.babylonTexture);
  91423. return;
  91424. }
  91425. var sampler = gltfRuntime.samplers[texture.sampler];
  91426. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91427. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91428. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91429. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91430. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91431. var blob = new Blob([buffer]);
  91432. var blobURL = URL.createObjectURL(blob);
  91433. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91434. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91435. if (sampler.wrapS !== undefined) {
  91436. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91437. }
  91438. if (sampler.wrapT !== undefined) {
  91439. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91440. }
  91441. newTexture.name = id;
  91442. texture.babylonTexture = newTexture;
  91443. onSuccess(newTexture);
  91444. };
  91445. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91446. var shader = gltfRuntime.shaders[id];
  91447. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91448. var shaderString = atob(shader.uri.split(",")[1]);
  91449. onSuccess(shaderString);
  91450. }
  91451. else {
  91452. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91453. if (request) {
  91454. onError(request.status + " " + request.statusText);
  91455. }
  91456. });
  91457. }
  91458. };
  91459. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91460. var material = gltfRuntime.materials[id];
  91461. if (!material.technique) {
  91462. if (onError) {
  91463. onError("No technique found.");
  91464. }
  91465. return;
  91466. }
  91467. var technique = gltfRuntime.techniques[material.technique];
  91468. if (!technique) {
  91469. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91470. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91471. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91472. onSuccess(defaultMaterial);
  91473. return;
  91474. }
  91475. var program = gltfRuntime.programs[technique.program];
  91476. var states = technique.states;
  91477. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91478. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91479. var newVertexShader = "";
  91480. var newPixelShader = "";
  91481. var vertexTokenizer = new Tokenizer(vertexShader);
  91482. var pixelTokenizer = new Tokenizer(pixelShader);
  91483. var unTreatedUniforms = {};
  91484. var uniforms = [];
  91485. var attributes = [];
  91486. var samplers = [];
  91487. // Fill uniform, sampler2D and attributes
  91488. for (var unif in technique.uniforms) {
  91489. var uniform = technique.uniforms[unif];
  91490. var uniformParameter = technique.parameters[uniform];
  91491. unTreatedUniforms[unif] = uniformParameter;
  91492. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91493. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91494. if (transformIndex !== -1) {
  91495. uniforms.push(babylonTransforms[transformIndex]);
  91496. delete unTreatedUniforms[unif];
  91497. }
  91498. else {
  91499. uniforms.push(unif);
  91500. }
  91501. }
  91502. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91503. samplers.push(unif);
  91504. }
  91505. else {
  91506. uniforms.push(unif);
  91507. }
  91508. }
  91509. for (var attr in technique.attributes) {
  91510. var attribute = technique.attributes[attr];
  91511. var attributeParameter = technique.parameters[attribute];
  91512. if (attributeParameter.semantic) {
  91513. attributes.push(getAttribute(attributeParameter));
  91514. }
  91515. }
  91516. // Configure vertex shader
  91517. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91518. var tokenType = vertexTokenizer.currentToken;
  91519. if (tokenType !== ETokenType.IDENTIFIER) {
  91520. newVertexShader += vertexTokenizer.currentString;
  91521. continue;
  91522. }
  91523. var foundAttribute = false;
  91524. for (var attr in technique.attributes) {
  91525. var attribute = technique.attributes[attr];
  91526. var attributeParameter = technique.parameters[attribute];
  91527. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91528. newVertexShader += getAttribute(attributeParameter);
  91529. foundAttribute = true;
  91530. break;
  91531. }
  91532. }
  91533. if (foundAttribute) {
  91534. continue;
  91535. }
  91536. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91537. }
  91538. // Configure pixel shader
  91539. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91540. var tokenType = pixelTokenizer.currentToken;
  91541. if (tokenType !== ETokenType.IDENTIFIER) {
  91542. newPixelShader += pixelTokenizer.currentString;
  91543. continue;
  91544. }
  91545. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91546. }
  91547. // Create shader material
  91548. var shaderPath = {
  91549. vertex: program.vertexShader + id,
  91550. fragment: program.fragmentShader + id
  91551. };
  91552. var options = {
  91553. attributes: attributes,
  91554. uniforms: uniforms,
  91555. samplers: samplers,
  91556. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91557. };
  91558. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91559. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91560. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91561. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91562. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91563. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91564. if (states && states.functions) {
  91565. var functions = states.functions;
  91566. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91567. shaderMaterial.backFaceCulling = false;
  91568. }
  91569. var blendFunc = functions.blendFuncSeparate;
  91570. if (blendFunc) {
  91571. 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) {
  91572. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91573. }
  91574. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91575. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91576. }
  91577. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91578. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91579. }
  91580. 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) {
  91581. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91582. }
  91583. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91584. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91585. }
  91586. 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) {
  91587. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91588. }
  91589. }
  91590. }
  91591. };
  91592. return GLTFLoaderBase;
  91593. }());
  91594. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91595. /**
  91596. * glTF V1 Loader
  91597. */
  91598. var GLTFLoader = /** @class */ (function () {
  91599. function GLTFLoader() {
  91600. // #region Stubs for IGLTFLoader interface
  91601. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91602. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91603. this.compileMaterials = false;
  91604. this.useClipPlane = false;
  91605. this.compileShadowGenerators = false;
  91606. this.onDisposeObservable = new BABYLON.Observable();
  91607. this.onMeshLoadedObservable = new BABYLON.Observable();
  91608. this.onTextureLoadedObservable = new BABYLON.Observable();
  91609. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91610. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  91611. this.onCompleteObservable = new BABYLON.Observable();
  91612. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91613. this.state = null;
  91614. }
  91615. GLTFLoader.RegisterExtension = function (extension) {
  91616. if (GLTFLoader.Extensions[extension.name]) {
  91617. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91618. return;
  91619. }
  91620. GLTFLoader.Extensions[extension.name] = extension;
  91621. };
  91622. GLTFLoader.prototype.dispose = function () { };
  91623. // #endregion
  91624. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91625. var _this = this;
  91626. scene.useRightHandedSystem = true;
  91627. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91628. gltfRuntime.importOnlyMeshes = true;
  91629. if (meshesNames === "") {
  91630. gltfRuntime.importMeshesNames = [];
  91631. }
  91632. else if (typeof meshesNames === "string") {
  91633. gltfRuntime.importMeshesNames = [meshesNames];
  91634. }
  91635. else if (meshesNames && !(meshesNames instanceof Array)) {
  91636. gltfRuntime.importMeshesNames = [meshesNames];
  91637. }
  91638. else {
  91639. gltfRuntime.importMeshesNames = [];
  91640. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91641. }
  91642. // Create nodes
  91643. _this._createNodes(gltfRuntime);
  91644. var meshes = new Array();
  91645. var skeletons = new Array();
  91646. // Fill arrays of meshes and skeletons
  91647. for (var nde in gltfRuntime.nodes) {
  91648. var node = gltfRuntime.nodes[nde];
  91649. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91650. meshes.push(node.babylonNode);
  91651. }
  91652. }
  91653. for (var skl in gltfRuntime.skins) {
  91654. var skin = gltfRuntime.skins[skl];
  91655. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91656. skeletons.push(skin.babylonSkeleton);
  91657. }
  91658. }
  91659. // Load buffers, shaders, materials, etc.
  91660. _this._loadBuffersAsync(gltfRuntime, function () {
  91661. _this._loadShadersAsync(gltfRuntime, function () {
  91662. importMaterials(gltfRuntime);
  91663. postLoad(gltfRuntime);
  91664. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91665. onSuccess(meshes, [], skeletons);
  91666. }
  91667. });
  91668. }, onProgress);
  91669. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91670. onSuccess(meshes, [], skeletons);
  91671. }
  91672. }, onError);
  91673. return true;
  91674. };
  91675. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91676. var _this = this;
  91677. return new Promise(function (resolve, reject) {
  91678. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91679. resolve({
  91680. meshes: meshes,
  91681. particleSystems: particleSystems,
  91682. skeletons: skeletons
  91683. });
  91684. }, onProgress, function (message) {
  91685. reject(new Error(message));
  91686. });
  91687. });
  91688. };
  91689. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91690. var _this = this;
  91691. scene.useRightHandedSystem = true;
  91692. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91693. // Load runtime extensios
  91694. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91695. // Create nodes
  91696. _this._createNodes(gltfRuntime);
  91697. // Load buffers, shaders, materials, etc.
  91698. _this._loadBuffersAsync(gltfRuntime, function () {
  91699. _this._loadShadersAsync(gltfRuntime, function () {
  91700. importMaterials(gltfRuntime);
  91701. postLoad(gltfRuntime);
  91702. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91703. onSuccess();
  91704. }
  91705. });
  91706. });
  91707. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91708. onSuccess();
  91709. }
  91710. }, onError);
  91711. }, onError);
  91712. };
  91713. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91714. var _this = this;
  91715. return new Promise(function (resolve, reject) {
  91716. _this._loadAsync(scene, data, rootUrl, function () {
  91717. resolve();
  91718. }, onProgress, function (message) {
  91719. reject(new Error(message));
  91720. });
  91721. });
  91722. };
  91723. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91724. var hasShaders = false;
  91725. var processShader = function (sha, shader) {
  91726. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91727. gltfRuntime.loadedShaderCount++;
  91728. if (shaderString) {
  91729. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91730. }
  91731. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91732. onload();
  91733. }
  91734. }, function () {
  91735. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91736. });
  91737. };
  91738. for (var sha in gltfRuntime.shaders) {
  91739. hasShaders = true;
  91740. var shader = gltfRuntime.shaders[sha];
  91741. if (shader) {
  91742. processShader.bind(this, sha, shader)();
  91743. }
  91744. else {
  91745. BABYLON.Tools.Error("No shader named: " + sha);
  91746. }
  91747. }
  91748. if (!hasShaders) {
  91749. onload();
  91750. }
  91751. };
  91752. ;
  91753. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91754. var hasBuffers = false;
  91755. var processBuffer = function (buf, buffer) {
  91756. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91757. gltfRuntime.loadedBufferCount++;
  91758. if (bufferView) {
  91759. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91760. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91761. }
  91762. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91763. }
  91764. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91765. onLoad();
  91766. }
  91767. }, function () {
  91768. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91769. });
  91770. };
  91771. for (var buf in gltfRuntime.buffers) {
  91772. hasBuffers = true;
  91773. var buffer = gltfRuntime.buffers[buf];
  91774. if (buffer) {
  91775. processBuffer.bind(this, buf, buffer)();
  91776. }
  91777. else {
  91778. BABYLON.Tools.Error("No buffer named: " + buf);
  91779. }
  91780. }
  91781. if (!hasBuffers) {
  91782. onLoad();
  91783. }
  91784. };
  91785. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91786. var currentScene = gltfRuntime.currentScene;
  91787. if (currentScene) {
  91788. // Only one scene even if multiple scenes are defined
  91789. for (var i = 0; i < currentScene.nodes.length; i++) {
  91790. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91791. }
  91792. }
  91793. else {
  91794. // Load all scenes
  91795. for (var thing in gltfRuntime.scenes) {
  91796. currentScene = gltfRuntime.scenes[thing];
  91797. for (var i = 0; i < currentScene.nodes.length; i++) {
  91798. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91799. }
  91800. }
  91801. }
  91802. };
  91803. GLTFLoader.Extensions = {};
  91804. return GLTFLoader;
  91805. }());
  91806. GLTF1.GLTFLoader = GLTFLoader;
  91807. ;
  91808. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  91809. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91810. })(BABYLON || (BABYLON = {}));
  91811. //# sourceMappingURL=babylon.glTFLoader.js.map
  91812. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91813. var BABYLON;
  91814. (function (BABYLON) {
  91815. var GLTF1;
  91816. (function (GLTF1) {
  91817. /**
  91818. * Utils functions for GLTF
  91819. */
  91820. var GLTFUtils = /** @class */ (function () {
  91821. function GLTFUtils() {
  91822. }
  91823. /**
  91824. * Sets the given "parameter" matrix
  91825. * @param scene: the {BABYLON.Scene} object
  91826. * @param source: the source node where to pick the matrix
  91827. * @param parameter: the GLTF technique parameter
  91828. * @param uniformName: the name of the shader's uniform
  91829. * @param shaderMaterial: the shader material
  91830. */
  91831. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  91832. var mat = null;
  91833. if (parameter.semantic === "MODEL") {
  91834. mat = source.getWorldMatrix();
  91835. }
  91836. else if (parameter.semantic === "PROJECTION") {
  91837. mat = scene.getProjectionMatrix();
  91838. }
  91839. else if (parameter.semantic === "VIEW") {
  91840. mat = scene.getViewMatrix();
  91841. }
  91842. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  91843. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  91844. }
  91845. else if (parameter.semantic === "MODELVIEW") {
  91846. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  91847. }
  91848. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  91849. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  91850. }
  91851. else if (parameter.semantic === "MODELINVERSE") {
  91852. mat = source.getWorldMatrix().invert();
  91853. }
  91854. else if (parameter.semantic === "VIEWINVERSE") {
  91855. mat = scene.getViewMatrix().invert();
  91856. }
  91857. else if (parameter.semantic === "PROJECTIONINVERSE") {
  91858. mat = scene.getProjectionMatrix().invert();
  91859. }
  91860. else if (parameter.semantic === "MODELVIEWINVERSE") {
  91861. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  91862. }
  91863. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  91864. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  91865. }
  91866. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  91867. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  91868. }
  91869. else {
  91870. debugger;
  91871. }
  91872. if (mat) {
  91873. switch (parameter.type) {
  91874. case GLTF1.EParameterType.FLOAT_MAT2:
  91875. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  91876. break;
  91877. case GLTF1.EParameterType.FLOAT_MAT3:
  91878. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  91879. break;
  91880. case GLTF1.EParameterType.FLOAT_MAT4:
  91881. shaderMaterial.setMatrix(uniformName, mat);
  91882. break;
  91883. default: break;
  91884. }
  91885. }
  91886. };
  91887. /**
  91888. * Sets the given "parameter" matrix
  91889. * @param shaderMaterial: the shader material
  91890. * @param uniform: the name of the shader's uniform
  91891. * @param value: the value of the uniform
  91892. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  91893. */
  91894. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  91895. switch (type) {
  91896. case GLTF1.EParameterType.FLOAT:
  91897. shaderMaterial.setFloat(uniform, value);
  91898. return true;
  91899. case GLTF1.EParameterType.FLOAT_VEC2:
  91900. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  91901. return true;
  91902. case GLTF1.EParameterType.FLOAT_VEC3:
  91903. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  91904. return true;
  91905. case GLTF1.EParameterType.FLOAT_VEC4:
  91906. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  91907. return true;
  91908. default: return false;
  91909. }
  91910. };
  91911. /**
  91912. * Returns the wrap mode of the texture
  91913. * @param mode: the mode value
  91914. */
  91915. GLTFUtils.GetWrapMode = function (mode) {
  91916. switch (mode) {
  91917. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91918. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91919. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91920. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91921. }
  91922. };
  91923. /**
  91924. * Returns the byte stride giving an accessor
  91925. * @param accessor: the GLTF accessor objet
  91926. */
  91927. GLTFUtils.GetByteStrideFromType = function (accessor) {
  91928. // Needs this function since "byteStride" isn't requiered in glTF format
  91929. var type = accessor.type;
  91930. switch (type) {
  91931. case "VEC2": return 2;
  91932. case "VEC3": return 3;
  91933. case "VEC4": return 4;
  91934. case "MAT2": return 4;
  91935. case "MAT3": return 9;
  91936. case "MAT4": return 16;
  91937. default: return 1;
  91938. }
  91939. };
  91940. /**
  91941. * Returns the texture filter mode giving a mode value
  91942. * @param mode: the filter mode value
  91943. */
  91944. GLTFUtils.GetTextureFilterMode = function (mode) {
  91945. switch (mode) {
  91946. case GLTF1.ETextureFilterType.LINEAR:
  91947. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  91948. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  91949. case GLTF1.ETextureFilterType.NEAREST:
  91950. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  91951. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91952. }
  91953. };
  91954. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  91955. var byteOffset = bufferView.byteOffset + byteOffset;
  91956. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  91957. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  91958. throw new Error("Buffer access is out of range");
  91959. }
  91960. var buffer = loadedBufferView.buffer;
  91961. byteOffset += loadedBufferView.byteOffset;
  91962. switch (componentType) {
  91963. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  91964. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  91965. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  91966. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  91967. default: return new Float32Array(buffer, byteOffset, byteLength);
  91968. }
  91969. };
  91970. /**
  91971. * Returns a buffer from its accessor
  91972. * @param gltfRuntime: the GLTF runtime
  91973. * @param accessor: the GLTF accessor
  91974. */
  91975. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  91976. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  91977. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  91978. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  91979. };
  91980. /**
  91981. * Decodes a buffer view into a string
  91982. * @param view: the buffer view
  91983. */
  91984. GLTFUtils.DecodeBufferToText = function (view) {
  91985. var result = "";
  91986. var length = view.byteLength;
  91987. for (var i = 0; i < length; ++i) {
  91988. result += String.fromCharCode(view[i]);
  91989. }
  91990. return result;
  91991. };
  91992. /**
  91993. * Returns the default material of gltf. Related to
  91994. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  91995. * @param scene: the Babylon.js scene
  91996. */
  91997. GLTFUtils.GetDefaultMaterial = function (scene) {
  91998. if (!GLTFUtils._DefaultMaterial) {
  91999. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  92000. "precision highp float;",
  92001. "",
  92002. "uniform mat4 worldView;",
  92003. "uniform mat4 projection;",
  92004. "",
  92005. "attribute vec3 position;",
  92006. "",
  92007. "void main(void)",
  92008. "{",
  92009. " gl_Position = projection * worldView * vec4(position, 1.0);",
  92010. "}"
  92011. ].join("\n");
  92012. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  92013. "precision highp float;",
  92014. "",
  92015. "uniform vec4 u_emission;",
  92016. "",
  92017. "void main(void)",
  92018. "{",
  92019. " gl_FragColor = u_emission;",
  92020. "}"
  92021. ].join("\n");
  92022. var shaderPath = {
  92023. vertex: "GLTFDefaultMaterial",
  92024. fragment: "GLTFDefaultMaterial"
  92025. };
  92026. var options = {
  92027. attributes: ["position"],
  92028. uniforms: ["worldView", "projection", "u_emission"],
  92029. samplers: new Array(),
  92030. needAlphaBlending: false
  92031. };
  92032. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  92033. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  92034. }
  92035. return GLTFUtils._DefaultMaterial;
  92036. };
  92037. // The GLTF default material
  92038. GLTFUtils._DefaultMaterial = null;
  92039. return GLTFUtils;
  92040. }());
  92041. GLTF1.GLTFUtils = GLTFUtils;
  92042. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92043. })(BABYLON || (BABYLON = {}));
  92044. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  92045. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92046. var BABYLON;
  92047. (function (BABYLON) {
  92048. var GLTF1;
  92049. (function (GLTF1) {
  92050. var GLTFLoaderExtension = /** @class */ (function () {
  92051. function GLTFLoaderExtension(name) {
  92052. this._name = name;
  92053. }
  92054. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  92055. get: function () {
  92056. return this._name;
  92057. },
  92058. enumerable: true,
  92059. configurable: true
  92060. });
  92061. /**
  92062. * Defines an override for loading the runtime
  92063. * Return true to stop further extensions from loading the runtime
  92064. */
  92065. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92066. return false;
  92067. };
  92068. /**
  92069. * Defines an onverride for creating gltf runtime
  92070. * Return true to stop further extensions from creating the runtime
  92071. */
  92072. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92073. return false;
  92074. };
  92075. /**
  92076. * Defines an override for loading buffers
  92077. * Return true to stop further extensions from loading this buffer
  92078. */
  92079. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92080. return false;
  92081. };
  92082. /**
  92083. * Defines an override for loading texture buffers
  92084. * Return true to stop further extensions from loading this texture data
  92085. */
  92086. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92087. return false;
  92088. };
  92089. /**
  92090. * Defines an override for creating textures
  92091. * Return true to stop further extensions from loading this texture
  92092. */
  92093. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92094. return false;
  92095. };
  92096. /**
  92097. * Defines an override for loading shader strings
  92098. * Return true to stop further extensions from loading this shader data
  92099. */
  92100. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92101. return false;
  92102. };
  92103. /**
  92104. * Defines an override for loading materials
  92105. * Return true to stop further extensions from loading this material
  92106. */
  92107. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92108. return false;
  92109. };
  92110. // ---------
  92111. // Utilities
  92112. // ---------
  92113. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92114. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92115. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  92116. }, function () {
  92117. setTimeout(function () {
  92118. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92119. });
  92120. });
  92121. };
  92122. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92123. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92124. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  92125. }, function () {
  92126. setTimeout(function () {
  92127. onSuccess();
  92128. });
  92129. });
  92130. };
  92131. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92132. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92133. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92134. }, function () {
  92135. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  92136. });
  92137. };
  92138. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  92139. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  92140. };
  92141. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92142. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92143. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92144. }, function () {
  92145. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  92146. });
  92147. };
  92148. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92149. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92150. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92151. }, function () {
  92152. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  92153. });
  92154. };
  92155. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92156. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92157. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92158. }, function () {
  92159. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  92160. });
  92161. };
  92162. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92163. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  92164. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92165. }, function () {
  92166. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  92167. });
  92168. };
  92169. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  92170. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  92171. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  92172. if (func(loaderExtension)) {
  92173. return;
  92174. }
  92175. }
  92176. defaultFunc();
  92177. };
  92178. return GLTFLoaderExtension;
  92179. }());
  92180. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  92181. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92182. })(BABYLON || (BABYLON = {}));
  92183. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92184. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92185. var BABYLON;
  92186. (function (BABYLON) {
  92187. var GLTF1;
  92188. (function (GLTF1) {
  92189. var BinaryExtensionBufferName = "binary_glTF";
  92190. ;
  92191. ;
  92192. var GLTFBinaryExtension = /** @class */ (function (_super) {
  92193. __extends(GLTFBinaryExtension, _super);
  92194. function GLTFBinaryExtension() {
  92195. return _super.call(this, "KHR_binary_glTF") || this;
  92196. }
  92197. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  92198. var extensionsUsed = data.json.extensionsUsed;
  92199. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  92200. return false;
  92201. }
  92202. this._bin = data.bin;
  92203. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  92204. return true;
  92205. };
  92206. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92207. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  92208. return false;
  92209. }
  92210. if (id !== BinaryExtensionBufferName) {
  92211. return false;
  92212. }
  92213. onSuccess(this._bin);
  92214. return true;
  92215. };
  92216. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92217. var texture = gltfRuntime.textures[id];
  92218. var source = gltfRuntime.images[texture.source];
  92219. if (!source.extensions || !(this.name in source.extensions)) {
  92220. return false;
  92221. }
  92222. var sourceExt = source.extensions[this.name];
  92223. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  92224. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92225. onSuccess(buffer);
  92226. return true;
  92227. };
  92228. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  92229. var shader = gltfRuntime.shaders[id];
  92230. if (!shader.extensions || !(this.name in shader.extensions)) {
  92231. return false;
  92232. }
  92233. var binaryExtensionShader = shader.extensions[this.name];
  92234. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  92235. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  92236. setTimeout(function () {
  92237. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  92238. onSuccess(shaderString);
  92239. });
  92240. return true;
  92241. };
  92242. return GLTFBinaryExtension;
  92243. }(GLTF1.GLTFLoaderExtension));
  92244. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  92245. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  92246. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92247. })(BABYLON || (BABYLON = {}));
  92248. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  92249. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92250. var BABYLON;
  92251. (function (BABYLON) {
  92252. var GLTF1;
  92253. (function (GLTF1) {
  92254. ;
  92255. ;
  92256. ;
  92257. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  92258. __extends(GLTFMaterialsCommonExtension, _super);
  92259. function GLTFMaterialsCommonExtension() {
  92260. return _super.call(this, "KHR_materials_common") || this;
  92261. }
  92262. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  92263. if (!gltfRuntime.extensions)
  92264. return false;
  92265. var extension = gltfRuntime.extensions[this.name];
  92266. if (!extension)
  92267. return false;
  92268. // Create lights
  92269. var lights = extension.lights;
  92270. if (lights) {
  92271. for (var thing in lights) {
  92272. var light = lights[thing];
  92273. switch (light.type) {
  92274. case "ambient":
  92275. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92276. var ambient = light.ambient;
  92277. if (ambient) {
  92278. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92279. }
  92280. break;
  92281. case "point":
  92282. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92283. var point = light.point;
  92284. if (point) {
  92285. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92286. }
  92287. break;
  92288. case "directional":
  92289. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92290. var directional = light.directional;
  92291. if (directional) {
  92292. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92293. }
  92294. break;
  92295. case "spot":
  92296. var spot = light.spot;
  92297. if (spot) {
  92298. 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);
  92299. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92300. }
  92301. break;
  92302. default:
  92303. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92304. break;
  92305. }
  92306. }
  92307. }
  92308. return false;
  92309. };
  92310. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92311. var material = gltfRuntime.materials[id];
  92312. if (!material || !material.extensions)
  92313. return false;
  92314. var extension = material.extensions[this.name];
  92315. if (!extension)
  92316. return false;
  92317. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92318. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92319. if (extension.technique === "CONSTANT") {
  92320. standardMaterial.disableLighting = true;
  92321. }
  92322. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92323. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92324. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92325. // Ambient
  92326. if (typeof extension.values.ambient === "string") {
  92327. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92328. }
  92329. else {
  92330. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92331. }
  92332. // Diffuse
  92333. if (typeof extension.values.diffuse === "string") {
  92334. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92335. }
  92336. else {
  92337. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92338. }
  92339. // Emission
  92340. if (typeof extension.values.emission === "string") {
  92341. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92342. }
  92343. else {
  92344. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92345. }
  92346. // Specular
  92347. if (typeof extension.values.specular === "string") {
  92348. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92349. }
  92350. else {
  92351. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92352. }
  92353. return true;
  92354. };
  92355. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92356. // Create buffer from texture url
  92357. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92358. // Create texture from buffer
  92359. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92360. }, onError);
  92361. };
  92362. return GLTFMaterialsCommonExtension;
  92363. }(GLTF1.GLTFLoaderExtension));
  92364. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92365. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92366. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92367. })(BABYLON || (BABYLON = {}));
  92368. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92369. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92370. var BABYLON;
  92371. (function (BABYLON) {
  92372. var GLTF2;
  92373. (function (GLTF2) {
  92374. var ArrayItem = /** @class */ (function () {
  92375. function ArrayItem() {
  92376. }
  92377. ArrayItem.Assign = function (values) {
  92378. if (values) {
  92379. for (var index = 0; index < values.length; index++) {
  92380. values[index]._index = index;
  92381. }
  92382. }
  92383. };
  92384. return ArrayItem;
  92385. }());
  92386. GLTF2.ArrayItem = ArrayItem;
  92387. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92388. })(BABYLON || (BABYLON = {}));
  92389. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92390. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92391. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92392. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92393. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92394. var BABYLON;
  92395. (function (BABYLON) {
  92396. var GLTF2;
  92397. (function (GLTF2) {
  92398. var GLTFLoader = /** @class */ (function () {
  92399. function GLTFLoader() {
  92400. this._completePromises = new Array();
  92401. this._disposed = false;
  92402. this._state = null;
  92403. this._extensions = {};
  92404. this._defaultSampler = {};
  92405. this._requests = new Array();
  92406. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92407. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92408. this.compileMaterials = false;
  92409. this.useClipPlane = false;
  92410. this.compileShadowGenerators = false;
  92411. this.onDisposeObservable = new BABYLON.Observable();
  92412. this.onMeshLoadedObservable = new BABYLON.Observable();
  92413. this.onTextureLoadedObservable = new BABYLON.Observable();
  92414. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92415. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  92416. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92417. this.onCompleteObservable = new BABYLON.Observable();
  92418. }
  92419. GLTFLoader._Register = function (name, factory) {
  92420. if (GLTFLoader._Factories[name]) {
  92421. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92422. return;
  92423. }
  92424. GLTFLoader._Factories[name] = factory;
  92425. // Keep the order of registration so that extensions registered first are called first.
  92426. GLTFLoader._Names.push(name);
  92427. };
  92428. Object.defineProperty(GLTFLoader.prototype, "state", {
  92429. get: function () {
  92430. return this._state;
  92431. },
  92432. enumerable: true,
  92433. configurable: true
  92434. });
  92435. GLTFLoader.prototype.dispose = function () {
  92436. if (this._disposed) {
  92437. return;
  92438. }
  92439. this._disposed = true;
  92440. this.onDisposeObservable.notifyObservers(this);
  92441. this.onDisposeObservable.clear();
  92442. this._clear();
  92443. };
  92444. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92445. var _this = this;
  92446. return Promise.resolve().then(function () {
  92447. var nodes = null;
  92448. if (meshesNames) {
  92449. var nodeMap_1 = {};
  92450. if (_this._gltf.nodes) {
  92451. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92452. var node = _a[_i];
  92453. if (node.name) {
  92454. nodeMap_1[node.name] = node;
  92455. }
  92456. }
  92457. }
  92458. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92459. nodes = names.map(function (name) {
  92460. var node = nodeMap_1[name];
  92461. if (!node) {
  92462. throw new Error("Failed to find node " + name);
  92463. }
  92464. return node;
  92465. });
  92466. }
  92467. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92468. return {
  92469. meshes: _this._getMeshes(),
  92470. particleSystems: [],
  92471. skeletons: _this._getSkeletons(),
  92472. };
  92473. });
  92474. });
  92475. };
  92476. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92477. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92478. };
  92479. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92480. var _this = this;
  92481. return Promise.resolve().then(function () {
  92482. _this._loadExtensions();
  92483. _this._babylonScene = scene;
  92484. _this._rootUrl = rootUrl;
  92485. _this._progressCallback = onProgress;
  92486. _this._state = BABYLON.GLTFLoaderState.Loading;
  92487. _this._loadData(data);
  92488. _this._checkExtensions();
  92489. var promises = new Array();
  92490. if (nodes) {
  92491. promises.push(_this._loadNodesAsync(nodes));
  92492. }
  92493. else {
  92494. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92495. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92496. }
  92497. if (_this.compileMaterials) {
  92498. promises.push(_this._compileMaterialsAsync());
  92499. }
  92500. if (_this.compileShadowGenerators) {
  92501. promises.push(_this._compileShadowGeneratorsAsync());
  92502. }
  92503. var resultPromise = Promise.all(promises).then(function () {
  92504. _this._state = BABYLON.GLTFLoaderState.Ready;
  92505. _this._startAnimations();
  92506. });
  92507. resultPromise.then(function () {
  92508. _this._rootBabylonMesh.setEnabled(true);
  92509. BABYLON.Tools.SetImmediate(function () {
  92510. if (!_this._disposed) {
  92511. Promise.all(_this._completePromises).then(function () {
  92512. _this._state = BABYLON.GLTFLoaderState.Complete;
  92513. _this.onCompleteObservable.notifyObservers(_this);
  92514. _this.onCompleteObservable.clear();
  92515. _this._clear();
  92516. }).catch(function (error) {
  92517. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92518. _this._clear();
  92519. });
  92520. }
  92521. });
  92522. });
  92523. return resultPromise;
  92524. }).catch(function (error) {
  92525. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92526. _this._clear();
  92527. throw error;
  92528. });
  92529. };
  92530. GLTFLoader.prototype._loadExtensions = function () {
  92531. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92532. var name_1 = _a[_i];
  92533. var extension = GLTFLoader._Factories[name_1](this);
  92534. this._extensions[name_1] = extension;
  92535. this.onExtensionLoadedObservable.notifyObservers(extension);
  92536. }
  92537. this.onExtensionLoadedObservable.clear();
  92538. };
  92539. GLTFLoader.prototype._loadData = function (data) {
  92540. this._gltf = data.json;
  92541. this._setupData();
  92542. if (data.bin) {
  92543. var buffers = this._gltf.buffers;
  92544. if (buffers && buffers[0] && !buffers[0].uri) {
  92545. var binaryBuffer = buffers[0];
  92546. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92547. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92548. }
  92549. binaryBuffer._data = Promise.resolve(data.bin);
  92550. }
  92551. else {
  92552. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92553. }
  92554. }
  92555. };
  92556. GLTFLoader.prototype._setupData = function () {
  92557. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92558. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92559. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92560. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92561. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92562. GLTF2.ArrayItem.Assign(this._gltf.images);
  92563. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92564. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92565. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92566. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92567. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92568. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92569. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92570. if (this._gltf.nodes) {
  92571. var nodeParents = {};
  92572. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92573. var node = _a[_i];
  92574. if (node.children) {
  92575. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92576. var index = _c[_b];
  92577. nodeParents[index] = node._index;
  92578. }
  92579. }
  92580. }
  92581. var rootNode = this._createRootNode();
  92582. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92583. var node = _e[_d];
  92584. var parentIndex = nodeParents[node._index];
  92585. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92586. }
  92587. }
  92588. };
  92589. GLTFLoader.prototype._checkExtensions = function () {
  92590. if (this._gltf.extensionsRequired) {
  92591. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92592. var name_2 = _a[_i];
  92593. var extension = this._extensions[name_2];
  92594. if (!extension || !extension.enabled) {
  92595. throw new Error("Require extension " + name_2 + " is not available");
  92596. }
  92597. }
  92598. }
  92599. };
  92600. GLTFLoader.prototype._createRootNode = function () {
  92601. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92602. this._rootBabylonMesh.setEnabled(false);
  92603. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92604. switch (this.coordinateSystemMode) {
  92605. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92606. if (!this._babylonScene.useRightHandedSystem) {
  92607. rootNode.rotation = [0, 1, 0, 0];
  92608. rootNode.scale = [1, 1, -1];
  92609. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92610. }
  92611. break;
  92612. }
  92613. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92614. this._babylonScene.useRightHandedSystem = true;
  92615. break;
  92616. }
  92617. default: {
  92618. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  92619. }
  92620. }
  92621. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92622. return rootNode;
  92623. };
  92624. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92625. var promises = new Array();
  92626. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92627. var node = nodes_1[_i];
  92628. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92629. }
  92630. promises.push(this._loadAnimationsAsync());
  92631. return Promise.all(promises).then(function () { });
  92632. };
  92633. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92634. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92635. if (promise) {
  92636. return promise;
  92637. }
  92638. var promises = new Array();
  92639. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92640. var index = _a[_i];
  92641. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92642. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92643. }
  92644. promises.push(this._loadAnimationsAsync());
  92645. return Promise.all(promises).then(function () { });
  92646. };
  92647. GLTFLoader.prototype._getMeshes = function () {
  92648. var meshes = new Array();
  92649. // Root mesh is always first.
  92650. meshes.push(this._rootBabylonMesh);
  92651. var nodes = this._gltf.nodes;
  92652. if (nodes) {
  92653. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92654. var node = nodes_2[_i];
  92655. if (node._babylonMesh) {
  92656. meshes.push(node._babylonMesh);
  92657. }
  92658. if (node._primitiveBabylonMeshes) {
  92659. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  92660. var babylonMesh = _b[_a];
  92661. meshes.push(babylonMesh);
  92662. }
  92663. }
  92664. }
  92665. }
  92666. return meshes;
  92667. };
  92668. GLTFLoader.prototype._getSkeletons = function () {
  92669. var skeletons = new Array();
  92670. var skins = this._gltf.skins;
  92671. if (skins) {
  92672. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92673. var skin = skins_1[_i];
  92674. if (skin._babylonSkeleton) {
  92675. skeletons.push(skin._babylonSkeleton);
  92676. }
  92677. }
  92678. }
  92679. return skeletons;
  92680. };
  92681. GLTFLoader.prototype._startAnimations = function () {
  92682. var animations = this._gltf.animations;
  92683. if (!animations) {
  92684. return;
  92685. }
  92686. switch (this.animationStartMode) {
  92687. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92688. // do nothing
  92689. break;
  92690. }
  92691. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92692. var animation = animations[0];
  92693. animation._babylonAnimationGroup.start(true);
  92694. break;
  92695. }
  92696. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92697. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92698. var animation = animations_1[_i];
  92699. animation._babylonAnimationGroup.start(true);
  92700. }
  92701. break;
  92702. }
  92703. default: {
  92704. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  92705. return;
  92706. }
  92707. }
  92708. };
  92709. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92710. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92711. if (promise) {
  92712. return promise;
  92713. }
  92714. if (node._babylonMesh) {
  92715. throw new Error(context + ": Invalid recursive node hierarchy");
  92716. }
  92717. var promises = new Array();
  92718. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92719. node._babylonMesh = babylonMesh;
  92720. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92721. node._babylonAnimationTargets.push(babylonMesh);
  92722. GLTFLoader._LoadTransform(node, babylonMesh);
  92723. if (node.mesh != undefined) {
  92724. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92725. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  92726. }
  92727. if (node.children) {
  92728. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92729. var index = _a[_i];
  92730. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92731. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92732. }
  92733. }
  92734. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92735. return Promise.all(promises).then(function () { });
  92736. };
  92737. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  92738. // TODO: instancing
  92739. var promises = new Array();
  92740. var primitives = mesh.primitives;
  92741. if (!primitives || primitives.length === 0) {
  92742. throw new Error(context + ": Primitives are missing");
  92743. }
  92744. GLTF2.ArrayItem.Assign(primitives);
  92745. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92746. var primitive = primitives_1[_i];
  92747. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  92748. }
  92749. if (node.skin != undefined) {
  92750. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92751. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92752. }
  92753. return Promise.all(promises).then(function () {
  92754. if (node._primitiveBabylonMeshes) {
  92755. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92756. var primitiveBabylonMesh = _a[_i];
  92757. primitiveBabylonMesh._refreshBoundingInfo(true);
  92758. }
  92759. }
  92760. });
  92761. };
  92762. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  92763. var _this = this;
  92764. var promises = new Array();
  92765. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  92766. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  92767. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  92768. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92769. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92770. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92771. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92772. }));
  92773. if (primitive.material == undefined) {
  92774. babylonMesh.material = this._getDefaultMaterial();
  92775. }
  92776. else {
  92777. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  92778. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  92779. babylonMesh.material = babylonMaterial;
  92780. }));
  92781. }
  92782. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92783. return Promise.all(promises).then(function () { });
  92784. };
  92785. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92786. var _this = this;
  92787. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92788. if (promise) {
  92789. return promise;
  92790. }
  92791. var attributes = primitive.attributes;
  92792. if (!attributes) {
  92793. throw new Error(context + ": Attributes are missing");
  92794. }
  92795. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  92796. // TODO: handle other primitive modes
  92797. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  92798. }
  92799. var promises = new Array();
  92800. var babylonVertexData = new BABYLON.VertexData();
  92801. if (primitive.indices == undefined) {
  92802. var positionAccessorIndex = attributes["POSITION"];
  92803. if (positionAccessorIndex != undefined) {
  92804. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  92805. babylonVertexData.indices = new Uint32Array(accessor.count);
  92806. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  92807. babylonVertexData.indices[i] = i;
  92808. }
  92809. }
  92810. }
  92811. else {
  92812. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  92813. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  92814. babylonVertexData.indices = data;
  92815. }));
  92816. }
  92817. var loadAttribute = function (attribute, kind) {
  92818. if (attributes[attribute] == undefined) {
  92819. return;
  92820. }
  92821. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  92822. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  92823. babylonMesh._delayInfo.push(kind);
  92824. }
  92825. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92826. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92827. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  92828. if (attribute === "COLOR_0") {
  92829. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  92830. babylonMesh.hasVertexAlpha = true;
  92831. if (accessor.type === "VEC3") {
  92832. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  92833. }
  92834. }
  92835. babylonVertexData.set(attributeData, kind);
  92836. }));
  92837. };
  92838. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  92839. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  92840. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  92841. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  92842. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  92843. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  92844. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  92845. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  92846. return Promise.all(promises).then(function () {
  92847. return babylonVertexData;
  92848. });
  92849. };
  92850. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  92851. if (!primitive.targets) {
  92852. return;
  92853. }
  92854. if (node._numMorphTargets == undefined) {
  92855. node._numMorphTargets = primitive.targets.length;
  92856. }
  92857. else if (primitive.targets.length !== node._numMorphTargets) {
  92858. throw new Error(context + ": Primitives do not have the same number of targets");
  92859. }
  92860. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  92861. for (var index = 0; index < primitive.targets.length; index++) {
  92862. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  92863. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  92864. // TODO: tell the target whether it has positions, normals, tangents
  92865. }
  92866. };
  92867. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  92868. if (!primitive.targets) {
  92869. return Promise.resolve();
  92870. }
  92871. var promises = new Array();
  92872. var morphTargetManager = babylonMesh.morphTargetManager;
  92873. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  92874. var babylonMorphTarget = morphTargetManager.getTarget(index);
  92875. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  92876. }
  92877. return Promise.all(promises).then(function () { });
  92878. };
  92879. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  92880. var _this = this;
  92881. var promises = new Array();
  92882. var loadAttribute = function (attribute, setData) {
  92883. if (attributes[attribute] == undefined) {
  92884. return;
  92885. }
  92886. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92887. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92888. setData(data);
  92889. }));
  92890. };
  92891. loadAttribute("POSITION", function (data) {
  92892. if (babylonVertexData.positions) {
  92893. for (var i = 0; i < data.length; i++) {
  92894. data[i] += babylonVertexData.positions[i];
  92895. }
  92896. babylonMorphTarget.setPositions(data);
  92897. }
  92898. });
  92899. loadAttribute("NORMAL", function (data) {
  92900. if (babylonVertexData.normals) {
  92901. for (var i = 0; i < data.length; i++) {
  92902. data[i] += babylonVertexData.normals[i];
  92903. }
  92904. babylonMorphTarget.setNormals(data);
  92905. }
  92906. });
  92907. loadAttribute("TANGENT", function (data) {
  92908. if (babylonVertexData.tangents) {
  92909. // Tangent data for morph targets is stored as xyz delta.
  92910. // The vertexData.tangent is stored as xyzw.
  92911. // So we need to skip every fourth vertexData.tangent.
  92912. for (var i = 0, j = 0; i < data.length; i++) {
  92913. data[i] += babylonVertexData.tangents[j++];
  92914. if ((i + 1) % 3 == 0) {
  92915. j++;
  92916. }
  92917. }
  92918. babylonMorphTarget.setTangents(data);
  92919. }
  92920. });
  92921. return Promise.all(promises).then(function () { });
  92922. };
  92923. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  92924. if (accessor.componentType == 5126 /* FLOAT */) {
  92925. return data;
  92926. }
  92927. var factor = 1;
  92928. if (accessor.normalized) {
  92929. switch (accessor.componentType) {
  92930. case 5121 /* UNSIGNED_BYTE */: {
  92931. factor = 1 / 255;
  92932. break;
  92933. }
  92934. case 5123 /* UNSIGNED_SHORT */: {
  92935. factor = 1 / 65535;
  92936. break;
  92937. }
  92938. default: {
  92939. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92940. }
  92941. }
  92942. }
  92943. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  92944. for (var i = 0; i < result.length; i++) {
  92945. result[i] = data[i] * factor;
  92946. }
  92947. return result;
  92948. };
  92949. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  92950. var result = new Float32Array(data.length / 3 * 4);
  92951. var offset = 0;
  92952. for (var i = 0; i < result.length; i++) {
  92953. if ((i + 1) % 4 === 0) {
  92954. result[i] = 1;
  92955. }
  92956. else {
  92957. result[i] = data[offset++];
  92958. }
  92959. }
  92960. return result;
  92961. };
  92962. GLTFLoader._LoadTransform = function (node, babylonNode) {
  92963. var position = BABYLON.Vector3.Zero();
  92964. var rotation = BABYLON.Quaternion.Identity();
  92965. var scaling = BABYLON.Vector3.One();
  92966. if (node.matrix) {
  92967. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  92968. matrix.decompose(scaling, rotation, position);
  92969. }
  92970. else {
  92971. if (node.translation)
  92972. position = BABYLON.Vector3.FromArray(node.translation);
  92973. if (node.rotation)
  92974. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  92975. if (node.scale)
  92976. scaling = BABYLON.Vector3.FromArray(node.scale);
  92977. }
  92978. babylonNode.position = position;
  92979. babylonNode.rotationQuaternion = rotation;
  92980. babylonNode.scaling = scaling;
  92981. };
  92982. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  92983. var _this = this;
  92984. var assignSkeleton = function () {
  92985. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92986. var babylonMesh = _a[_i];
  92987. babylonMesh.skeleton = skin._babylonSkeleton;
  92988. }
  92989. node._babylonMesh.parent = _this._rootBabylonMesh;
  92990. node._babylonMesh.position = BABYLON.Vector3.Zero();
  92991. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  92992. node._babylonMesh.scaling = BABYLON.Vector3.One();
  92993. };
  92994. if (skin._loaded) {
  92995. return skin._loaded.then(function () {
  92996. assignSkeleton();
  92997. });
  92998. }
  92999. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  93000. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  93001. var skeletonId = "skeleton" + skin._index;
  93002. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  93003. skin._babylonSkeleton = babylonSkeleton;
  93004. _this._loadBones(context, skin, inverseBindMatricesData);
  93005. assignSkeleton();
  93006. }));
  93007. };
  93008. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  93009. if (skin.inverseBindMatrices == undefined) {
  93010. return Promise.resolve(null);
  93011. }
  93012. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  93013. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  93014. return data;
  93015. });
  93016. };
  93017. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  93018. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  93019. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  93020. node._babylonAnimationTargets.push(babylonBone);
  93021. return babylonBone;
  93022. };
  93023. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  93024. var babylonBones = {};
  93025. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  93026. var index = _a[_i];
  93027. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  93028. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  93029. }
  93030. };
  93031. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  93032. var babylonBone = babylonBones[node._index];
  93033. if (babylonBone) {
  93034. return babylonBone;
  93035. }
  93036. var boneIndex = skin.joints.indexOf(node._index);
  93037. var baseMatrix = BABYLON.Matrix.Identity();
  93038. if (inverseBindMatricesData && boneIndex !== -1) {
  93039. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  93040. baseMatrix.invertToRef(baseMatrix);
  93041. }
  93042. var babylonParentBone = null;
  93043. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  93044. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  93045. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  93046. }
  93047. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  93048. babylonBones[node._index] = babylonBone;
  93049. return babylonBone;
  93050. };
  93051. GLTFLoader.prototype._getNodeMatrix = function (node) {
  93052. return node.matrix ?
  93053. BABYLON.Matrix.FromArray(node.matrix) :
  93054. 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());
  93055. };
  93056. GLTFLoader.prototype._loadAnimationsAsync = function () {
  93057. var animations = this._gltf.animations;
  93058. if (!animations) {
  93059. return Promise.resolve();
  93060. }
  93061. var promises = new Array();
  93062. for (var index = 0; index < animations.length; index++) {
  93063. var animation = animations[index];
  93064. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  93065. }
  93066. return Promise.all(promises).then(function () { });
  93067. };
  93068. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  93069. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  93070. animation._babylonAnimationGroup = babylonAnimationGroup;
  93071. var promises = new Array();
  93072. GLTF2.ArrayItem.Assign(animation.channels);
  93073. GLTF2.ArrayItem.Assign(animation.samplers);
  93074. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  93075. var channel = _a[_i];
  93076. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  93077. }
  93078. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  93079. return Promise.all(promises).then(function () {
  93080. babylonAnimationGroup.normalize();
  93081. });
  93082. };
  93083. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  93084. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  93085. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  93086. return Promise.resolve();
  93087. }
  93088. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  93089. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  93090. var targetPath;
  93091. var animationType;
  93092. switch (channel.target.path) {
  93093. case "translation" /* TRANSLATION */: {
  93094. targetPath = "position";
  93095. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93096. break;
  93097. }
  93098. case "rotation" /* ROTATION */: {
  93099. targetPath = "rotationQuaternion";
  93100. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  93101. break;
  93102. }
  93103. case "scale" /* SCALE */: {
  93104. targetPath = "scaling";
  93105. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  93106. break;
  93107. }
  93108. case "weights" /* WEIGHTS */: {
  93109. targetPath = "influence";
  93110. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  93111. break;
  93112. }
  93113. default: {
  93114. throw new Error(context + ": Invalid target path " + channel.target.path);
  93115. }
  93116. }
  93117. var outputBufferOffset = 0;
  93118. var getNextOutputValue;
  93119. switch (targetPath) {
  93120. case "position": {
  93121. getNextOutputValue = function () {
  93122. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93123. outputBufferOffset += 3;
  93124. return value;
  93125. };
  93126. break;
  93127. }
  93128. case "rotationQuaternion": {
  93129. getNextOutputValue = function () {
  93130. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  93131. outputBufferOffset += 4;
  93132. return value;
  93133. };
  93134. break;
  93135. }
  93136. case "scaling": {
  93137. getNextOutputValue = function () {
  93138. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  93139. outputBufferOffset += 3;
  93140. return value;
  93141. };
  93142. break;
  93143. }
  93144. case "influence": {
  93145. getNextOutputValue = function () {
  93146. var value = new Array(targetNode._numMorphTargets);
  93147. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  93148. value[i] = data.output[outputBufferOffset++];
  93149. }
  93150. return value;
  93151. };
  93152. break;
  93153. }
  93154. }
  93155. var getNextKey;
  93156. switch (data.interpolation) {
  93157. case "STEP" /* STEP */: {
  93158. getNextKey = function (frameIndex) { return ({
  93159. frame: data.input[frameIndex],
  93160. value: getNextOutputValue(),
  93161. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  93162. }); };
  93163. break;
  93164. }
  93165. case "LINEAR" /* LINEAR */: {
  93166. getNextKey = function (frameIndex) { return ({
  93167. frame: data.input[frameIndex],
  93168. value: getNextOutputValue()
  93169. }); };
  93170. break;
  93171. }
  93172. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93173. getNextKey = function (frameIndex) { return ({
  93174. frame: data.input[frameIndex],
  93175. inTangent: getNextOutputValue(),
  93176. value: getNextOutputValue(),
  93177. outTangent: getNextOutputValue()
  93178. }); };
  93179. break;
  93180. }
  93181. }
  93182. var keys;
  93183. if (data.input.length === 1) {
  93184. var key = getNextKey(0);
  93185. keys = [
  93186. { frame: key.frame, value: key.value },
  93187. { frame: key.frame + 1, value: key.value }
  93188. ];
  93189. }
  93190. else {
  93191. keys = new Array(data.input.length);
  93192. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  93193. keys[frameIndex] = getNextKey(frameIndex);
  93194. }
  93195. }
  93196. if (targetPath === "influence") {
  93197. var _loop_1 = function (targetIndex) {
  93198. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93199. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93200. babylonAnimation.setKeys(keys.map(function (key) { return ({
  93201. frame: key.frame,
  93202. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  93203. value: key.value[targetIndex],
  93204. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  93205. }); }));
  93206. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  93207. var babylonMesh = _a[_i];
  93208. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  93209. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  93210. }
  93211. };
  93212. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  93213. _loop_1(targetIndex);
  93214. }
  93215. }
  93216. else {
  93217. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  93218. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  93219. babylonAnimation.setKeys(keys);
  93220. if (targetNode._babylonAnimationTargets) {
  93221. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  93222. var target = _a[_i];
  93223. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  93224. }
  93225. }
  93226. }
  93227. });
  93228. };
  93229. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  93230. if (sampler._data) {
  93231. return sampler._data;
  93232. }
  93233. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  93234. switch (interpolation) {
  93235. case "STEP" /* STEP */:
  93236. case "LINEAR" /* LINEAR */:
  93237. case "CUBICSPLINE" /* CUBICSPLINE */: {
  93238. break;
  93239. }
  93240. default: {
  93241. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  93242. }
  93243. }
  93244. var inputData;
  93245. var outputData;
  93246. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  93247. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  93248. sampler._data = Promise.all([
  93249. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  93250. inputData = data;
  93251. }),
  93252. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  93253. outputData = data;
  93254. })
  93255. ]).then(function () {
  93256. return {
  93257. input: inputData,
  93258. interpolation: interpolation,
  93259. output: outputData,
  93260. };
  93261. });
  93262. return sampler._data;
  93263. };
  93264. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  93265. if (buffer._data) {
  93266. return buffer._data;
  93267. }
  93268. if (!buffer.uri) {
  93269. throw new Error(context + ": Uri is missing");
  93270. }
  93271. buffer._data = this._loadUriAsync(context, buffer.uri);
  93272. return buffer._data;
  93273. };
  93274. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  93275. if (bufferView._data) {
  93276. return bufferView._data;
  93277. }
  93278. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93279. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93280. try {
  93281. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93282. }
  93283. catch (e) {
  93284. throw new Error(context + ": " + e.message);
  93285. }
  93286. });
  93287. return bufferView._data;
  93288. };
  93289. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93290. var _this = this;
  93291. if (accessor.sparse) {
  93292. throw new Error(context + ": Sparse accessors are not currently supported");
  93293. }
  93294. if (accessor._data) {
  93295. return accessor._data;
  93296. }
  93297. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93298. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93299. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93300. var byteOffset = accessor.byteOffset || 0;
  93301. var byteStride = bufferView.byteStride;
  93302. if (byteStride === 0) {
  93303. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93304. }
  93305. try {
  93306. switch (accessor.componentType) {
  93307. case 5120 /* BYTE */: {
  93308. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93309. }
  93310. case 5121 /* UNSIGNED_BYTE */: {
  93311. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93312. }
  93313. case 5122 /* SHORT */: {
  93314. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93315. }
  93316. case 5123 /* UNSIGNED_SHORT */: {
  93317. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93318. }
  93319. case 5125 /* UNSIGNED_INT */: {
  93320. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93321. }
  93322. case 5126 /* FLOAT */: {
  93323. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93324. }
  93325. default: {
  93326. throw new Error(context + ": Invalid component type " + accessor.componentType);
  93327. }
  93328. }
  93329. }
  93330. catch (e) {
  93331. throw new Error(context + ": " + e);
  93332. }
  93333. });
  93334. return accessor._data;
  93335. };
  93336. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93337. byteOffset += data.byteOffset;
  93338. var targetLength = count * numComponents;
  93339. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93340. return new typedArray(data.buffer, byteOffset, targetLength);
  93341. }
  93342. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93343. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93344. var targetBuffer = new typedArray(targetLength);
  93345. var sourceIndex = 0;
  93346. var targetIndex = 0;
  93347. while (targetIndex < targetLength) {
  93348. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93349. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93350. targetIndex++;
  93351. }
  93352. sourceIndex += elementStride;
  93353. }
  93354. return targetBuffer;
  93355. };
  93356. GLTFLoader.prototype._getDefaultMaterial = function () {
  93357. var id = "__gltf_default";
  93358. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93359. if (!babylonMaterial) {
  93360. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93361. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93362. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93363. babylonMaterial.metallic = 1;
  93364. babylonMaterial.roughness = 1;
  93365. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93366. }
  93367. return babylonMaterial;
  93368. };
  93369. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93370. var promises = new Array();
  93371. var babylonMaterial = material._babylonMaterial;
  93372. // Ensure metallic workflow
  93373. babylonMaterial.metallic = 1;
  93374. babylonMaterial.roughness = 1;
  93375. var properties = material.pbrMetallicRoughness;
  93376. if (properties) {
  93377. if (properties.baseColorFactor) {
  93378. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93379. babylonMaterial.alpha = properties.baseColorFactor[3];
  93380. }
  93381. else {
  93382. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93383. }
  93384. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93385. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93386. if (properties.baseColorTexture) {
  93387. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93388. babylonMaterial.albedoTexture = texture;
  93389. }));
  93390. }
  93391. if (properties.metallicRoughnessTexture) {
  93392. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93393. babylonMaterial.metallicTexture = texture;
  93394. }));
  93395. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93396. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93397. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93398. }
  93399. }
  93400. this._loadMaterialAlphaProperties(context, material);
  93401. return Promise.all(promises).then(function () { });
  93402. };
  93403. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93404. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  93405. if (promise) {
  93406. return promise;
  93407. }
  93408. material._babylonMeshes = material._babylonMeshes || [];
  93409. material._babylonMeshes.push(babylonMesh);
  93410. if (!material._loaded) {
  93411. var promises = new Array();
  93412. var babylonMaterial = this._createMaterial(material);
  93413. material._babylonMaterial = babylonMaterial;
  93414. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93415. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93416. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93417. material._loaded = Promise.all(promises).then(function () { });
  93418. }
  93419. assign(material._babylonMaterial);
  93420. return material._loaded;
  93421. };
  93422. GLTFLoader.prototype._createMaterial = function (material) {
  93423. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93424. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93425. return babylonMaterial;
  93426. };
  93427. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93428. var promises = new Array();
  93429. var babylonMaterial = material._babylonMaterial;
  93430. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93431. if (material.doubleSided) {
  93432. babylonMaterial.backFaceCulling = false;
  93433. babylonMaterial.twoSidedLighting = true;
  93434. }
  93435. if (material.normalTexture) {
  93436. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93437. babylonMaterial.bumpTexture = texture;
  93438. }));
  93439. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93440. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93441. if (material.normalTexture.scale != undefined) {
  93442. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93443. }
  93444. }
  93445. if (material.occlusionTexture) {
  93446. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93447. babylonMaterial.ambientTexture = texture;
  93448. }));
  93449. babylonMaterial.useAmbientInGrayScale = true;
  93450. if (material.occlusionTexture.strength != undefined) {
  93451. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93452. }
  93453. }
  93454. if (material.emissiveTexture) {
  93455. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93456. babylonMaterial.emissiveTexture = texture;
  93457. }));
  93458. }
  93459. return Promise.all(promises).then(function () { });
  93460. };
  93461. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93462. var babylonMaterial = material._babylonMaterial;
  93463. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93464. switch (alphaMode) {
  93465. case "OPAQUE" /* OPAQUE */: {
  93466. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93467. break;
  93468. }
  93469. case "MASK" /* MASK */: {
  93470. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93471. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93472. if (babylonMaterial.alpha) {
  93473. if (babylonMaterial.alpha === 0) {
  93474. babylonMaterial.alphaCutOff = 1;
  93475. }
  93476. else {
  93477. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93478. }
  93479. babylonMaterial.alpha = 1;
  93480. }
  93481. if (babylonMaterial.albedoTexture) {
  93482. babylonMaterial.albedoTexture.hasAlpha = true;
  93483. }
  93484. break;
  93485. }
  93486. case "BLEND" /* BLEND */: {
  93487. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93488. if (babylonMaterial.albedoTexture) {
  93489. babylonMaterial.albedoTexture.hasAlpha = true;
  93490. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93491. }
  93492. break;
  93493. }
  93494. default: {
  93495. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  93496. }
  93497. }
  93498. };
  93499. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93500. var _this = this;
  93501. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93502. context = "#/textures/" + textureInfo.index;
  93503. var promises = new Array();
  93504. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93505. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93506. var deferred = new BABYLON.Deferred();
  93507. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93508. if (!_this._disposed) {
  93509. deferred.resolve();
  93510. }
  93511. }, function (message, exception) {
  93512. if (!_this._disposed) {
  93513. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  93514. }
  93515. });
  93516. promises.push(deferred.promise);
  93517. babylonTexture.name = texture.name || "texture" + texture._index;
  93518. babylonTexture.wrapU = samplerData.wrapU;
  93519. babylonTexture.wrapV = samplerData.wrapV;
  93520. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93521. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93522. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93523. babylonTexture.updateURL(objectURL);
  93524. }));
  93525. assign(babylonTexture);
  93526. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93527. return Promise.all(promises).then(function () { });
  93528. };
  93529. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93530. if (!sampler._data) {
  93531. sampler._data = {
  93532. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93533. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93534. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93535. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93536. };
  93537. }
  93538. ;
  93539. return sampler._data;
  93540. };
  93541. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93542. if (image._objectURL) {
  93543. return image._objectURL;
  93544. }
  93545. var promise;
  93546. if (image.uri) {
  93547. promise = this._loadUriAsync(context, image.uri);
  93548. }
  93549. else {
  93550. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93551. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93552. }
  93553. image._objectURL = promise.then(function (data) {
  93554. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93555. });
  93556. return image._objectURL;
  93557. };
  93558. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93559. var _this = this;
  93560. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93561. if (promise) {
  93562. return promise;
  93563. }
  93564. if (!GLTFLoader._ValidateUri(uri)) {
  93565. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93566. }
  93567. if (BABYLON.Tools.IsBase64(uri)) {
  93568. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93569. }
  93570. return new Promise(function (resolve, reject) {
  93571. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93572. if (!_this._disposed) {
  93573. resolve(new Uint8Array(data));
  93574. }
  93575. }, function (event) {
  93576. if (!_this._disposed) {
  93577. try {
  93578. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93579. request._lengthComputable = event.lengthComputable;
  93580. request._loaded = event.loaded;
  93581. request._total = event.total;
  93582. _this._onProgress();
  93583. }
  93584. }
  93585. catch (e) {
  93586. reject(e);
  93587. }
  93588. }
  93589. }, _this._babylonScene.database, true, function (request, exception) {
  93590. if (!_this._disposed) {
  93591. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93592. }
  93593. });
  93594. _this._requests.push(request);
  93595. });
  93596. };
  93597. GLTFLoader.prototype._onProgress = function () {
  93598. if (!this._progressCallback) {
  93599. return;
  93600. }
  93601. var lengthComputable = true;
  93602. var loaded = 0;
  93603. var total = 0;
  93604. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93605. var request = _a[_i];
  93606. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93607. return;
  93608. }
  93609. lengthComputable = lengthComputable && request._lengthComputable;
  93610. loaded += request._loaded;
  93611. total += request._total;
  93612. }
  93613. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93614. };
  93615. GLTFLoader._GetProperty = function (context, array, index) {
  93616. if (!array || index == undefined || !array[index]) {
  93617. throw new Error(context + ": Failed to find index " + index);
  93618. }
  93619. return array[index];
  93620. };
  93621. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93622. // Set defaults if undefined
  93623. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93624. switch (mode) {
  93625. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93626. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93627. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93628. default:
  93629. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  93630. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93631. }
  93632. };
  93633. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93634. // Set defaults if undefined
  93635. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93636. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93637. if (magFilter === 9729 /* LINEAR */) {
  93638. switch (minFilter) {
  93639. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93640. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93641. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93642. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93643. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93644. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93645. default:
  93646. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93647. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93648. }
  93649. }
  93650. else {
  93651. if (magFilter !== 9728 /* NEAREST */) {
  93652. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  93653. }
  93654. switch (minFilter) {
  93655. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93656. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93657. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93658. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93659. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93660. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93661. default:
  93662. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93663. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93664. }
  93665. }
  93666. };
  93667. GLTFLoader._GetNumComponents = function (context, type) {
  93668. switch (type) {
  93669. case "SCALAR": return 1;
  93670. case "VEC2": return 2;
  93671. case "VEC3": return 3;
  93672. case "VEC4": return 4;
  93673. case "MAT2": return 4;
  93674. case "MAT3": return 9;
  93675. case "MAT4": return 16;
  93676. }
  93677. throw new Error(context + ": Invalid type " + type);
  93678. };
  93679. GLTFLoader._ValidateUri = function (uri) {
  93680. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93681. };
  93682. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93683. var promises = new Array();
  93684. if (this._gltf.materials) {
  93685. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93686. var material = _a[_i];
  93687. var babylonMaterial = material._babylonMaterial;
  93688. var babylonMeshes = material._babylonMeshes;
  93689. if (babylonMaterial && babylonMeshes) {
  93690. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93691. var babylonMesh = babylonMeshes_1[_b];
  93692. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93693. if (this.useClipPlane) {
  93694. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93695. }
  93696. }
  93697. }
  93698. }
  93699. }
  93700. return Promise.all(promises).then(function () { });
  93701. };
  93702. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93703. var promises = new Array();
  93704. var lights = this._babylonScene.lights;
  93705. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93706. var light = lights_1[_i];
  93707. var generator = light.getShadowGenerator();
  93708. if (generator) {
  93709. promises.push(generator.forceCompilationAsync());
  93710. }
  93711. }
  93712. return Promise.all(promises).then(function () { });
  93713. };
  93714. GLTFLoader.prototype._clear = function () {
  93715. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93716. var request = _a[_i];
  93717. request.abort();
  93718. }
  93719. this._requests.length = 0;
  93720. if (this._gltf && this._gltf.images) {
  93721. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93722. var image = _c[_b];
  93723. if (image._objectURL) {
  93724. image._objectURL.then(function (value) {
  93725. URL.revokeObjectURL(value);
  93726. });
  93727. image._objectURL = undefined;
  93728. }
  93729. }
  93730. }
  93731. delete this._gltf;
  93732. delete this._babylonScene;
  93733. this._completePromises.length = 0;
  93734. for (var name_3 in this._extensions) {
  93735. this._extensions[name_3].dispose();
  93736. }
  93737. this._extensions = {};
  93738. delete this._rootBabylonMesh;
  93739. delete this._progressCallback;
  93740. this.onMeshLoadedObservable.clear();
  93741. this.onTextureLoadedObservable.clear();
  93742. this.onMaterialLoadedObservable.clear();
  93743. };
  93744. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93745. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93746. var name_4 = _a[_i];
  93747. var extension = this._extensions[name_4];
  93748. if (extension.enabled) {
  93749. var promise = actionAsync(extension);
  93750. if (promise) {
  93751. return promise;
  93752. }
  93753. }
  93754. }
  93755. return null;
  93756. };
  93757. GLTFLoader._Names = new Array();
  93758. GLTFLoader._Factories = {};
  93759. return GLTFLoader;
  93760. }());
  93761. GLTF2.GLTFLoader = GLTFLoader;
  93762. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93763. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93764. })(BABYLON || (BABYLON = {}));
  93765. //# sourceMappingURL=babylon.glTFLoader.js.map
  93766. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93767. var BABYLON;
  93768. (function (BABYLON) {
  93769. var GLTF2;
  93770. (function (GLTF2) {
  93771. var GLTFLoaderExtension = /** @class */ (function () {
  93772. function GLTFLoaderExtension(loader) {
  93773. this.enabled = true;
  93774. this._loader = loader;
  93775. }
  93776. GLTFLoaderExtension.prototype.dispose = function () {
  93777. delete this._loader;
  93778. };
  93779. // #region Overridable Methods
  93780. /** Override this method to modify the default behavior for loading scenes. */
  93781. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93782. /** Override this method to modify the default behavior for loading nodes. */
  93783. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93784. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93785. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93786. /** Override this method to modify the default behavior for loading materials. */
  93787. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  93788. /** Override this method to modify the default behavior for loading uris. */
  93789. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93790. // #endregion
  93791. /** Helper method called by a loader extension to load an glTF extension. */
  93792. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  93793. if (!property.extensions) {
  93794. return null;
  93795. }
  93796. var extensions = property.extensions;
  93797. var extension = extensions[this.name];
  93798. if (!extension) {
  93799. return null;
  93800. }
  93801. // Clear out the extension before executing the action to avoid recursing into the same property.
  93802. delete extensions[this.name];
  93803. try {
  93804. return actionAsync(context + "/extensions/" + this.name, extension);
  93805. }
  93806. finally {
  93807. // Restore the extension after executing the action.
  93808. extensions[this.name] = extension;
  93809. }
  93810. };
  93811. /** Helper method called by the loader to allow extensions to override loading scenes. */
  93812. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  93813. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  93814. };
  93815. /** Helper method called by the loader to allow extensions to override loading nodes. */
  93816. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  93817. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  93818. };
  93819. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  93820. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  93821. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  93822. };
  93823. /** Helper method called by the loader to allow extensions to override loading materials. */
  93824. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  93825. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  93826. };
  93827. /** Helper method called by the loader to allow extensions to override loading uris. */
  93828. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  93829. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  93830. };
  93831. return GLTFLoaderExtension;
  93832. }());
  93833. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  93834. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93835. })(BABYLON || (BABYLON = {}));
  93836. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93837. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93838. var BABYLON;
  93839. (function (BABYLON) {
  93840. var GLTF2;
  93841. (function (GLTF2) {
  93842. var Extensions;
  93843. (function (Extensions) {
  93844. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  93845. var NAME = "MSFT_lod";
  93846. var MSFT_lod = /** @class */ (function (_super) {
  93847. __extends(MSFT_lod, _super);
  93848. function MSFT_lod() {
  93849. var _this = _super !== null && _super.apply(this, arguments) || this;
  93850. _this.name = NAME;
  93851. /**
  93852. * Maximum number of LODs to load, starting from the lowest LOD.
  93853. */
  93854. _this.maxLODsToLoad = Number.MAX_VALUE;
  93855. _this._loadingNodeLOD = null;
  93856. _this._loadNodeSignals = {};
  93857. _this._loadingMaterialLOD = null;
  93858. _this._loadMaterialSignals = {};
  93859. return _this;
  93860. }
  93861. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  93862. var _this = this;
  93863. return this._loadExtensionAsync(context, node, function (context, extension) {
  93864. var firstPromise;
  93865. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  93866. var _loop_1 = function (indexLOD) {
  93867. var nodeLOD = nodeLODs[indexLOD];
  93868. if (indexLOD !== 0) {
  93869. _this._loadingNodeLOD = nodeLOD;
  93870. if (!_this._loadNodeSignals[nodeLOD._index]) {
  93871. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  93872. }
  93873. }
  93874. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  93875. if (indexLOD !== 0) {
  93876. var previousNodeLOD = nodeLODs[indexLOD - 1];
  93877. previousNodeLOD._babylonMesh.setEnabled(false);
  93878. }
  93879. if (indexLOD !== nodeLODs.length - 1) {
  93880. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  93881. if (_this._loadNodeSignals[nodeIndex]) {
  93882. _this._loadNodeSignals[nodeIndex].resolve();
  93883. delete _this._loadNodeSignals[nodeIndex];
  93884. }
  93885. }
  93886. });
  93887. if (indexLOD === 0) {
  93888. firstPromise = promise;
  93889. }
  93890. else {
  93891. _this._loader._completePromises.push(promise);
  93892. _this._loadingNodeLOD = null;
  93893. }
  93894. };
  93895. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  93896. _loop_1(indexLOD);
  93897. }
  93898. return firstPromise;
  93899. });
  93900. };
  93901. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  93902. var _this = this;
  93903. // Don't load material LODs if already loading a node LOD.
  93904. if (this._loadingNodeLOD) {
  93905. return null;
  93906. }
  93907. return this._loadExtensionAsync(context, material, function (context, extension) {
  93908. var firstPromise;
  93909. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  93910. var _loop_2 = function (indexLOD) {
  93911. var materialLOD = materialLODs[indexLOD];
  93912. if (indexLOD !== 0) {
  93913. _this._loadingMaterialLOD = materialLOD;
  93914. if (!_this._loadMaterialSignals[materialLOD._index]) {
  93915. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  93916. }
  93917. }
  93918. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  93919. if (indexLOD !== 0) {
  93920. assign(materialLOD._babylonMaterial);
  93921. }
  93922. if (indexLOD !== materialLODs.length - 1) {
  93923. var materialIndex = materialLODs[indexLOD + 1]._index;
  93924. if (_this._loadMaterialSignals[materialIndex]) {
  93925. _this._loadMaterialSignals[materialIndex].resolve();
  93926. delete _this._loadMaterialSignals[materialIndex];
  93927. }
  93928. }
  93929. });
  93930. if (indexLOD === 0) {
  93931. firstPromise = promise;
  93932. }
  93933. else {
  93934. _this._loader._completePromises.push(promise);
  93935. _this._loadingMaterialLOD = null;
  93936. }
  93937. };
  93938. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  93939. _loop_2(indexLOD);
  93940. }
  93941. return firstPromise;
  93942. });
  93943. };
  93944. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  93945. var _this = this;
  93946. // Defer the loading of uris if loading a material or node LOD.
  93947. if (this._loadingMaterialLOD) {
  93948. var index = this._loadingMaterialLOD._index;
  93949. return this._loadMaterialSignals[index].promise.then(function () {
  93950. return _this._loader._loadUriAsync(context, uri);
  93951. });
  93952. }
  93953. else if (this._loadingNodeLOD) {
  93954. var index = this._loadingNodeLOD._index;
  93955. return this._loadNodeSignals[index].promise.then(function () {
  93956. return _this._loader._loadUriAsync(context, uri);
  93957. });
  93958. }
  93959. return null;
  93960. };
  93961. /**
  93962. * Gets an array of LOD properties from lowest to highest.
  93963. */
  93964. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  93965. if (this.maxLODsToLoad <= 0) {
  93966. throw new Error("maxLODsToLoad must be greater than zero");
  93967. }
  93968. var properties = new Array();
  93969. for (var i = ids.length - 1; i >= 0; i--) {
  93970. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  93971. if (properties.length === this.maxLODsToLoad) {
  93972. return properties;
  93973. }
  93974. }
  93975. properties.push(property);
  93976. return properties;
  93977. };
  93978. return MSFT_lod;
  93979. }(GLTF2.GLTFLoaderExtension));
  93980. Extensions.MSFT_lod = MSFT_lod;
  93981. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  93982. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93983. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93984. })(BABYLON || (BABYLON = {}));
  93985. //# sourceMappingURL=MSFT_lod.js.map
  93986. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93987. var BABYLON;
  93988. (function (BABYLON) {
  93989. var GLTF2;
  93990. (function (GLTF2) {
  93991. var Extensions;
  93992. (function (Extensions) {
  93993. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  93994. var NAME = "KHR_draco_mesh_compression";
  93995. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  93996. __extends(KHR_draco_mesh_compression, _super);
  93997. function KHR_draco_mesh_compression(loader) {
  93998. var _this = _super.call(this, loader) || this;
  93999. _this.name = NAME;
  94000. _this._dracoCompression = null;
  94001. // Disable extension if decoder is not available.
  94002. if (!BABYLON.DracoCompression.DecoderUrl) {
  94003. _this.enabled = false;
  94004. }
  94005. return _this;
  94006. }
  94007. KHR_draco_mesh_compression.prototype.dispose = function () {
  94008. if (this._dracoCompression) {
  94009. this._dracoCompression.dispose();
  94010. }
  94011. _super.prototype.dispose.call(this);
  94012. };
  94013. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94014. var _this = this;
  94015. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  94016. if (primitive.mode != undefined) {
  94017. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  94018. primitive.mode !== 4 /* TRIANGLES */) {
  94019. throw new Error(context + ": Unsupported mode " + primitive.mode);
  94020. }
  94021. // TODO: handle triangle strips
  94022. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  94023. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  94024. }
  94025. }
  94026. var attributes = {};
  94027. var loadAttribute = function (name, kind) {
  94028. var uniqueId = extension.attributes[name];
  94029. if (uniqueId == undefined) {
  94030. return;
  94031. }
  94032. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94033. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94034. babylonMesh._delayInfo.push(kind);
  94035. }
  94036. attributes[kind] = uniqueId;
  94037. };
  94038. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94039. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94040. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94041. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94042. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94043. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94044. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94045. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94046. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  94047. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  94048. try {
  94049. if (!_this._dracoCompression) {
  94050. _this._dracoCompression = new BABYLON.DracoCompression();
  94051. }
  94052. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  94053. }
  94054. catch (e) {
  94055. throw new Error(context + ": " + e.message);
  94056. }
  94057. });
  94058. });
  94059. };
  94060. return KHR_draco_mesh_compression;
  94061. }(GLTF2.GLTFLoaderExtension));
  94062. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  94063. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  94064. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94065. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94066. })(BABYLON || (BABYLON = {}));
  94067. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  94068. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94069. var BABYLON;
  94070. (function (BABYLON) {
  94071. var GLTF2;
  94072. (function (GLTF2) {
  94073. var Extensions;
  94074. (function (Extensions) {
  94075. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  94076. var NAME = "KHR_materials_pbrSpecularGlossiness";
  94077. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  94078. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  94079. function KHR_materials_pbrSpecularGlossiness() {
  94080. var _this = _super !== null && _super.apply(this, arguments) || this;
  94081. _this.name = NAME;
  94082. return _this;
  94083. }
  94084. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  94085. var _this = this;
  94086. return this._loadExtensionAsync(context, material, function (context, extension) {
  94087. material._babylonMeshes = material._babylonMeshes || [];
  94088. material._babylonMeshes.push(babylonMesh);
  94089. if (!material._loaded) {
  94090. var promises = new Array();
  94091. var babylonMaterial = _this._loader._createMaterial(material);
  94092. material._babylonMaterial = babylonMaterial;
  94093. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  94094. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  94095. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94096. material._loaded = Promise.all(promises).then(function () { });
  94097. }
  94098. assign(material._babylonMaterial);
  94099. return material._loaded;
  94100. });
  94101. };
  94102. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  94103. var promises = new Array();
  94104. var babylonMaterial = material._babylonMaterial;
  94105. if (properties.diffuseFactor) {
  94106. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  94107. babylonMaterial.alpha = properties.diffuseFactor[3];
  94108. }
  94109. else {
  94110. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94111. }
  94112. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  94113. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  94114. if (properties.diffuseTexture) {
  94115. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  94116. babylonMaterial.albedoTexture = texture;
  94117. }));
  94118. }
  94119. if (properties.specularGlossinessTexture) {
  94120. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  94121. babylonMaterial.reflectivityTexture = texture;
  94122. }));
  94123. babylonMaterial.reflectivityTexture.hasAlpha = true;
  94124. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  94125. }
  94126. this._loader._loadMaterialAlphaProperties(context, material);
  94127. return Promise.all(promises).then(function () { });
  94128. };
  94129. return KHR_materials_pbrSpecularGlossiness;
  94130. }(GLTF2.GLTFLoaderExtension));
  94131. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  94132. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  94133. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94134. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94135. })(BABYLON || (BABYLON = {}));
  94136. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  94137. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  94138. var BABYLON;
  94139. (function (BABYLON) {
  94140. var GLTF2;
  94141. (function (GLTF2) {
  94142. var Extensions;
  94143. (function (Extensions) {
  94144. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  94145. var NAME = "KHR_lights";
  94146. var LightType;
  94147. (function (LightType) {
  94148. LightType["AMBIENT"] = "ambient";
  94149. LightType["DIRECTIONAL"] = "directional";
  94150. LightType["POINT"] = "point";
  94151. LightType["SPOT"] = "spot";
  94152. })(LightType || (LightType = {}));
  94153. var KHR_lights = /** @class */ (function (_super) {
  94154. __extends(KHR_lights, _super);
  94155. function KHR_lights() {
  94156. var _this = _super !== null && _super.apply(this, arguments) || this;
  94157. _this.name = NAME;
  94158. return _this;
  94159. }
  94160. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  94161. var _this = this;
  94162. return this._loadExtensionAsync(context, scene, function (context, extension) {
  94163. var promise = _this._loader._loadSceneAsync(context, scene);
  94164. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94165. if (light.type !== LightType.AMBIENT) {
  94166. throw new Error(context + ": Only ambient lights are allowed on a scene");
  94167. }
  94168. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  94169. return promise;
  94170. });
  94171. };
  94172. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  94173. var _this = this;
  94174. return this._loadExtensionAsync(context, node, function (context, extension) {
  94175. var promise = _this._loader._loadNodeAsync(context, node);
  94176. var babylonLight;
  94177. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  94178. var name = node._babylonMesh.name;
  94179. switch (light.type) {
  94180. case LightType.AMBIENT: {
  94181. throw new Error(context + ": Ambient lights are not allowed on a node");
  94182. }
  94183. case LightType.DIRECTIONAL: {
  94184. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  94185. break;
  94186. }
  94187. case LightType.POINT: {
  94188. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  94189. break;
  94190. }
  94191. case LightType.SPOT: {
  94192. var spotLight = light;
  94193. // TODO: support inner and outer cone angles
  94194. //const innerConeAngle = spotLight.innerConeAngle || 0;
  94195. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  94196. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  94197. break;
  94198. }
  94199. default: {
  94200. throw new Error(context + ": Invalid light type " + light.type);
  94201. }
  94202. }
  94203. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  94204. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  94205. babylonLight.parent = node._babylonMesh;
  94206. return promise;
  94207. });
  94208. };
  94209. Object.defineProperty(KHR_lights.prototype, "_lights", {
  94210. get: function () {
  94211. var extensions = this._loader._gltf.extensions;
  94212. if (!extensions || !extensions[this.name]) {
  94213. throw new Error("#/extensions: " + this.name + " not found");
  94214. }
  94215. var extension = extensions[this.name];
  94216. return extension.lights;
  94217. },
  94218. enumerable: true,
  94219. configurable: true
  94220. });
  94221. return KHR_lights;
  94222. }(GLTF2.GLTFLoaderExtension));
  94223. Extensions.KHR_lights = KHR_lights;
  94224. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  94225. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  94226. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  94227. })(BABYLON || (BABYLON = {}));
  94228. //# sourceMappingURL=KHR_lights.js.map
  94229. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  94230. globalObject["BABYLON"] = BABYLON;
  94231. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  94232. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,SharpenPostProcess,ChromaticAberrationPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };