es6.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746
  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. return InternalPromise;
  9457. }());
  9458. /**
  9459. * Helper class that provides a small promise polyfill
  9460. */
  9461. var PromisePolyfill = /** @class */ (function () {
  9462. function PromisePolyfill() {
  9463. }
  9464. /**
  9465. * Static function used to check if the polyfill is required
  9466. * If this is the case then the function will inject the polyfill to window.Promise
  9467. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9468. */
  9469. PromisePolyfill.Apply = function (force) {
  9470. if (force === void 0) { force = false; }
  9471. if (force || typeof Promise === 'undefined') {
  9472. var root = window;
  9473. root.Promise = InternalPromise;
  9474. }
  9475. };
  9476. return PromisePolyfill;
  9477. }());
  9478. BABYLON.PromisePolyfill = PromisePolyfill;
  9479. })(BABYLON || (BABYLON = {}));
  9480. //# sourceMappingURL=babylon.promise.js.map
  9481. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9482. var BABYLON;
  9483. (function (BABYLON) {
  9484. /**
  9485. * Helper class to push actions to a pool of workers.
  9486. */
  9487. var WorkerPool = /** @class */ (function () {
  9488. /**
  9489. * Constructor
  9490. * @param workers Array of workers to use for actions
  9491. */
  9492. function WorkerPool(workers) {
  9493. this._pendingActions = new Array();
  9494. this._workerInfos = workers.map(function (worker) { return ({
  9495. worker: worker,
  9496. active: false
  9497. }); });
  9498. }
  9499. /**
  9500. * Terminates all workers and clears any pending actions.
  9501. */
  9502. WorkerPool.prototype.dispose = function () {
  9503. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9504. var workerInfo = _a[_i];
  9505. workerInfo.worker.terminate();
  9506. }
  9507. delete this._workerInfos;
  9508. delete this._pendingActions;
  9509. };
  9510. /**
  9511. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9512. * pended until a worker has completed its action.
  9513. * @param action The action to perform. Call onComplete when the action is complete.
  9514. */
  9515. WorkerPool.prototype.push = function (action) {
  9516. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9517. var workerInfo = _a[_i];
  9518. if (!workerInfo.active) {
  9519. this._execute(workerInfo, action);
  9520. return;
  9521. }
  9522. }
  9523. this._pendingActions.push(action);
  9524. };
  9525. WorkerPool.prototype._execute = function (workerInfo, action) {
  9526. var _this = this;
  9527. workerInfo.active = true;
  9528. action(workerInfo.worker, function () {
  9529. workerInfo.active = false;
  9530. var nextAction = _this._pendingActions.shift();
  9531. if (nextAction) {
  9532. _this._execute(workerInfo, nextAction);
  9533. }
  9534. });
  9535. };
  9536. return WorkerPool;
  9537. }());
  9538. BABYLON.WorkerPool = WorkerPool;
  9539. })(BABYLON || (BABYLON = {}));
  9540. //# sourceMappingURL=babylon.workerPool.js.map
  9541. var BABYLON;
  9542. (function (BABYLON) {
  9543. var _AlphaState = /** @class */ (function () {
  9544. /**
  9545. * Initializes the state.
  9546. */
  9547. function _AlphaState() {
  9548. this._isAlphaBlendDirty = false;
  9549. this._isBlendFunctionParametersDirty = false;
  9550. this._isBlendEquationParametersDirty = false;
  9551. this._isBlendConstantsDirty = false;
  9552. this._alphaBlend = false;
  9553. this._blendFunctionParameters = new Array(4);
  9554. this._blendEquationParameters = new Array(2);
  9555. this._blendConstants = new Array(4);
  9556. this.reset();
  9557. }
  9558. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9559. get: function () {
  9560. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9561. },
  9562. enumerable: true,
  9563. configurable: true
  9564. });
  9565. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9566. get: function () {
  9567. return this._alphaBlend;
  9568. },
  9569. set: function (value) {
  9570. if (this._alphaBlend === value) {
  9571. return;
  9572. }
  9573. this._alphaBlend = value;
  9574. this._isAlphaBlendDirty = true;
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9580. if (this._blendConstants[0] === r &&
  9581. this._blendConstants[1] === g &&
  9582. this._blendConstants[2] === b &&
  9583. this._blendConstants[3] === a) {
  9584. return;
  9585. }
  9586. this._blendConstants[0] = r;
  9587. this._blendConstants[1] = g;
  9588. this._blendConstants[2] = b;
  9589. this._blendConstants[3] = a;
  9590. this._isBlendConstantsDirty = true;
  9591. };
  9592. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9593. if (this._blendFunctionParameters[0] === value0 &&
  9594. this._blendFunctionParameters[1] === value1 &&
  9595. this._blendFunctionParameters[2] === value2 &&
  9596. this._blendFunctionParameters[3] === value3) {
  9597. return;
  9598. }
  9599. this._blendFunctionParameters[0] = value0;
  9600. this._blendFunctionParameters[1] = value1;
  9601. this._blendFunctionParameters[2] = value2;
  9602. this._blendFunctionParameters[3] = value3;
  9603. this._isBlendFunctionParametersDirty = true;
  9604. };
  9605. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9606. if (this._blendEquationParameters[0] === rgb &&
  9607. this._blendEquationParameters[1] === alpha) {
  9608. return;
  9609. }
  9610. this._blendEquationParameters[0] = rgb;
  9611. this._blendEquationParameters[1] = alpha;
  9612. this._isBlendEquationParametersDirty = true;
  9613. };
  9614. _AlphaState.prototype.reset = function () {
  9615. this._alphaBlend = false;
  9616. this._blendFunctionParameters[0] = null;
  9617. this._blendFunctionParameters[1] = null;
  9618. this._blendFunctionParameters[2] = null;
  9619. this._blendFunctionParameters[3] = null;
  9620. this._blendEquationParameters[0] = null;
  9621. this._blendEquationParameters[1] = null;
  9622. this._blendConstants[0] = null;
  9623. this._blendConstants[1] = null;
  9624. this._blendConstants[2] = null;
  9625. this._blendConstants[3] = null;
  9626. this._isAlphaBlendDirty = true;
  9627. this._isBlendFunctionParametersDirty = false;
  9628. this._isBlendEquationParametersDirty = false;
  9629. this._isBlendConstantsDirty = false;
  9630. };
  9631. _AlphaState.prototype.apply = function (gl) {
  9632. if (!this.isDirty) {
  9633. return;
  9634. }
  9635. // Alpha blend
  9636. if (this._isAlphaBlendDirty) {
  9637. if (this._alphaBlend) {
  9638. gl.enable(gl.BLEND);
  9639. }
  9640. else {
  9641. gl.disable(gl.BLEND);
  9642. }
  9643. this._isAlphaBlendDirty = false;
  9644. }
  9645. // Alpha function
  9646. if (this._isBlendFunctionParametersDirty) {
  9647. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9648. this._isBlendFunctionParametersDirty = false;
  9649. }
  9650. // Alpha equation
  9651. if (this._isBlendEquationParametersDirty) {
  9652. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9653. this._isBlendEquationParametersDirty = false;
  9654. }
  9655. // Constants
  9656. if (this._isBlendConstantsDirty) {
  9657. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9658. this._isBlendConstantsDirty = false;
  9659. }
  9660. };
  9661. return _AlphaState;
  9662. }());
  9663. BABYLON._AlphaState = _AlphaState;
  9664. })(BABYLON || (BABYLON = {}));
  9665. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9666. var BABYLON;
  9667. (function (BABYLON) {
  9668. var _DepthCullingState = /** @class */ (function () {
  9669. /**
  9670. * Initializes the state.
  9671. */
  9672. function _DepthCullingState() {
  9673. this._isDepthTestDirty = false;
  9674. this._isDepthMaskDirty = false;
  9675. this._isDepthFuncDirty = false;
  9676. this._isCullFaceDirty = false;
  9677. this._isCullDirty = false;
  9678. this._isZOffsetDirty = false;
  9679. this._isFrontFaceDirty = false;
  9680. this.reset();
  9681. }
  9682. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9683. get: function () {
  9684. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9690. get: function () {
  9691. return this._zOffset;
  9692. },
  9693. set: function (value) {
  9694. if (this._zOffset === value) {
  9695. return;
  9696. }
  9697. this._zOffset = value;
  9698. this._isZOffsetDirty = true;
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9704. get: function () {
  9705. return this._cullFace;
  9706. },
  9707. set: function (value) {
  9708. if (this._cullFace === value) {
  9709. return;
  9710. }
  9711. this._cullFace = value;
  9712. this._isCullFaceDirty = true;
  9713. },
  9714. enumerable: true,
  9715. configurable: true
  9716. });
  9717. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9718. get: function () {
  9719. return this._cull;
  9720. },
  9721. set: function (value) {
  9722. if (this._cull === value) {
  9723. return;
  9724. }
  9725. this._cull = value;
  9726. this._isCullDirty = true;
  9727. },
  9728. enumerable: true,
  9729. configurable: true
  9730. });
  9731. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9732. get: function () {
  9733. return this._depthFunc;
  9734. },
  9735. set: function (value) {
  9736. if (this._depthFunc === value) {
  9737. return;
  9738. }
  9739. this._depthFunc = value;
  9740. this._isDepthFuncDirty = true;
  9741. },
  9742. enumerable: true,
  9743. configurable: true
  9744. });
  9745. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9746. get: function () {
  9747. return this._depthMask;
  9748. },
  9749. set: function (value) {
  9750. if (this._depthMask === value) {
  9751. return;
  9752. }
  9753. this._depthMask = value;
  9754. this._isDepthMaskDirty = true;
  9755. },
  9756. enumerable: true,
  9757. configurable: true
  9758. });
  9759. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9760. get: function () {
  9761. return this._depthTest;
  9762. },
  9763. set: function (value) {
  9764. if (this._depthTest === value) {
  9765. return;
  9766. }
  9767. this._depthTest = value;
  9768. this._isDepthTestDirty = true;
  9769. },
  9770. enumerable: true,
  9771. configurable: true
  9772. });
  9773. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9774. get: function () {
  9775. return this._frontFace;
  9776. },
  9777. set: function (value) {
  9778. if (this._frontFace === value) {
  9779. return;
  9780. }
  9781. this._frontFace = value;
  9782. this._isFrontFaceDirty = true;
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. _DepthCullingState.prototype.reset = function () {
  9788. this._depthMask = true;
  9789. this._depthTest = true;
  9790. this._depthFunc = null;
  9791. this._cullFace = null;
  9792. this._cull = null;
  9793. this._zOffset = 0;
  9794. this._frontFace = null;
  9795. this._isDepthTestDirty = true;
  9796. this._isDepthMaskDirty = true;
  9797. this._isDepthFuncDirty = false;
  9798. this._isCullFaceDirty = false;
  9799. this._isCullDirty = false;
  9800. this._isZOffsetDirty = false;
  9801. this._isFrontFaceDirty = false;
  9802. };
  9803. _DepthCullingState.prototype.apply = function (gl) {
  9804. if (!this.isDirty) {
  9805. return;
  9806. }
  9807. // Cull
  9808. if (this._isCullDirty) {
  9809. if (this.cull) {
  9810. gl.enable(gl.CULL_FACE);
  9811. }
  9812. else {
  9813. gl.disable(gl.CULL_FACE);
  9814. }
  9815. this._isCullDirty = false;
  9816. }
  9817. // Cull face
  9818. if (this._isCullFaceDirty) {
  9819. gl.cullFace(this.cullFace);
  9820. this._isCullFaceDirty = false;
  9821. }
  9822. // Depth mask
  9823. if (this._isDepthMaskDirty) {
  9824. gl.depthMask(this.depthMask);
  9825. this._isDepthMaskDirty = false;
  9826. }
  9827. // Depth test
  9828. if (this._isDepthTestDirty) {
  9829. if (this.depthTest) {
  9830. gl.enable(gl.DEPTH_TEST);
  9831. }
  9832. else {
  9833. gl.disable(gl.DEPTH_TEST);
  9834. }
  9835. this._isDepthTestDirty = false;
  9836. }
  9837. // Depth func
  9838. if (this._isDepthFuncDirty) {
  9839. gl.depthFunc(this.depthFunc);
  9840. this._isDepthFuncDirty = false;
  9841. }
  9842. // zOffset
  9843. if (this._isZOffsetDirty) {
  9844. if (this.zOffset) {
  9845. gl.enable(gl.POLYGON_OFFSET_FILL);
  9846. gl.polygonOffset(this.zOffset, 0);
  9847. }
  9848. else {
  9849. gl.disable(gl.POLYGON_OFFSET_FILL);
  9850. }
  9851. this._isZOffsetDirty = false;
  9852. }
  9853. // Front face
  9854. if (this._isFrontFaceDirty) {
  9855. gl.frontFace(this.frontFace);
  9856. this._isFrontFaceDirty = false;
  9857. }
  9858. };
  9859. return _DepthCullingState;
  9860. }());
  9861. BABYLON._DepthCullingState = _DepthCullingState;
  9862. })(BABYLON || (BABYLON = {}));
  9863. //# sourceMappingURL=babylon.depthCullingState.js.map
  9864. var BABYLON;
  9865. (function (BABYLON) {
  9866. var _StencilState = /** @class */ (function () {
  9867. function _StencilState() {
  9868. this._isStencilTestDirty = false;
  9869. this._isStencilMaskDirty = false;
  9870. this._isStencilFuncDirty = false;
  9871. this._isStencilOpDirty = false;
  9872. this.reset();
  9873. }
  9874. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9875. get: function () {
  9876. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9882. get: function () {
  9883. return this._stencilFunc;
  9884. },
  9885. set: function (value) {
  9886. if (this._stencilFunc === value) {
  9887. return;
  9888. }
  9889. this._stencilFunc = value;
  9890. this._isStencilFuncDirty = true;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9896. get: function () {
  9897. return this._stencilFuncRef;
  9898. },
  9899. set: function (value) {
  9900. if (this._stencilFuncRef === value) {
  9901. return;
  9902. }
  9903. this._stencilFuncRef = value;
  9904. this._isStencilFuncDirty = true;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9910. get: function () {
  9911. return this._stencilFuncMask;
  9912. },
  9913. set: function (value) {
  9914. if (this._stencilFuncMask === value) {
  9915. return;
  9916. }
  9917. this._stencilFuncMask = value;
  9918. this._isStencilFuncDirty = true;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9924. get: function () {
  9925. return this._stencilOpStencilFail;
  9926. },
  9927. set: function (value) {
  9928. if (this._stencilOpStencilFail === value) {
  9929. return;
  9930. }
  9931. this._stencilOpStencilFail = value;
  9932. this._isStencilOpDirty = true;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9938. get: function () {
  9939. return this._stencilOpDepthFail;
  9940. },
  9941. set: function (value) {
  9942. if (this._stencilOpDepthFail === value) {
  9943. return;
  9944. }
  9945. this._stencilOpDepthFail = value;
  9946. this._isStencilOpDirty = true;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9952. get: function () {
  9953. return this._stencilOpStencilDepthPass;
  9954. },
  9955. set: function (value) {
  9956. if (this._stencilOpStencilDepthPass === value) {
  9957. return;
  9958. }
  9959. this._stencilOpStencilDepthPass = value;
  9960. this._isStencilOpDirty = true;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9966. get: function () {
  9967. return this._stencilMask;
  9968. },
  9969. set: function (value) {
  9970. if (this._stencilMask === value) {
  9971. return;
  9972. }
  9973. this._stencilMask = value;
  9974. this._isStencilMaskDirty = true;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9980. get: function () {
  9981. return this._stencilTest;
  9982. },
  9983. set: function (value) {
  9984. if (this._stencilTest === value) {
  9985. return;
  9986. }
  9987. this._stencilTest = value;
  9988. this._isStencilTestDirty = true;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. _StencilState.prototype.reset = function () {
  9994. this._stencilTest = false;
  9995. this._stencilMask = 0xFF;
  9996. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9997. this._stencilFuncRef = 1;
  9998. this._stencilFuncMask = 0xFF;
  9999. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10000. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10001. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10002. this._isStencilTestDirty = true;
  10003. this._isStencilMaskDirty = true;
  10004. this._isStencilFuncDirty = true;
  10005. this._isStencilOpDirty = true;
  10006. };
  10007. _StencilState.prototype.apply = function (gl) {
  10008. if (!this.isDirty) {
  10009. return;
  10010. }
  10011. // Stencil test
  10012. if (this._isStencilTestDirty) {
  10013. if (this.stencilTest) {
  10014. gl.enable(gl.STENCIL_TEST);
  10015. }
  10016. else {
  10017. gl.disable(gl.STENCIL_TEST);
  10018. }
  10019. this._isStencilTestDirty = false;
  10020. }
  10021. // Stencil mask
  10022. if (this._isStencilMaskDirty) {
  10023. gl.stencilMask(this.stencilMask);
  10024. this._isStencilMaskDirty = false;
  10025. }
  10026. // Stencil func
  10027. if (this._isStencilFuncDirty) {
  10028. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10029. this._isStencilFuncDirty = false;
  10030. }
  10031. // Stencil op
  10032. if (this._isStencilOpDirty) {
  10033. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10034. this._isStencilOpDirty = false;
  10035. }
  10036. };
  10037. return _StencilState;
  10038. }());
  10039. BABYLON._StencilState = _StencilState;
  10040. })(BABYLON || (BABYLON = {}));
  10041. //# sourceMappingURL=babylon.stencilState.js.map
  10042. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10043. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10044. s = arguments[i];
  10045. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10046. t[p] = s[p];
  10047. }
  10048. return t;
  10049. };
  10050. var BABYLON;
  10051. (function (BABYLON) {
  10052. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10053. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10054. };
  10055. var compileRawShader = function (gl, source, type) {
  10056. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10057. gl.shaderSource(shader, source);
  10058. gl.compileShader(shader);
  10059. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10060. var log = gl.getShaderInfoLog(shader);
  10061. if (log) {
  10062. throw new Error(log);
  10063. }
  10064. }
  10065. if (!shader) {
  10066. throw new Error("Something went wrong while compile the shader.");
  10067. }
  10068. return shader;
  10069. };
  10070. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10071. var magFilter = gl.NEAREST;
  10072. var minFilter = gl.NEAREST;
  10073. switch (samplingMode) {
  10074. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10075. magFilter = gl.LINEAR;
  10076. if (generateMipMaps) {
  10077. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10078. }
  10079. else {
  10080. minFilter = gl.LINEAR;
  10081. }
  10082. break;
  10083. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10084. magFilter = gl.LINEAR;
  10085. if (generateMipMaps) {
  10086. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10087. }
  10088. else {
  10089. minFilter = gl.LINEAR;
  10090. }
  10091. break;
  10092. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10093. magFilter = gl.NEAREST;
  10094. if (generateMipMaps) {
  10095. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10096. }
  10097. else {
  10098. minFilter = gl.NEAREST;
  10099. }
  10100. break;
  10101. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10102. magFilter = gl.NEAREST;
  10103. if (generateMipMaps) {
  10104. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10105. }
  10106. else {
  10107. minFilter = gl.NEAREST;
  10108. }
  10109. break;
  10110. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10111. magFilter = gl.NEAREST;
  10112. if (generateMipMaps) {
  10113. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10114. }
  10115. else {
  10116. minFilter = gl.LINEAR;
  10117. }
  10118. break;
  10119. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10120. magFilter = gl.NEAREST;
  10121. if (generateMipMaps) {
  10122. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10123. }
  10124. else {
  10125. minFilter = gl.LINEAR;
  10126. }
  10127. break;
  10128. case BABYLON.Texture.NEAREST_LINEAR:
  10129. magFilter = gl.NEAREST;
  10130. minFilter = gl.LINEAR;
  10131. break;
  10132. case BABYLON.Texture.NEAREST_NEAREST:
  10133. magFilter = gl.NEAREST;
  10134. minFilter = gl.NEAREST;
  10135. break;
  10136. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10137. magFilter = gl.LINEAR;
  10138. if (generateMipMaps) {
  10139. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10140. }
  10141. else {
  10142. minFilter = gl.NEAREST;
  10143. }
  10144. break;
  10145. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10146. magFilter = gl.LINEAR;
  10147. if (generateMipMaps) {
  10148. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10149. }
  10150. else {
  10151. minFilter = gl.NEAREST;
  10152. }
  10153. break;
  10154. case BABYLON.Texture.LINEAR_LINEAR:
  10155. magFilter = gl.LINEAR;
  10156. minFilter = gl.LINEAR;
  10157. break;
  10158. case BABYLON.Texture.LINEAR_NEAREST:
  10159. magFilter = gl.LINEAR;
  10160. minFilter = gl.NEAREST;
  10161. break;
  10162. }
  10163. return {
  10164. min: minFilter,
  10165. mag: magFilter
  10166. };
  10167. };
  10168. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10169. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10170. var img;
  10171. var onload = function () {
  10172. loadedImages[index] = img;
  10173. loadedImages._internalCount++;
  10174. if (scene) {
  10175. scene._removePendingData(img);
  10176. }
  10177. if (loadedImages._internalCount === 6) {
  10178. onfinish(loadedImages);
  10179. }
  10180. };
  10181. var onerror = function (message, exception) {
  10182. if (scene) {
  10183. scene._removePendingData(img);
  10184. }
  10185. if (onErrorCallBack) {
  10186. onErrorCallBack(message, exception);
  10187. }
  10188. };
  10189. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10190. if (scene) {
  10191. scene._addPendingData(img);
  10192. }
  10193. };
  10194. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10195. if (onError === void 0) { onError = null; }
  10196. var loadedImages = [];
  10197. loadedImages._internalCount = 0;
  10198. for (var index = 0; index < 6; index++) {
  10199. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10200. }
  10201. };
  10202. var BufferPointer = /** @class */ (function () {
  10203. function BufferPointer() {
  10204. }
  10205. return BufferPointer;
  10206. }());
  10207. var InstancingAttributeInfo = /** @class */ (function () {
  10208. function InstancingAttributeInfo() {
  10209. }
  10210. return InstancingAttributeInfo;
  10211. }());
  10212. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10213. /**
  10214. * Define options used to create a render target texture
  10215. */
  10216. var RenderTargetCreationOptions = /** @class */ (function () {
  10217. function RenderTargetCreationOptions() {
  10218. }
  10219. return RenderTargetCreationOptions;
  10220. }());
  10221. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10222. /**
  10223. * Define options used to create a depth texture
  10224. */
  10225. var DepthTextureCreationOptions = /** @class */ (function () {
  10226. function DepthTextureCreationOptions() {
  10227. }
  10228. return DepthTextureCreationOptions;
  10229. }());
  10230. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10231. /**
  10232. * Regroup several parameters relative to the browser in use
  10233. */
  10234. var EngineCapabilities = /** @class */ (function () {
  10235. function EngineCapabilities() {
  10236. }
  10237. return EngineCapabilities;
  10238. }());
  10239. BABYLON.EngineCapabilities = EngineCapabilities;
  10240. /**
  10241. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10242. */
  10243. var Engine = /** @class */ (function () {
  10244. /**
  10245. * @constructor
  10246. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10247. * @param antialias defines enable antialiasing (default: false)
  10248. * @param options defines further options to be sent to the getContext() function
  10249. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10250. */
  10251. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10252. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10253. var _this = this;
  10254. // Public members
  10255. this.forcePOTTextures = false;
  10256. this.isFullscreen = false;
  10257. this.isPointerLock = false;
  10258. this.cullBackFaces = true;
  10259. this.renderEvenInBackground = true;
  10260. this.preventCacheWipeBetweenFrames = false;
  10261. // To enable/disable IDB support and avoid XHR on .manifest
  10262. this.enableOfflineSupport = false;
  10263. this.scenes = new Array();
  10264. this.postProcesses = new Array();
  10265. // Observables
  10266. /**
  10267. * Observable event triggered each time the rendering canvas is resized
  10268. */
  10269. this.onResizeObservable = new BABYLON.Observable();
  10270. /**
  10271. * Observable event triggered each time the canvas loses focus
  10272. */
  10273. this.onCanvasBlurObservable = new BABYLON.Observable();
  10274. /**
  10275. * Observable event triggered each time the canvas gains focus
  10276. */
  10277. this.onCanvasFocusObservable = new BABYLON.Observable();
  10278. /**
  10279. * Observable event triggered each time the canvas receives pointerout event
  10280. */
  10281. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10282. /**
  10283. * Observable event triggered before each texture is initialized
  10284. */
  10285. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10286. //WebVR
  10287. this._vrDisplay = undefined;
  10288. this._vrSupported = false;
  10289. this._vrExclusivePointerMode = false;
  10290. // Uniform buffers list
  10291. this.disableUniformBuffers = false;
  10292. this._uniformBuffers = new Array();
  10293. // Observables
  10294. /**
  10295. * Observable raised when the engine begins a new frame
  10296. */
  10297. this.onBeginFrameObservable = new BABYLON.Observable();
  10298. /**
  10299. * Observable raised when the engine ends the current frame
  10300. */
  10301. this.onEndFrameObservable = new BABYLON.Observable();
  10302. /**
  10303. * Observable raised when the engine is about to compile a shader
  10304. */
  10305. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10306. /**
  10307. * Observable raised when the engine has jsut compiled a shader
  10308. */
  10309. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10310. this._windowIsBackground = false;
  10311. this._webGLVersion = 1.0;
  10312. this._badOS = false;
  10313. this._badDesktopOS = false;
  10314. /**
  10315. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10316. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10317. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10318. */
  10319. this.disableTextureBindingOptimization = false;
  10320. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10321. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10322. this.onVRRequestPresentStart = new BABYLON.Observable();
  10323. this._colorWrite = true;
  10324. this._drawCalls = new BABYLON.PerfCounter();
  10325. this._textureCollisions = new BABYLON.PerfCounter();
  10326. this._renderingQueueLaunched = false;
  10327. this._activeRenderLoops = new Array();
  10328. // Deterministic lockstepMaxSteps
  10329. this._deterministicLockstep = false;
  10330. this._lockstepMaxSteps = 4;
  10331. // Lost context
  10332. this.onContextLostObservable = new BABYLON.Observable();
  10333. this.onContextRestoredObservable = new BABYLON.Observable();
  10334. this._contextWasLost = false;
  10335. this._doNotHandleContextLost = false;
  10336. // FPS
  10337. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10338. this._fps = 60;
  10339. this._deltaTime = 0;
  10340. /**
  10341. * Turn this value on if you want to pause FPS computation when in background
  10342. */
  10343. this.disablePerformanceMonitorInBackground = false;
  10344. // States
  10345. this._depthCullingState = new BABYLON._DepthCullingState();
  10346. this._stencilState = new BABYLON._StencilState();
  10347. this._alphaState = new BABYLON._AlphaState();
  10348. this._alphaMode = Engine.ALPHA_DISABLE;
  10349. // Cache
  10350. this._internalTexturesCache = new Array();
  10351. this._activeChannel = 0;
  10352. this._currentTextureChannel = -1;
  10353. this._boundTexturesCache = {};
  10354. this._compiledEffects = {};
  10355. this._vertexAttribArraysEnabled = [];
  10356. this._uintIndicesCurrentlySet = false;
  10357. this._currentBoundBuffer = new Array();
  10358. this._currentBufferPointers = new Array();
  10359. this._currentInstanceLocations = new Array();
  10360. this._currentInstanceBuffers = new Array();
  10361. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10362. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10363. this._vaoRecordInProgress = false;
  10364. this._mustWipeVertexAttributes = false;
  10365. this._nextFreeTextureSlots = new Array();
  10366. this._maxSimultaneousTextures = 0;
  10367. this._activeRequests = new Array();
  10368. // Hardware supported Compressed Textures
  10369. this._texturesSupported = new Array();
  10370. this._onVRFullScreenTriggered = function () {
  10371. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10372. //get the old size before we change
  10373. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10374. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10375. //get the width and height, change the render size
  10376. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10377. _this.setHardwareScalingLevel(1);
  10378. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10379. }
  10380. else {
  10381. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10382. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10383. }
  10384. };
  10385. this._boundUniforms = {};
  10386. // Register promises
  10387. BABYLON.PromisePolyfill.Apply();
  10388. var canvas = null;
  10389. Engine.Instances.push(this);
  10390. if (!canvasOrContext) {
  10391. return;
  10392. }
  10393. options = options || {};
  10394. if (canvasOrContext.getContext) {
  10395. canvas = canvasOrContext;
  10396. this._renderingCanvas = canvas;
  10397. if (antialias != null) {
  10398. options.antialias = antialias;
  10399. }
  10400. if (options.deterministicLockstep === undefined) {
  10401. options.deterministicLockstep = false;
  10402. }
  10403. if (options.lockstepMaxSteps === undefined) {
  10404. options.lockstepMaxSteps = 4;
  10405. }
  10406. if (options.preserveDrawingBuffer === undefined) {
  10407. options.preserveDrawingBuffer = false;
  10408. }
  10409. if (options.audioEngine === undefined) {
  10410. options.audioEngine = true;
  10411. }
  10412. if (options.stencil === undefined) {
  10413. options.stencil = true;
  10414. }
  10415. this._deterministicLockstep = options.deterministicLockstep;
  10416. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10417. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10418. // Exceptions
  10419. if (navigator && navigator.userAgent) {
  10420. var ua = navigator.userAgent;
  10421. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10422. var exception = _a[_i];
  10423. var key = exception.key;
  10424. var targets = exception.targets;
  10425. if (ua.indexOf(key) > -1) {
  10426. if (exception.capture && exception.captureConstraint) {
  10427. var capture = exception.capture;
  10428. var constraint = exception.captureConstraint;
  10429. var regex = new RegExp(capture);
  10430. var matches = regex.exec(ua);
  10431. if (matches && matches.length > 0) {
  10432. var capturedValue = parseInt(matches[matches.length - 1]);
  10433. if (capturedValue >= constraint) {
  10434. continue;
  10435. }
  10436. }
  10437. }
  10438. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10439. var target = targets_1[_b];
  10440. switch (target) {
  10441. case "uniformBuffer":
  10442. this.disableUniformBuffers = true;
  10443. break;
  10444. case "textureBindingOptimization":
  10445. this.disableTextureBindingOptimization = true;
  10446. break;
  10447. }
  10448. }
  10449. break;
  10450. }
  10451. }
  10452. }
  10453. // GL
  10454. if (!options.disableWebGL2Support) {
  10455. try {
  10456. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10457. if (this._gl) {
  10458. this._webGLVersion = 2.0;
  10459. }
  10460. }
  10461. catch (e) {
  10462. // Do nothing
  10463. }
  10464. }
  10465. if (!this._gl) {
  10466. if (!canvas) {
  10467. throw new Error("The provided canvas is null or undefined.");
  10468. }
  10469. try {
  10470. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10471. }
  10472. catch (e) {
  10473. throw new Error("WebGL not supported");
  10474. }
  10475. }
  10476. if (!this._gl) {
  10477. throw new Error("WebGL not supported");
  10478. }
  10479. this._onCanvasFocus = function () {
  10480. _this.onCanvasFocusObservable.notifyObservers(_this);
  10481. };
  10482. this._onCanvasBlur = function () {
  10483. _this.onCanvasBlurObservable.notifyObservers(_this);
  10484. };
  10485. canvas.addEventListener("focus", this._onCanvasFocus);
  10486. canvas.addEventListener("blur", this._onCanvasBlur);
  10487. this._onBlur = function () {
  10488. if (_this.disablePerformanceMonitorInBackground) {
  10489. _this._performanceMonitor.disable();
  10490. }
  10491. _this._windowIsBackground = true;
  10492. };
  10493. this._onFocus = function () {
  10494. if (_this.disablePerformanceMonitorInBackground) {
  10495. _this._performanceMonitor.enable();
  10496. }
  10497. _this._windowIsBackground = false;
  10498. };
  10499. this._onCanvasPointerOut = function (ev) {
  10500. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10501. };
  10502. window.addEventListener("blur", this._onBlur);
  10503. window.addEventListener("focus", this._onFocus);
  10504. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10505. // Context lost
  10506. if (!this._doNotHandleContextLost) {
  10507. this._onContextLost = function (evt) {
  10508. evt.preventDefault();
  10509. _this._contextWasLost = true;
  10510. BABYLON.Tools.Warn("WebGL context lost.");
  10511. _this.onContextLostObservable.notifyObservers(_this);
  10512. };
  10513. this._onContextRestored = function (evt) {
  10514. // Adding a timeout to avoid race condition at browser level
  10515. setTimeout(function () {
  10516. // Rebuild gl context
  10517. _this._initGLContext();
  10518. // Rebuild effects
  10519. _this._rebuildEffects();
  10520. // Rebuild textures
  10521. _this._rebuildInternalTextures();
  10522. // Rebuild buffers
  10523. _this._rebuildBuffers();
  10524. // Cache
  10525. _this.wipeCaches(true);
  10526. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10527. _this.onContextRestoredObservable.notifyObservers(_this);
  10528. _this._contextWasLost = false;
  10529. }, 0);
  10530. };
  10531. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10532. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10533. }
  10534. }
  10535. else {
  10536. this._gl = canvasOrContext;
  10537. this._renderingCanvas = this._gl.canvas;
  10538. if (this._gl.renderbufferStorageMultisample) {
  10539. this._webGLVersion = 2.0;
  10540. }
  10541. options.stencil = this._gl.getContextAttributes().stencil;
  10542. }
  10543. // Viewport
  10544. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10545. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10546. this.resize();
  10547. this._isStencilEnable = options.stencil ? true : false;
  10548. this._initGLContext();
  10549. if (canvas) {
  10550. // Fullscreen
  10551. this._onFullscreenChange = function () {
  10552. if (document.fullscreen !== undefined) {
  10553. _this.isFullscreen = document.fullscreen;
  10554. }
  10555. else if (document.mozFullScreen !== undefined) {
  10556. _this.isFullscreen = document.mozFullScreen;
  10557. }
  10558. else if (document.webkitIsFullScreen !== undefined) {
  10559. _this.isFullscreen = document.webkitIsFullScreen;
  10560. }
  10561. else if (document.msIsFullScreen !== undefined) {
  10562. _this.isFullscreen = document.msIsFullScreen;
  10563. }
  10564. // Pointer lock
  10565. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10566. canvas.requestPointerLock = canvas.requestPointerLock ||
  10567. canvas.msRequestPointerLock ||
  10568. canvas.mozRequestPointerLock ||
  10569. canvas.webkitRequestPointerLock;
  10570. if (canvas.requestPointerLock) {
  10571. canvas.requestPointerLock();
  10572. }
  10573. }
  10574. };
  10575. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10576. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10577. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10578. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10579. // Pointer lock
  10580. this._onPointerLockChange = function () {
  10581. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10582. document.webkitPointerLockElement === canvas ||
  10583. document.msPointerLockElement === canvas ||
  10584. document.pointerLockElement === canvas);
  10585. };
  10586. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10587. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10588. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10589. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10590. this._onVRDisplayPointerRestricted = function () {
  10591. if (canvas) {
  10592. canvas.requestPointerLock();
  10593. }
  10594. };
  10595. this._onVRDisplayPointerUnrestricted = function () {
  10596. document.exitPointerLock();
  10597. };
  10598. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10599. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10600. }
  10601. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10602. Engine.audioEngine = new BABYLON.AudioEngine();
  10603. }
  10604. // Prepare buffer pointers
  10605. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10606. this._currentBufferPointers[i] = new BufferPointer();
  10607. }
  10608. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10609. // Load WebVR Devices
  10610. if (options.autoEnableWebVR) {
  10611. this.initWebVR();
  10612. }
  10613. // Detect if we are running on a faulty buggy OS.
  10614. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10615. // Detect if we are running on a faulty buggy desktop OS.
  10616. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10617. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10618. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10619. }
  10620. Object.defineProperty(Engine, "LastCreatedEngine", {
  10621. get: function () {
  10622. if (Engine.Instances.length === 0) {
  10623. return null;
  10624. }
  10625. return Engine.Instances[Engine.Instances.length - 1];
  10626. },
  10627. enumerable: true,
  10628. configurable: true
  10629. });
  10630. Object.defineProperty(Engine, "LastCreatedScene", {
  10631. get: function () {
  10632. var lastCreatedEngine = Engine.LastCreatedEngine;
  10633. if (!lastCreatedEngine) {
  10634. return null;
  10635. }
  10636. if (lastCreatedEngine.scenes.length === 0) {
  10637. return null;
  10638. }
  10639. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10640. },
  10641. enumerable: true,
  10642. configurable: true
  10643. });
  10644. /**
  10645. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10646. */
  10647. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10648. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10649. var engine = Engine.Instances[engineIndex];
  10650. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10651. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10652. }
  10653. }
  10654. };
  10655. Object.defineProperty(Engine, "NEVER", {
  10656. get: function () {
  10657. return Engine._NEVER;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(Engine, "ALWAYS", {
  10663. get: function () {
  10664. return Engine._ALWAYS;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(Engine, "LESS", {
  10670. get: function () {
  10671. return Engine._LESS;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "EQUAL", {
  10677. get: function () {
  10678. return Engine._EQUAL;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "LEQUAL", {
  10684. get: function () {
  10685. return Engine._LEQUAL;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "GREATER", {
  10691. get: function () {
  10692. return Engine._GREATER;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "GEQUAL", {
  10698. get: function () {
  10699. return Engine._GEQUAL;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "NOTEQUAL", {
  10705. get: function () {
  10706. return Engine._NOTEQUAL;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "KEEP", {
  10712. get: function () {
  10713. return Engine._KEEP;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "REPLACE", {
  10719. get: function () {
  10720. return Engine._REPLACE;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "INCR", {
  10726. get: function () {
  10727. return Engine._INCR;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "DECR", {
  10733. get: function () {
  10734. return Engine._DECR;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "INVERT", {
  10740. get: function () {
  10741. return Engine._INVERT;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "INCR_WRAP", {
  10747. get: function () {
  10748. return Engine._INCR_WRAP;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "DECR_WRAP", {
  10754. get: function () {
  10755. return Engine._DECR_WRAP;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10761. get: function () {
  10762. return Engine._ALPHA_DISABLE;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10768. get: function () {
  10769. return Engine._ALPHA_ONEONE;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "ALPHA_ADD", {
  10775. get: function () {
  10776. return Engine._ALPHA_ADD;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10782. get: function () {
  10783. return Engine._ALPHA_COMBINE;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10789. get: function () {
  10790. return Engine._ALPHA_SUBTRACT;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10796. get: function () {
  10797. return Engine._ALPHA_MULTIPLY;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10803. get: function () {
  10804. return Engine._ALPHA_MAXIMIZED;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10810. get: function () {
  10811. return Engine._ALPHA_PREMULTIPLIED;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10817. get: function () {
  10818. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10824. get: function () {
  10825. return Engine._ALPHA_INTERPOLATE;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10831. get: function () {
  10832. return Engine._ALPHA_SCREENMODE;
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10838. get: function () {
  10839. return Engine._DELAYLOADSTATE_NONE;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10845. get: function () {
  10846. return Engine._DELAYLOADSTATE_LOADED;
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10852. get: function () {
  10853. return Engine._DELAYLOADSTATE_LOADING;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10859. get: function () {
  10860. return Engine._DELAYLOADSTATE_NOTLOADED;
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10866. get: function () {
  10867. return Engine._TEXTUREFORMAT_ALPHA;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10873. get: function () {
  10874. return Engine._TEXTUREFORMAT_LUMINANCE;
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10880. /**
  10881. * R32F
  10882. */
  10883. get: function () {
  10884. return Engine._TEXTUREFORMAT_R32F;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10890. /**
  10891. * RG32F
  10892. */
  10893. get: function () {
  10894. return Engine._TEXTUREFORMAT_RG32F;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10900. /**
  10901. * RGB32F
  10902. */
  10903. get: function () {
  10904. return Engine._TEXTUREFORMAT_RGB32F;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10910. /**
  10911. * RGBA32F
  10912. */
  10913. get: function () {
  10914. return Engine._TEXTUREFORMAT_RGBA32F;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10920. get: function () {
  10921. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10927. get: function () {
  10928. return Engine._TEXTUREFORMAT_RGB;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10934. get: function () {
  10935. return Engine._TEXTUREFORMAT_RGBA;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10941. get: function () {
  10942. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10948. get: function () {
  10949. return Engine._TEXTURETYPE_FLOAT;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10955. get: function () {
  10956. return Engine._TEXTURETYPE_HALF_FLOAT;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10962. get: function () {
  10963. return Engine._SCALEMODE_FLOOR;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10969. get: function () {
  10970. return Engine._SCALEMODE_NEAREST;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10976. get: function () {
  10977. return Engine._SCALEMODE_CEILING;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "Version", {
  10983. get: function () {
  10984. return "3.2.0-alphaA";
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10990. get: function () {
  10991. return this._vrExclusivePointerMode;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10997. get: function () {
  10998. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11004. get: function () {
  11005. return this._webGLVersion < 2 || this.forcePOTTextures;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine.prototype, "badOS", {
  11011. get: function () {
  11012. return this._badOS;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11018. get: function () {
  11019. return this._badDesktopOS;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11025. get: function () {
  11026. return this._performanceMonitor;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11032. get: function () {
  11033. return this._texturesSupported;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11039. get: function () {
  11040. return this._textureFormatInUse;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine.prototype, "currentViewport", {
  11046. get: function () {
  11047. return this._cachedViewport;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11053. // Empty texture
  11054. get: function () {
  11055. if (!this._emptyTexture) {
  11056. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11057. }
  11058. return this._emptyTexture;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11064. get: function () {
  11065. if (!this._emptyTexture3D) {
  11066. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11067. }
  11068. return this._emptyTexture3D;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11074. get: function () {
  11075. if (!this._emptyCubeTexture) {
  11076. var faceData = new Uint8Array(4);
  11077. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11078. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11079. }
  11080. return this._emptyCubeTexture;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Engine.prototype._rebuildInternalTextures = function () {
  11086. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11087. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11088. var internalTexture = currentState_1[_i];
  11089. internalTexture._rebuild();
  11090. }
  11091. };
  11092. Engine.prototype._rebuildEffects = function () {
  11093. for (var key in this._compiledEffects) {
  11094. var effect = this._compiledEffects[key];
  11095. effect._prepareEffect();
  11096. }
  11097. BABYLON.Effect.ResetCache();
  11098. };
  11099. Engine.prototype._rebuildBuffers = function () {
  11100. // Index / Vertex
  11101. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11102. var scene = _a[_i];
  11103. scene.resetCachedMaterial();
  11104. scene._rebuildGeometries();
  11105. scene._rebuildTextures();
  11106. }
  11107. // Uniforms
  11108. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11109. var uniformBuffer = _c[_b];
  11110. uniformBuffer._rebuild();
  11111. }
  11112. };
  11113. Engine.prototype._initGLContext = function () {
  11114. // Caps
  11115. this._caps = new EngineCapabilities();
  11116. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11117. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11118. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11119. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11120. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11121. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11122. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11123. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11124. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11125. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11126. // Infos
  11127. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11128. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11129. if (rendererInfo != null) {
  11130. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11131. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11132. }
  11133. if (!this._glVendor) {
  11134. this._glVendor = "Unknown vendor";
  11135. }
  11136. if (!this._glRenderer) {
  11137. this._glRenderer = "Unknown renderer";
  11138. }
  11139. // Constants
  11140. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11141. if (this._gl.RGBA16F !== 0x881A) {
  11142. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11143. }
  11144. if (this._gl.RGBA32F !== 0x8814) {
  11145. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11146. }
  11147. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11148. this._gl.DEPTH24_STENCIL8 = 35056;
  11149. }
  11150. // Extensions
  11151. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11152. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11153. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11154. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11155. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11156. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11157. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11158. 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');
  11159. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11160. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11161. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11162. this._caps.highPrecisionShaderSupported = true;
  11163. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11164. if (this._caps.timerQuery) {
  11165. if (this._webGLVersion === 1) {
  11166. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11167. }
  11168. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11169. }
  11170. // Checks if some of the format renders first to allow the use of webgl inspector.
  11171. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11172. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11173. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11174. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11175. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11176. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11177. if (this._webGLVersion > 1) {
  11178. this._gl.HALF_FLOAT_OES = 0x140B;
  11179. }
  11180. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11181. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11182. // Draw buffers
  11183. if (this._webGLVersion > 1) {
  11184. this._caps.drawBuffersExtension = true;
  11185. }
  11186. else {
  11187. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11188. if (drawBuffersExtension !== null) {
  11189. this._caps.drawBuffersExtension = true;
  11190. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11191. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11192. for (var i = 0; i < 16; i++) {
  11193. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11194. }
  11195. }
  11196. else {
  11197. this._caps.drawBuffersExtension = false;
  11198. }
  11199. }
  11200. // Depth Texture
  11201. if (this._webGLVersion > 1) {
  11202. this._caps.depthTextureExtension = true;
  11203. }
  11204. else {
  11205. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11206. if (depthTextureExtension != null) {
  11207. this._caps.depthTextureExtension = true;
  11208. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11209. }
  11210. }
  11211. // Vertex array object
  11212. if (this._webGLVersion > 1) {
  11213. this._caps.vertexArrayObject = true;
  11214. }
  11215. else {
  11216. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11217. if (vertexArrayObjectExtension != null) {
  11218. this._caps.vertexArrayObject = true;
  11219. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11220. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11221. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11222. }
  11223. else {
  11224. this._caps.vertexArrayObject = false;
  11225. }
  11226. }
  11227. // Instances count
  11228. if (this._webGLVersion > 1) {
  11229. this._caps.instancedArrays = true;
  11230. }
  11231. else {
  11232. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11233. if (instanceExtension != null) {
  11234. this._caps.instancedArrays = true;
  11235. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11236. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11237. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11238. }
  11239. else {
  11240. this._caps.instancedArrays = false;
  11241. }
  11242. }
  11243. // Intelligently add supported compressed formats in order to check for.
  11244. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11245. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11246. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11247. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11248. if (this._caps.astc)
  11249. this.texturesSupported.push('-astc.ktx');
  11250. if (this._caps.s3tc)
  11251. this.texturesSupported.push('-dxt.ktx');
  11252. if (this._caps.pvrtc)
  11253. this.texturesSupported.push('-pvrtc.ktx');
  11254. if (this._caps.etc2)
  11255. this.texturesSupported.push('-etc2.ktx');
  11256. if (this._caps.etc1)
  11257. this.texturesSupported.push('-etc1.ktx');
  11258. if (this._gl.getShaderPrecisionFormat) {
  11259. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11260. if (highp) {
  11261. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11262. }
  11263. }
  11264. // Depth buffer
  11265. this.setDepthBuffer(true);
  11266. this.setDepthFunctionToLessOrEqual();
  11267. this.setDepthWrite(true);
  11268. // Texture maps
  11269. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11270. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11271. this._nextFreeTextureSlots.push(slot);
  11272. }
  11273. };
  11274. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11275. get: function () {
  11276. return this._webGLVersion;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11282. /**
  11283. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11284. */
  11285. get: function () {
  11286. return this._isStencilEnable;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Engine.prototype._prepareWorkingCanvas = function () {
  11292. if (this._workingCanvas) {
  11293. return;
  11294. }
  11295. this._workingCanvas = document.createElement("canvas");
  11296. var context = this._workingCanvas.getContext("2d");
  11297. if (context) {
  11298. this._workingContext = context;
  11299. }
  11300. };
  11301. Engine.prototype.resetTextureCache = function () {
  11302. for (var key in this._boundTexturesCache) {
  11303. var boundTexture = this._boundTexturesCache[key];
  11304. if (boundTexture) {
  11305. this._removeDesignatedSlot(boundTexture);
  11306. }
  11307. this._boundTexturesCache[key] = null;
  11308. }
  11309. if (!this.disableTextureBindingOptimization) {
  11310. this._nextFreeTextureSlots = [];
  11311. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11312. this._nextFreeTextureSlots.push(slot);
  11313. }
  11314. }
  11315. this._currentTextureChannel = -1;
  11316. };
  11317. Engine.prototype.isDeterministicLockStep = function () {
  11318. return this._deterministicLockstep;
  11319. };
  11320. Engine.prototype.getLockstepMaxSteps = function () {
  11321. return this._lockstepMaxSteps;
  11322. };
  11323. Engine.prototype.getGlInfo = function () {
  11324. return {
  11325. vendor: this._glVendor,
  11326. renderer: this._glRenderer,
  11327. version: this._glVersion
  11328. };
  11329. };
  11330. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11331. if (useScreen === void 0) { useScreen = false; }
  11332. var viewport = camera.viewport;
  11333. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11334. };
  11335. Engine.prototype.getRenderWidth = function (useScreen) {
  11336. if (useScreen === void 0) { useScreen = false; }
  11337. if (!useScreen && this._currentRenderTarget) {
  11338. return this._currentRenderTarget.width;
  11339. }
  11340. return this._gl.drawingBufferWidth;
  11341. };
  11342. Engine.prototype.getRenderHeight = function (useScreen) {
  11343. if (useScreen === void 0) { useScreen = false; }
  11344. if (!useScreen && this._currentRenderTarget) {
  11345. return this._currentRenderTarget.height;
  11346. }
  11347. return this._gl.drawingBufferHeight;
  11348. };
  11349. Engine.prototype.getRenderingCanvas = function () {
  11350. return this._renderingCanvas;
  11351. };
  11352. Engine.prototype.getRenderingCanvasClientRect = function () {
  11353. if (!this._renderingCanvas) {
  11354. return null;
  11355. }
  11356. return this._renderingCanvas.getBoundingClientRect();
  11357. };
  11358. Engine.prototype.setHardwareScalingLevel = function (level) {
  11359. this._hardwareScalingLevel = level;
  11360. this.resize();
  11361. };
  11362. Engine.prototype.getHardwareScalingLevel = function () {
  11363. return this._hardwareScalingLevel;
  11364. };
  11365. Engine.prototype.getLoadedTexturesCache = function () {
  11366. return this._internalTexturesCache;
  11367. };
  11368. Engine.prototype.getCaps = function () {
  11369. return this._caps;
  11370. };
  11371. Object.defineProperty(Engine.prototype, "drawCalls", {
  11372. /** The number of draw calls submitted last frame */
  11373. get: function () {
  11374. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11375. return 0;
  11376. },
  11377. enumerable: true,
  11378. configurable: true
  11379. });
  11380. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11381. get: function () {
  11382. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11383. return null;
  11384. },
  11385. enumerable: true,
  11386. configurable: true
  11387. });
  11388. Engine.prototype.getDepthFunction = function () {
  11389. return this._depthCullingState.depthFunc;
  11390. };
  11391. Engine.prototype.setDepthFunction = function (depthFunc) {
  11392. this._depthCullingState.depthFunc = depthFunc;
  11393. };
  11394. Engine.prototype.setDepthFunctionToGreater = function () {
  11395. this._depthCullingState.depthFunc = this._gl.GREATER;
  11396. };
  11397. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11398. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11399. };
  11400. Engine.prototype.setDepthFunctionToLess = function () {
  11401. this._depthCullingState.depthFunc = this._gl.LESS;
  11402. };
  11403. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11404. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11405. };
  11406. Engine.prototype.getStencilBuffer = function () {
  11407. return this._stencilState.stencilTest;
  11408. };
  11409. Engine.prototype.setStencilBuffer = function (enable) {
  11410. this._stencilState.stencilTest = enable;
  11411. };
  11412. Engine.prototype.getStencilMask = function () {
  11413. return this._stencilState.stencilMask;
  11414. };
  11415. Engine.prototype.setStencilMask = function (mask) {
  11416. this._stencilState.stencilMask = mask;
  11417. };
  11418. Engine.prototype.getStencilFunction = function () {
  11419. return this._stencilState.stencilFunc;
  11420. };
  11421. Engine.prototype.getStencilFunctionReference = function () {
  11422. return this._stencilState.stencilFuncRef;
  11423. };
  11424. Engine.prototype.getStencilFunctionMask = function () {
  11425. return this._stencilState.stencilFuncMask;
  11426. };
  11427. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11428. this._stencilState.stencilFunc = stencilFunc;
  11429. };
  11430. Engine.prototype.setStencilFunctionReference = function (reference) {
  11431. this._stencilState.stencilFuncRef = reference;
  11432. };
  11433. Engine.prototype.setStencilFunctionMask = function (mask) {
  11434. this._stencilState.stencilFuncMask = mask;
  11435. };
  11436. Engine.prototype.getStencilOperationFail = function () {
  11437. return this._stencilState.stencilOpStencilFail;
  11438. };
  11439. Engine.prototype.getStencilOperationDepthFail = function () {
  11440. return this._stencilState.stencilOpDepthFail;
  11441. };
  11442. Engine.prototype.getStencilOperationPass = function () {
  11443. return this._stencilState.stencilOpStencilDepthPass;
  11444. };
  11445. Engine.prototype.setStencilOperationFail = function (operation) {
  11446. this._stencilState.stencilOpStencilFail = operation;
  11447. };
  11448. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11449. this._stencilState.stencilOpDepthFail = operation;
  11450. };
  11451. Engine.prototype.setStencilOperationPass = function (operation) {
  11452. this._stencilState.stencilOpStencilDepthPass = operation;
  11453. };
  11454. Engine.prototype.setDitheringState = function (value) {
  11455. if (value) {
  11456. this._gl.enable(this._gl.DITHER);
  11457. }
  11458. else {
  11459. this._gl.disable(this._gl.DITHER);
  11460. }
  11461. };
  11462. Engine.prototype.setRasterizerState = function (value) {
  11463. if (value) {
  11464. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11465. }
  11466. else {
  11467. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11468. }
  11469. };
  11470. /**
  11471. * stop executing a render loop function and remove it from the execution array
  11472. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11473. */
  11474. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11475. if (!renderFunction) {
  11476. this._activeRenderLoops = [];
  11477. return;
  11478. }
  11479. var index = this._activeRenderLoops.indexOf(renderFunction);
  11480. if (index >= 0) {
  11481. this._activeRenderLoops.splice(index, 1);
  11482. }
  11483. };
  11484. Engine.prototype._renderLoop = function () {
  11485. if (!this._contextWasLost) {
  11486. var shouldRender = true;
  11487. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11488. shouldRender = false;
  11489. }
  11490. if (shouldRender) {
  11491. // Start new frame
  11492. this.beginFrame();
  11493. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11494. var renderFunction = this._activeRenderLoops[index];
  11495. renderFunction();
  11496. }
  11497. // Present
  11498. this.endFrame();
  11499. }
  11500. }
  11501. if (this._activeRenderLoops.length > 0) {
  11502. // Register new frame
  11503. var requester = null;
  11504. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11505. requester = this._vrDisplay;
  11506. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11507. }
  11508. else {
  11509. this._renderingQueueLaunched = false;
  11510. }
  11511. };
  11512. /**
  11513. * Register and execute a render loop. The engine can have more than one render function.
  11514. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11515. * @example
  11516. * engine.runRenderLoop(function () {
  11517. * scene.render()
  11518. * })
  11519. */
  11520. Engine.prototype.runRenderLoop = function (renderFunction) {
  11521. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11522. return;
  11523. }
  11524. this._activeRenderLoops.push(renderFunction);
  11525. if (!this._renderingQueueLaunched) {
  11526. this._renderingQueueLaunched = true;
  11527. this._bindedRenderFunction = this._renderLoop.bind(this);
  11528. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11529. }
  11530. };
  11531. /**
  11532. * Toggle full screen mode.
  11533. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11534. * @param {any} options - an options object to be sent to the requestFullscreen function
  11535. */
  11536. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11537. if (this.isFullscreen) {
  11538. BABYLON.Tools.ExitFullscreen();
  11539. }
  11540. else {
  11541. this._pointerLockRequested = requestPointerLock;
  11542. if (this._renderingCanvas) {
  11543. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11544. }
  11545. }
  11546. };
  11547. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11548. if (stencil === void 0) { stencil = false; }
  11549. this.applyStates();
  11550. var mode = 0;
  11551. if (backBuffer && color) {
  11552. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11553. mode |= this._gl.COLOR_BUFFER_BIT;
  11554. }
  11555. if (depth) {
  11556. this._gl.clearDepth(1.0);
  11557. mode |= this._gl.DEPTH_BUFFER_BIT;
  11558. }
  11559. if (stencil) {
  11560. this._gl.clearStencil(0);
  11561. mode |= this._gl.STENCIL_BUFFER_BIT;
  11562. }
  11563. this._gl.clear(mode);
  11564. };
  11565. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11566. var gl = this._gl;
  11567. // Save state
  11568. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11569. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11570. // Change state
  11571. gl.enable(gl.SCISSOR_TEST);
  11572. gl.scissor(x, y, width, height);
  11573. // Clear
  11574. this.clear(clearColor, true, true, true);
  11575. // Restore state
  11576. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11577. if (curScissor === true) {
  11578. gl.enable(gl.SCISSOR_TEST);
  11579. }
  11580. else {
  11581. gl.disable(gl.SCISSOR_TEST);
  11582. }
  11583. };
  11584. /**
  11585. * Set the WebGL's viewport
  11586. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11587. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11588. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11589. */
  11590. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11591. var width = requiredWidth || this.getRenderWidth();
  11592. var height = requiredHeight || this.getRenderHeight();
  11593. var x = viewport.x || 0;
  11594. var y = viewport.y || 0;
  11595. this._cachedViewport = viewport;
  11596. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11597. };
  11598. /**
  11599. * Directly set the WebGL Viewport
  11600. * The x, y, width & height are directly passed to the WebGL call
  11601. * @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.
  11602. */
  11603. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11604. var currentViewport = this._cachedViewport;
  11605. this._cachedViewport = null;
  11606. this._gl.viewport(x, y, width, height);
  11607. return currentViewport;
  11608. };
  11609. Engine.prototype.beginFrame = function () {
  11610. this.onBeginFrameObservable.notifyObservers(this);
  11611. this._measureFps();
  11612. };
  11613. Engine.prototype.endFrame = function () {
  11614. //force a flush in case we are using a bad OS.
  11615. if (this._badOS) {
  11616. this.flushFramebuffer();
  11617. }
  11618. //submit frame to the vr device, if enabled
  11619. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11620. // TODO: We should only submit the frame if we read frameData successfully.
  11621. this._vrDisplay.submitFrame();
  11622. }
  11623. this.onEndFrameObservable.notifyObservers(this);
  11624. };
  11625. /**
  11626. * resize the view according to the canvas' size.
  11627. * @example
  11628. * window.addEventListener("resize", function () {
  11629. * engine.resize();
  11630. * });
  11631. */
  11632. Engine.prototype.resize = function () {
  11633. // We're not resizing the size of the canvas while in VR mode & presenting
  11634. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11635. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11636. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11637. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11638. }
  11639. };
  11640. /**
  11641. * force a specific size of the canvas
  11642. * @param {number} width - the new canvas' width
  11643. * @param {number} height - the new canvas' height
  11644. */
  11645. Engine.prototype.setSize = function (width, height) {
  11646. if (!this._renderingCanvas) {
  11647. return;
  11648. }
  11649. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11650. return;
  11651. }
  11652. this._renderingCanvas.width = width;
  11653. this._renderingCanvas.height = height;
  11654. for (var index = 0; index < this.scenes.length; index++) {
  11655. var scene = this.scenes[index];
  11656. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11657. var cam = scene.cameras[camIndex];
  11658. cam._currentRenderId = 0;
  11659. }
  11660. }
  11661. if (this.onResizeObservable.hasObservers) {
  11662. this.onResizeObservable.notifyObservers(this);
  11663. }
  11664. };
  11665. // WebVR functions
  11666. Engine.prototype.isVRDevicePresent = function () {
  11667. return !!this._vrDisplay;
  11668. };
  11669. Engine.prototype.getVRDevice = function () {
  11670. return this._vrDisplay;
  11671. };
  11672. /**
  11673. * Initializes a webVR display and starts listening to display change events.
  11674. * The onVRDisplayChangedObservable will be notified upon these changes.
  11675. * @returns The onVRDisplayChangedObservable.
  11676. */
  11677. Engine.prototype.initWebVR = function () {
  11678. this.initWebVRAsync();
  11679. return this.onVRDisplayChangedObservable;
  11680. };
  11681. /**
  11682. * Initializes a webVR display and starts listening to display change events.
  11683. * The onVRDisplayChangedObservable will be notified upon these changes.
  11684. * @returns A promise containing a VRDisplay and if vr is supported.
  11685. */
  11686. Engine.prototype.initWebVRAsync = function () {
  11687. var _this = this;
  11688. var notifyObservers = function () {
  11689. var eventArgs = {
  11690. vrDisplay: _this._vrDisplay,
  11691. vrSupported: _this._vrSupported
  11692. };
  11693. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11694. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11695. };
  11696. if (!this._onVrDisplayConnect) {
  11697. this._onVrDisplayConnect = function (event) {
  11698. _this._vrDisplay = event.display;
  11699. notifyObservers();
  11700. };
  11701. this._onVrDisplayDisconnect = function () {
  11702. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11703. _this._vrDisplay = undefined;
  11704. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11705. notifyObservers();
  11706. };
  11707. this._onVrDisplayPresentChange = function () {
  11708. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11709. };
  11710. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11711. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11712. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11713. }
  11714. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11715. this._webVRInitPromise.then(notifyObservers);
  11716. return this._webVRInitPromise;
  11717. };
  11718. Engine.prototype.enableVR = function () {
  11719. var _this = this;
  11720. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11721. var onResolved = function () {
  11722. _this.onVRRequestPresentComplete.notifyObservers(true);
  11723. _this._onVRFullScreenTriggered();
  11724. };
  11725. var onRejected = function () {
  11726. _this.onVRRequestPresentComplete.notifyObservers(false);
  11727. };
  11728. this.onVRRequestPresentStart.notifyObservers(this);
  11729. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11730. }
  11731. };
  11732. Engine.prototype.disableVR = function () {
  11733. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11734. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11735. }
  11736. };
  11737. Engine.prototype._getVRDisplaysAsync = function () {
  11738. var _this = this;
  11739. return new Promise(function (res, rej) {
  11740. if (navigator.getVRDisplays) {
  11741. navigator.getVRDisplays().then(function (devices) {
  11742. _this._vrSupported = true;
  11743. // note that devices may actually be an empty array. This is fine;
  11744. // we expect this._vrDisplay to be undefined in this case.
  11745. _this._vrDisplay = devices[0];
  11746. res({
  11747. vrDisplay: _this._vrDisplay,
  11748. vrSupported: _this._vrSupported
  11749. });
  11750. });
  11751. }
  11752. else {
  11753. _this._vrDisplay = undefined;
  11754. _this._vrSupported = false;
  11755. res({
  11756. vrDisplay: _this._vrDisplay,
  11757. vrSupported: _this._vrSupported
  11758. });
  11759. }
  11760. });
  11761. };
  11762. /**
  11763. * Binds the frame buffer to the specified texture.
  11764. * @param texture The texture to render to or null for the default canvas
  11765. * @param faceIndex The face of the texture to render to in case of cube texture
  11766. * @param requiredWidth The width of the target to render to
  11767. * @param requiredHeight The height of the target to render to
  11768. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11769. * @param depthStencilTexture The depth stencil texture to use to render
  11770. */
  11771. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11772. if (this._currentRenderTarget) {
  11773. this.unBindFramebuffer(this._currentRenderTarget);
  11774. }
  11775. this._currentRenderTarget = texture;
  11776. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11777. var gl = this._gl;
  11778. if (texture.isCube) {
  11779. if (faceIndex === undefined) {
  11780. faceIndex = 0;
  11781. }
  11782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11783. if (depthStencilTexture) {
  11784. if (depthStencilTexture._generateStencilBuffer) {
  11785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11786. }
  11787. else {
  11788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11789. }
  11790. }
  11791. }
  11792. if (this._cachedViewport && !forceFullscreenViewport) {
  11793. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11794. }
  11795. else {
  11796. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11797. }
  11798. this.wipeCaches();
  11799. };
  11800. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11801. if (this._currentFramebuffer !== framebuffer) {
  11802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11803. this._currentFramebuffer = framebuffer;
  11804. }
  11805. };
  11806. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11807. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11808. this._currentRenderTarget = null;
  11809. // If MSAA, we need to bitblt back to main texture
  11810. var gl = this._gl;
  11811. if (texture._MSAAFramebuffer) {
  11812. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11813. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11814. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11815. }
  11816. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11817. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11818. gl.generateMipmap(gl.TEXTURE_2D);
  11819. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11820. }
  11821. if (onBeforeUnbind) {
  11822. if (texture._MSAAFramebuffer) {
  11823. // Bind the correct framebuffer
  11824. this.bindUnboundFramebuffer(texture._framebuffer);
  11825. }
  11826. onBeforeUnbind();
  11827. }
  11828. this.bindUnboundFramebuffer(null);
  11829. };
  11830. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11831. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11832. this._currentRenderTarget = null;
  11833. // If MSAA, we need to bitblt back to main texture
  11834. var gl = this._gl;
  11835. if (textures[0]._MSAAFramebuffer) {
  11836. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11837. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11838. var attachments = textures[0]._attachments;
  11839. if (!attachments) {
  11840. attachments = new Array(textures.length);
  11841. textures[0]._attachments = attachments;
  11842. }
  11843. for (var i = 0; i < textures.length; i++) {
  11844. var texture = textures[i];
  11845. for (var j = 0; j < attachments.length; j++) {
  11846. attachments[j] = gl.NONE;
  11847. }
  11848. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11849. gl.readBuffer(attachments[i]);
  11850. gl.drawBuffers(attachments);
  11851. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11852. }
  11853. for (var i = 0; i < attachments.length; i++) {
  11854. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11855. }
  11856. gl.drawBuffers(attachments);
  11857. }
  11858. for (var i = 0; i < textures.length; i++) {
  11859. var texture = textures[i];
  11860. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11861. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11862. gl.generateMipmap(gl.TEXTURE_2D);
  11863. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11864. }
  11865. }
  11866. if (onBeforeUnbind) {
  11867. if (textures[0]._MSAAFramebuffer) {
  11868. // Bind the correct framebuffer
  11869. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11870. }
  11871. onBeforeUnbind();
  11872. }
  11873. this.bindUnboundFramebuffer(null);
  11874. };
  11875. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11876. if (texture.generateMipMaps) {
  11877. var gl = this._gl;
  11878. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11879. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11880. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11881. }
  11882. };
  11883. Engine.prototype.flushFramebuffer = function () {
  11884. this._gl.flush();
  11885. };
  11886. Engine.prototype.restoreDefaultFramebuffer = function () {
  11887. if (this._currentRenderTarget) {
  11888. this.unBindFramebuffer(this._currentRenderTarget);
  11889. }
  11890. else {
  11891. this.bindUnboundFramebuffer(null);
  11892. }
  11893. if (this._cachedViewport) {
  11894. this.setViewport(this._cachedViewport);
  11895. }
  11896. this.wipeCaches();
  11897. };
  11898. // UBOs
  11899. Engine.prototype.createUniformBuffer = function (elements) {
  11900. var ubo = this._gl.createBuffer();
  11901. if (!ubo) {
  11902. throw new Error("Unable to create uniform buffer");
  11903. }
  11904. this.bindUniformBuffer(ubo);
  11905. if (elements instanceof Float32Array) {
  11906. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11907. }
  11908. else {
  11909. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11910. }
  11911. this.bindUniformBuffer(null);
  11912. ubo.references = 1;
  11913. return ubo;
  11914. };
  11915. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11916. var ubo = this._gl.createBuffer();
  11917. if (!ubo) {
  11918. throw new Error("Unable to create dynamic uniform buffer");
  11919. }
  11920. this.bindUniformBuffer(ubo);
  11921. if (elements instanceof Float32Array) {
  11922. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11923. }
  11924. else {
  11925. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11926. }
  11927. this.bindUniformBuffer(null);
  11928. ubo.references = 1;
  11929. return ubo;
  11930. };
  11931. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11932. this.bindUniformBuffer(uniformBuffer);
  11933. if (offset === undefined) {
  11934. offset = 0;
  11935. }
  11936. if (count === undefined) {
  11937. if (elements instanceof Float32Array) {
  11938. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11939. }
  11940. else {
  11941. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11942. }
  11943. }
  11944. else {
  11945. if (elements instanceof Float32Array) {
  11946. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11947. }
  11948. else {
  11949. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11950. }
  11951. }
  11952. this.bindUniformBuffer(null);
  11953. };
  11954. // VBOs
  11955. Engine.prototype._resetVertexBufferBinding = function () {
  11956. this.bindArrayBuffer(null);
  11957. this._cachedVertexBuffers = null;
  11958. };
  11959. Engine.prototype.createVertexBuffer = function (vertices) {
  11960. var vbo = this._gl.createBuffer();
  11961. if (!vbo) {
  11962. throw new Error("Unable to create vertex buffer");
  11963. }
  11964. this.bindArrayBuffer(vbo);
  11965. if (vertices instanceof Float32Array) {
  11966. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11967. }
  11968. else {
  11969. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11970. }
  11971. this._resetVertexBufferBinding();
  11972. vbo.references = 1;
  11973. return vbo;
  11974. };
  11975. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11976. var vbo = this._gl.createBuffer();
  11977. if (!vbo) {
  11978. throw new Error("Unable to create dynamic vertex buffer");
  11979. }
  11980. this.bindArrayBuffer(vbo);
  11981. if (vertices instanceof Float32Array) {
  11982. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11983. }
  11984. else {
  11985. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11986. }
  11987. this._resetVertexBufferBinding();
  11988. vbo.references = 1;
  11989. return vbo;
  11990. };
  11991. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11992. if (offset === void 0) { offset = 0; }
  11993. // Force cache update
  11994. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11995. this.bindIndexBuffer(indexBuffer);
  11996. var arrayBuffer;
  11997. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11998. arrayBuffer = indices;
  11999. }
  12000. else {
  12001. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12002. }
  12003. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12004. this._resetIndexBufferBinding();
  12005. };
  12006. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12007. this.bindArrayBuffer(vertexBuffer);
  12008. if (offset === undefined) {
  12009. offset = 0;
  12010. }
  12011. if (count === undefined) {
  12012. if (vertices instanceof Float32Array) {
  12013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12014. }
  12015. else {
  12016. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12017. }
  12018. }
  12019. else {
  12020. if (vertices instanceof Float32Array) {
  12021. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12022. }
  12023. else {
  12024. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12025. }
  12026. }
  12027. this._resetVertexBufferBinding();
  12028. };
  12029. Engine.prototype._resetIndexBufferBinding = function () {
  12030. this.bindIndexBuffer(null);
  12031. this._cachedIndexBuffer = null;
  12032. };
  12033. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12034. var vbo = this._gl.createBuffer();
  12035. if (!vbo) {
  12036. throw new Error("Unable to create index buffer");
  12037. }
  12038. this.bindIndexBuffer(vbo);
  12039. // Check for 32 bits indices
  12040. var arrayBuffer;
  12041. var need32Bits = false;
  12042. if (indices instanceof Uint16Array) {
  12043. arrayBuffer = indices;
  12044. }
  12045. else {
  12046. //check 32 bit support
  12047. if (this._caps.uintIndices) {
  12048. if (indices instanceof Uint32Array) {
  12049. arrayBuffer = indices;
  12050. need32Bits = true;
  12051. }
  12052. else {
  12053. //number[] or Int32Array, check if 32 bit is necessary
  12054. for (var index = 0; index < indices.length; index++) {
  12055. if (indices[index] > 65535) {
  12056. need32Bits = true;
  12057. break;
  12058. }
  12059. }
  12060. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12061. }
  12062. }
  12063. else {
  12064. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12065. arrayBuffer = new Uint16Array(indices);
  12066. }
  12067. }
  12068. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12069. this._resetIndexBufferBinding();
  12070. vbo.references = 1;
  12071. vbo.is32Bits = need32Bits;
  12072. return vbo;
  12073. };
  12074. Engine.prototype.bindArrayBuffer = function (buffer) {
  12075. if (!this._vaoRecordInProgress) {
  12076. this._unbindVertexArrayObject();
  12077. }
  12078. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12079. };
  12080. Engine.prototype.bindUniformBuffer = function (buffer) {
  12081. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12082. };
  12083. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12084. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12085. };
  12086. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12087. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12088. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12089. };
  12090. ;
  12091. Engine.prototype.bindIndexBuffer = function (buffer) {
  12092. if (!this._vaoRecordInProgress) {
  12093. this._unbindVertexArrayObject();
  12094. }
  12095. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12096. };
  12097. Engine.prototype.bindBuffer = function (buffer, target) {
  12098. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12099. this._gl.bindBuffer(target, buffer);
  12100. this._currentBoundBuffer[target] = buffer;
  12101. }
  12102. };
  12103. Engine.prototype.updateArrayBuffer = function (data) {
  12104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12105. };
  12106. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12107. var pointer = this._currentBufferPointers[indx];
  12108. var changed = false;
  12109. if (!pointer.active) {
  12110. changed = true;
  12111. pointer.active = true;
  12112. pointer.index = indx;
  12113. pointer.size = size;
  12114. pointer.type = type;
  12115. pointer.normalized = normalized;
  12116. pointer.stride = stride;
  12117. pointer.offset = offset;
  12118. pointer.buffer = buffer;
  12119. }
  12120. else {
  12121. if (pointer.buffer !== buffer) {
  12122. pointer.buffer = buffer;
  12123. changed = true;
  12124. }
  12125. if (pointer.size !== size) {
  12126. pointer.size = size;
  12127. changed = true;
  12128. }
  12129. if (pointer.type !== type) {
  12130. pointer.type = type;
  12131. changed = true;
  12132. }
  12133. if (pointer.normalized !== normalized) {
  12134. pointer.normalized = normalized;
  12135. changed = true;
  12136. }
  12137. if (pointer.stride !== stride) {
  12138. pointer.stride = stride;
  12139. changed = true;
  12140. }
  12141. if (pointer.offset !== offset) {
  12142. pointer.offset = offset;
  12143. changed = true;
  12144. }
  12145. }
  12146. if (changed || this._vaoRecordInProgress) {
  12147. this.bindArrayBuffer(buffer);
  12148. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12149. }
  12150. };
  12151. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12152. if (indexBuffer == null) {
  12153. return;
  12154. }
  12155. if (this._cachedIndexBuffer !== indexBuffer) {
  12156. this._cachedIndexBuffer = indexBuffer;
  12157. this.bindIndexBuffer(indexBuffer);
  12158. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12159. }
  12160. };
  12161. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12162. var attributes = effect.getAttributesNames();
  12163. if (!this._vaoRecordInProgress) {
  12164. this._unbindVertexArrayObject();
  12165. }
  12166. this.unbindAllAttributes();
  12167. for (var index = 0; index < attributes.length; index++) {
  12168. var order = effect.getAttributeLocation(index);
  12169. if (order >= 0) {
  12170. var vertexBuffer = vertexBuffers[attributes[index]];
  12171. if (!vertexBuffer) {
  12172. continue;
  12173. }
  12174. this._gl.enableVertexAttribArray(order);
  12175. if (!this._vaoRecordInProgress) {
  12176. this._vertexAttribArraysEnabled[order] = true;
  12177. }
  12178. var buffer = vertexBuffer.getBuffer();
  12179. if (buffer) {
  12180. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12181. if (vertexBuffer.getIsInstanced()) {
  12182. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12183. if (!this._vaoRecordInProgress) {
  12184. this._currentInstanceLocations.push(order);
  12185. this._currentInstanceBuffers.push(buffer);
  12186. }
  12187. }
  12188. }
  12189. }
  12190. }
  12191. };
  12192. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12193. var vao = this._gl.createVertexArray();
  12194. this._vaoRecordInProgress = true;
  12195. this._gl.bindVertexArray(vao);
  12196. this._mustWipeVertexAttributes = true;
  12197. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12198. this.bindIndexBuffer(indexBuffer);
  12199. this._vaoRecordInProgress = false;
  12200. this._gl.bindVertexArray(null);
  12201. return vao;
  12202. };
  12203. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12204. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12205. this._cachedVertexArrayObject = vertexArrayObject;
  12206. this._gl.bindVertexArray(vertexArrayObject);
  12207. this._cachedVertexBuffers = null;
  12208. this._cachedIndexBuffer = null;
  12209. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12210. this._mustWipeVertexAttributes = true;
  12211. }
  12212. };
  12213. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12214. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12215. this._cachedVertexBuffers = vertexBuffer;
  12216. this._cachedEffectForVertexBuffers = effect;
  12217. var attributesCount = effect.getAttributesCount();
  12218. this._unbindVertexArrayObject();
  12219. this.unbindAllAttributes();
  12220. var offset = 0;
  12221. for (var index = 0; index < attributesCount; index++) {
  12222. if (index < vertexDeclaration.length) {
  12223. var order = effect.getAttributeLocation(index);
  12224. if (order >= 0) {
  12225. this._gl.enableVertexAttribArray(order);
  12226. this._vertexAttribArraysEnabled[order] = true;
  12227. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12228. }
  12229. offset += vertexDeclaration[index] * 4;
  12230. }
  12231. }
  12232. }
  12233. this._bindIndexBufferWithCache(indexBuffer);
  12234. };
  12235. Engine.prototype._unbindVertexArrayObject = function () {
  12236. if (!this._cachedVertexArrayObject) {
  12237. return;
  12238. }
  12239. this._cachedVertexArrayObject = null;
  12240. this._gl.bindVertexArray(null);
  12241. };
  12242. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12243. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12244. this._cachedVertexBuffers = vertexBuffers;
  12245. this._cachedEffectForVertexBuffers = effect;
  12246. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12247. }
  12248. this._bindIndexBufferWithCache(indexBuffer);
  12249. };
  12250. Engine.prototype.unbindInstanceAttributes = function () {
  12251. var boundBuffer;
  12252. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12253. var instancesBuffer = this._currentInstanceBuffers[i];
  12254. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12255. boundBuffer = instancesBuffer;
  12256. this.bindArrayBuffer(instancesBuffer);
  12257. }
  12258. var offsetLocation = this._currentInstanceLocations[i];
  12259. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12260. }
  12261. this._currentInstanceBuffers.length = 0;
  12262. this._currentInstanceLocations.length = 0;
  12263. };
  12264. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12265. this._gl.deleteVertexArray(vao);
  12266. };
  12267. Engine.prototype._releaseBuffer = function (buffer) {
  12268. buffer.references--;
  12269. if (buffer.references === 0) {
  12270. this._gl.deleteBuffer(buffer);
  12271. return true;
  12272. }
  12273. return false;
  12274. };
  12275. Engine.prototype.createInstancesBuffer = function (capacity) {
  12276. var buffer = this._gl.createBuffer();
  12277. if (!buffer) {
  12278. throw new Error("Unable to create instance buffer");
  12279. }
  12280. buffer.capacity = capacity;
  12281. this.bindArrayBuffer(buffer);
  12282. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12283. return buffer;
  12284. };
  12285. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12286. this._gl.deleteBuffer(buffer);
  12287. };
  12288. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12289. this.bindArrayBuffer(instancesBuffer);
  12290. if (data) {
  12291. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12292. }
  12293. if (offsetLocations[0].index !== undefined) {
  12294. var stride = 0;
  12295. for (var i = 0; i < offsetLocations.length; i++) {
  12296. var ai = offsetLocations[i];
  12297. stride += ai.attributeSize * 4;
  12298. }
  12299. for (var i = 0; i < offsetLocations.length; i++) {
  12300. var ai = offsetLocations[i];
  12301. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12302. this._gl.enableVertexAttribArray(ai.index);
  12303. this._vertexAttribArraysEnabled[ai.index] = true;
  12304. }
  12305. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12306. this._gl.vertexAttribDivisor(ai.index, 1);
  12307. this._currentInstanceLocations.push(ai.index);
  12308. this._currentInstanceBuffers.push(instancesBuffer);
  12309. }
  12310. }
  12311. else {
  12312. for (var index = 0; index < 4; index++) {
  12313. var offsetLocation = offsetLocations[index];
  12314. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12315. this._gl.enableVertexAttribArray(offsetLocation);
  12316. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12317. }
  12318. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12319. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12320. this._currentInstanceLocations.push(offsetLocation);
  12321. this._currentInstanceBuffers.push(instancesBuffer);
  12322. }
  12323. }
  12324. };
  12325. Engine.prototype.applyStates = function () {
  12326. this._depthCullingState.apply(this._gl);
  12327. this._stencilState.apply(this._gl);
  12328. this._alphaState.apply(this._gl);
  12329. };
  12330. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12331. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12332. };
  12333. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12334. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12335. };
  12336. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12337. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12338. };
  12339. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12340. // Apply states
  12341. this.applyStates();
  12342. this._drawCalls.addCount(1, false);
  12343. // Render
  12344. var drawMode = this.DrawMode(fillMode);
  12345. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12346. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12347. if (instancesCount) {
  12348. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12349. }
  12350. else {
  12351. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12352. }
  12353. };
  12354. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12355. // Apply states
  12356. this.applyStates();
  12357. this._drawCalls.addCount(1, false);
  12358. var drawMode = this.DrawMode(fillMode);
  12359. if (instancesCount) {
  12360. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12361. }
  12362. else {
  12363. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12364. }
  12365. };
  12366. Engine.prototype.DrawMode = function (fillMode) {
  12367. switch (fillMode) {
  12368. // Triangle views
  12369. case BABYLON.Material.TriangleFillMode:
  12370. return this._gl.TRIANGLES;
  12371. case BABYLON.Material.PointFillMode:
  12372. return this._gl.POINTS;
  12373. case BABYLON.Material.WireFrameFillMode:
  12374. return this._gl.LINES;
  12375. // Draw modes
  12376. case BABYLON.Material.PointListDrawMode:
  12377. return this._gl.POINTS;
  12378. case BABYLON.Material.LineListDrawMode:
  12379. return this._gl.LINES;
  12380. case BABYLON.Material.LineLoopDrawMode:
  12381. return this._gl.LINE_LOOP;
  12382. case BABYLON.Material.LineStripDrawMode:
  12383. return this._gl.LINE_STRIP;
  12384. case BABYLON.Material.TriangleStripDrawMode:
  12385. return this._gl.TRIANGLE_STRIP;
  12386. case BABYLON.Material.TriangleFanDrawMode:
  12387. return this._gl.TRIANGLE_FAN;
  12388. default:
  12389. return this._gl.TRIANGLES;
  12390. }
  12391. };
  12392. // Shaders
  12393. Engine.prototype._releaseEffect = function (effect) {
  12394. if (this._compiledEffects[effect._key]) {
  12395. delete this._compiledEffects[effect._key];
  12396. this._deleteProgram(effect.getProgram());
  12397. }
  12398. };
  12399. Engine.prototype._deleteProgram = function (program) {
  12400. if (program) {
  12401. program.__SPECTOR_rebuildProgram = null;
  12402. if (program.transformFeedback) {
  12403. this.deleteTransformFeedback(program.transformFeedback);
  12404. program.transformFeedback = null;
  12405. }
  12406. this._gl.deleteProgram(program);
  12407. }
  12408. };
  12409. /**
  12410. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12411. * @param samplers An array of string used to represent textures
  12412. */
  12413. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12414. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12415. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12416. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12417. if (this._compiledEffects[name]) {
  12418. var compiledEffect = this._compiledEffects[name];
  12419. if (onCompiled && compiledEffect.isReady()) {
  12420. onCompiled(compiledEffect);
  12421. }
  12422. return compiledEffect;
  12423. }
  12424. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12425. effect._key = name;
  12426. this._compiledEffects[name] = effect;
  12427. return effect;
  12428. };
  12429. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12430. if (uniformsNames === void 0) { uniformsNames = []; }
  12431. if (samplers === void 0) { samplers = []; }
  12432. if (defines === void 0) { defines = ""; }
  12433. return this.createEffect({
  12434. vertex: "particles",
  12435. fragmentElement: fragmentName
  12436. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12437. };
  12438. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12439. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12440. context = context || this._gl;
  12441. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12442. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12443. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12444. };
  12445. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12446. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12447. context = context || this._gl;
  12448. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12449. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12450. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12451. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12452. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12453. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12454. return program;
  12455. };
  12456. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12457. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12458. var shaderProgram = context.createProgram();
  12459. if (!shaderProgram) {
  12460. throw new Error("Unable to create program");
  12461. }
  12462. context.attachShader(shaderProgram, vertexShader);
  12463. context.attachShader(shaderProgram, fragmentShader);
  12464. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12465. var transformFeedback = this.createTransformFeedback();
  12466. this.bindTransformFeedback(transformFeedback);
  12467. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12468. shaderProgram.transformFeedback = transformFeedback;
  12469. }
  12470. context.linkProgram(shaderProgram);
  12471. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12472. this.bindTransformFeedback(null);
  12473. }
  12474. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12475. if (!linked) {
  12476. context.validateProgram(shaderProgram);
  12477. var error = context.getProgramInfoLog(shaderProgram);
  12478. if (error) {
  12479. throw new Error(error);
  12480. }
  12481. }
  12482. context.deleteShader(vertexShader);
  12483. context.deleteShader(fragmentShader);
  12484. return shaderProgram;
  12485. };
  12486. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12487. var results = new Array();
  12488. for (var index = 0; index < uniformsNames.length; index++) {
  12489. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12490. }
  12491. return results;
  12492. };
  12493. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12494. var results = [];
  12495. for (var index = 0; index < attributesNames.length; index++) {
  12496. try {
  12497. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12498. }
  12499. catch (e) {
  12500. results.push(-1);
  12501. }
  12502. }
  12503. return results;
  12504. };
  12505. Engine.prototype.enableEffect = function (effect) {
  12506. if (!effect) {
  12507. return;
  12508. }
  12509. // Use program
  12510. this.bindSamplers(effect);
  12511. this._currentEffect = effect;
  12512. if (effect.onBind) {
  12513. effect.onBind(effect);
  12514. }
  12515. effect.onBindObservable.notifyObservers(effect);
  12516. };
  12517. Engine.prototype.setIntArray = function (uniform, array) {
  12518. if (!uniform)
  12519. return;
  12520. this._gl.uniform1iv(uniform, array);
  12521. };
  12522. Engine.prototype.setIntArray2 = function (uniform, array) {
  12523. if (!uniform || array.length % 2 !== 0)
  12524. return;
  12525. this._gl.uniform2iv(uniform, array);
  12526. };
  12527. Engine.prototype.setIntArray3 = function (uniform, array) {
  12528. if (!uniform || array.length % 3 !== 0)
  12529. return;
  12530. this._gl.uniform3iv(uniform, array);
  12531. };
  12532. Engine.prototype.setIntArray4 = function (uniform, array) {
  12533. if (!uniform || array.length % 4 !== 0)
  12534. return;
  12535. this._gl.uniform4iv(uniform, array);
  12536. };
  12537. Engine.prototype.setFloatArray = function (uniform, array) {
  12538. if (!uniform)
  12539. return;
  12540. this._gl.uniform1fv(uniform, array);
  12541. };
  12542. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12543. if (!uniform || array.length % 2 !== 0)
  12544. return;
  12545. this._gl.uniform2fv(uniform, array);
  12546. };
  12547. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12548. if (!uniform || array.length % 3 !== 0)
  12549. return;
  12550. this._gl.uniform3fv(uniform, array);
  12551. };
  12552. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12553. if (!uniform || array.length % 4 !== 0)
  12554. return;
  12555. this._gl.uniform4fv(uniform, array);
  12556. };
  12557. Engine.prototype.setArray = function (uniform, array) {
  12558. if (!uniform)
  12559. return;
  12560. this._gl.uniform1fv(uniform, array);
  12561. };
  12562. Engine.prototype.setArray2 = function (uniform, array) {
  12563. if (!uniform || array.length % 2 !== 0)
  12564. return;
  12565. this._gl.uniform2fv(uniform, array);
  12566. };
  12567. Engine.prototype.setArray3 = function (uniform, array) {
  12568. if (!uniform || array.length % 3 !== 0)
  12569. return;
  12570. this._gl.uniform3fv(uniform, array);
  12571. };
  12572. Engine.prototype.setArray4 = function (uniform, array) {
  12573. if (!uniform || array.length % 4 !== 0)
  12574. return;
  12575. this._gl.uniform4fv(uniform, array);
  12576. };
  12577. Engine.prototype.setMatrices = function (uniform, matrices) {
  12578. if (!uniform)
  12579. return;
  12580. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12581. };
  12582. Engine.prototype.setMatrix = function (uniform, matrix) {
  12583. if (!uniform)
  12584. return;
  12585. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12586. };
  12587. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12588. if (!uniform)
  12589. return;
  12590. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12591. };
  12592. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12593. if (!uniform)
  12594. return;
  12595. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12596. };
  12597. Engine.prototype.setInt = function (uniform, value) {
  12598. if (!uniform)
  12599. return;
  12600. this._gl.uniform1i(uniform, value);
  12601. };
  12602. Engine.prototype.setFloat = function (uniform, value) {
  12603. if (!uniform)
  12604. return;
  12605. this._gl.uniform1f(uniform, value);
  12606. };
  12607. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12608. if (!uniform)
  12609. return;
  12610. this._gl.uniform2f(uniform, x, y);
  12611. };
  12612. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12613. if (!uniform)
  12614. return;
  12615. this._gl.uniform3f(uniform, x, y, z);
  12616. };
  12617. Engine.prototype.setBool = function (uniform, bool) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniform1i(uniform, bool);
  12621. };
  12622. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12623. if (!uniform)
  12624. return;
  12625. this._gl.uniform4f(uniform, x, y, z, w);
  12626. };
  12627. Engine.prototype.setColor3 = function (uniform, color3) {
  12628. if (!uniform)
  12629. return;
  12630. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12631. };
  12632. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12633. if (!uniform)
  12634. return;
  12635. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12636. };
  12637. /**
  12638. * Sets a Color4 on a uniform variable
  12639. * @param uniform defines the uniform location
  12640. * @param color4 defines the value to be set
  12641. */
  12642. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12643. if (!uniform)
  12644. return;
  12645. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12646. };
  12647. // States
  12648. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12649. if (zOffset === void 0) { zOffset = 0; }
  12650. if (reverseSide === void 0) { reverseSide = false; }
  12651. // Culling
  12652. if (this._depthCullingState.cull !== culling || force) {
  12653. this._depthCullingState.cull = culling;
  12654. }
  12655. // Cull face
  12656. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12657. if (this._depthCullingState.cullFace !== cullFace || force) {
  12658. this._depthCullingState.cullFace = cullFace;
  12659. }
  12660. // Z offset
  12661. this.setZOffset(zOffset);
  12662. // Front face
  12663. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12664. if (this._depthCullingState.frontFace !== frontFace || force) {
  12665. this._depthCullingState.frontFace = frontFace;
  12666. }
  12667. };
  12668. Engine.prototype.setZOffset = function (value) {
  12669. this._depthCullingState.zOffset = value;
  12670. };
  12671. Engine.prototype.getZOffset = function () {
  12672. return this._depthCullingState.zOffset;
  12673. };
  12674. Engine.prototype.setDepthBuffer = function (enable) {
  12675. this._depthCullingState.depthTest = enable;
  12676. };
  12677. Engine.prototype.getDepthWrite = function () {
  12678. return this._depthCullingState.depthMask;
  12679. };
  12680. Engine.prototype.setDepthWrite = function (enable) {
  12681. this._depthCullingState.depthMask = enable;
  12682. };
  12683. Engine.prototype.setColorWrite = function (enable) {
  12684. this._gl.colorMask(enable, enable, enable, enable);
  12685. this._colorWrite = enable;
  12686. };
  12687. Engine.prototype.getColorWrite = function () {
  12688. return this._colorWrite;
  12689. };
  12690. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12691. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12692. };
  12693. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12694. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12695. if (this._alphaMode === mode) {
  12696. return;
  12697. }
  12698. switch (mode) {
  12699. case Engine.ALPHA_DISABLE:
  12700. this._alphaState.alphaBlend = false;
  12701. break;
  12702. case Engine.ALPHA_PREMULTIPLIED:
  12703. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12704. this._alphaState.alphaBlend = true;
  12705. break;
  12706. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12707. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12708. this._alphaState.alphaBlend = true;
  12709. break;
  12710. case Engine.ALPHA_COMBINE:
  12711. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12712. this._alphaState.alphaBlend = true;
  12713. break;
  12714. case Engine.ALPHA_ONEONE:
  12715. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12716. this._alphaState.alphaBlend = true;
  12717. break;
  12718. case Engine.ALPHA_ADD:
  12719. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12720. this._alphaState.alphaBlend = true;
  12721. break;
  12722. case Engine.ALPHA_SUBTRACT:
  12723. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12724. this._alphaState.alphaBlend = true;
  12725. break;
  12726. case Engine.ALPHA_MULTIPLY:
  12727. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12728. this._alphaState.alphaBlend = true;
  12729. break;
  12730. case Engine.ALPHA_MAXIMIZED:
  12731. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12732. this._alphaState.alphaBlend = true;
  12733. break;
  12734. case Engine.ALPHA_INTERPOLATE:
  12735. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12736. this._alphaState.alphaBlend = true;
  12737. break;
  12738. case Engine.ALPHA_SCREENMODE:
  12739. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12740. this._alphaState.alphaBlend = true;
  12741. break;
  12742. }
  12743. if (!noDepthWriteChange) {
  12744. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12745. }
  12746. this._alphaMode = mode;
  12747. };
  12748. Engine.prototype.getAlphaMode = function () {
  12749. return this._alphaMode;
  12750. };
  12751. // Textures
  12752. Engine.prototype.wipeCaches = function (bruteForce) {
  12753. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12754. return;
  12755. }
  12756. this._currentEffect = null;
  12757. // 6/8/2017: deltakosh: Should not be required anymore.
  12758. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12759. if (bruteForce) {
  12760. this.resetTextureCache();
  12761. this._currentProgram = null;
  12762. this._stencilState.reset();
  12763. this._depthCullingState.reset();
  12764. this.setDepthFunctionToLessOrEqual();
  12765. this._alphaState.reset();
  12766. }
  12767. this._resetVertexBufferBinding();
  12768. this._cachedIndexBuffer = null;
  12769. this._cachedEffectForVertexBuffers = null;
  12770. this._unbindVertexArrayObject();
  12771. this.bindIndexBuffer(null);
  12772. };
  12773. /**
  12774. * Set the compressed texture format to use, based on the formats you have, and the formats
  12775. * supported by the hardware / browser.
  12776. *
  12777. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12778. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12779. * to API arguments needed to compressed textures. This puts the burden on the container
  12780. * generator to house the arcane code for determining these for current & future formats.
  12781. *
  12782. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12783. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12784. *
  12785. * Note: The result of this call is not taken into account when a texture is base64.
  12786. *
  12787. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12788. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12789. *
  12790. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12791. * @returns The extension selected.
  12792. */
  12793. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12794. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12795. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12796. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12797. return this._textureFormatInUse = this._texturesSupported[i];
  12798. }
  12799. }
  12800. }
  12801. // actively set format to nothing, to allow this to be called more than once
  12802. // and possibly fail the 2nd time
  12803. this._textureFormatInUse = null;
  12804. return null;
  12805. };
  12806. Engine.prototype._createTexture = function () {
  12807. var texture = this._gl.createTexture();
  12808. if (!texture) {
  12809. throw new Error("Unable to create texture");
  12810. }
  12811. return texture;
  12812. };
  12813. /**
  12814. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12815. * @param {string} urlArg- This contains one of the following:
  12816. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12817. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12818. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12819. *
  12820. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12821. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12822. * @param {Scene} scene- Needed for loading to the correct scene.
  12823. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12824. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12825. * @param {callback} onError- Optional callback to be called upon failure.
  12826. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12827. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12828. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12829. *
  12830. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12831. */
  12832. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12833. var _this = this;
  12834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12835. if (onLoad === void 0) { onLoad = null; }
  12836. if (onError === void 0) { onError = null; }
  12837. if (buffer === void 0) { buffer = null; }
  12838. if (fallBack === void 0) { fallBack = null; }
  12839. if (format === void 0) { format = null; }
  12840. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12841. var fromData = url.substr(0, 5) === "data:";
  12842. var fromBlob = url.substr(0, 5) === "blob:";
  12843. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12844. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12845. // establish the file extension, if possible
  12846. var lastDot = url.lastIndexOf('.');
  12847. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12848. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12849. var isTGA = (extension.indexOf(".tga") === 0);
  12850. // determine if a ktx file should be substituted
  12851. var isKTX = false;
  12852. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12853. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12854. isKTX = true;
  12855. }
  12856. if (scene) {
  12857. scene._addPendingData(texture);
  12858. }
  12859. texture.url = url;
  12860. texture.generateMipMaps = !noMipmap;
  12861. texture.samplingMode = samplingMode;
  12862. texture.invertY = invertY;
  12863. if (!this._doNotHandleContextLost) {
  12864. // Keep a link to the buffer only if we plan to handle context lost
  12865. texture._buffer = buffer;
  12866. }
  12867. var onLoadObserver = null;
  12868. if (onLoad && !fallBack) {
  12869. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12870. }
  12871. if (!fallBack)
  12872. this._internalTexturesCache.push(texture);
  12873. var onerror = function (message, exception) {
  12874. if (scene) {
  12875. scene._removePendingData(texture);
  12876. }
  12877. if (onLoadObserver) {
  12878. texture.onLoadedObservable.remove(onLoadObserver);
  12879. }
  12880. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12881. if (isKTX) {
  12882. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12883. }
  12884. else if (BABYLON.Tools.UseFallbackTexture) {
  12885. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12886. }
  12887. if (onError) {
  12888. onError(message || "Unknown error", exception);
  12889. }
  12890. };
  12891. var callback = null;
  12892. // processing for non-image formats
  12893. if (isKTX || isTGA || isDDS) {
  12894. if (isKTX) {
  12895. callback = function (data) {
  12896. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12897. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12898. ktx.uploadLevels(_this._gl, !noMipmap);
  12899. return false;
  12900. }, samplingMode);
  12901. };
  12902. }
  12903. else if (isTGA) {
  12904. callback = function (arrayBuffer) {
  12905. var data = new Uint8Array(arrayBuffer);
  12906. var header = BABYLON.TGATools.GetTGAHeader(data);
  12907. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12908. BABYLON.TGATools.UploadContent(_this._gl, data);
  12909. return false;
  12910. }, samplingMode);
  12911. };
  12912. }
  12913. else if (isDDS) {
  12914. callback = function (data) {
  12915. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12916. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12917. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12918. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12919. return false;
  12920. }, samplingMode);
  12921. };
  12922. }
  12923. if (!buffer) {
  12924. this._loadFile(url, function (data) {
  12925. if (callback) {
  12926. callback(data);
  12927. }
  12928. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12929. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12930. });
  12931. }
  12932. else {
  12933. if (callback) {
  12934. callback(buffer);
  12935. }
  12936. }
  12937. // image format processing
  12938. }
  12939. else {
  12940. var onload = function (img) {
  12941. if (fromBlob && !_this._doNotHandleContextLost) {
  12942. // We need to store the image if we need to rebuild the texture
  12943. // in case of a webgl context lost
  12944. texture._buffer = img;
  12945. }
  12946. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12947. var gl = _this._gl;
  12948. var isPot = (img.width === potWidth && img.height === potHeight);
  12949. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12950. if (isPot) {
  12951. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12952. return false;
  12953. }
  12954. // Using shaders to rescale because canvas.drawImage is lossy
  12955. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12956. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12957. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12958. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12959. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12962. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12963. _this._releaseTexture(source);
  12964. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12965. continuationCallback();
  12966. });
  12967. return true;
  12968. }, samplingMode);
  12969. };
  12970. if (!fromData || isBase64)
  12971. if (buffer instanceof HTMLImageElement) {
  12972. onload(buffer);
  12973. }
  12974. else {
  12975. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12976. }
  12977. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12978. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12979. else
  12980. onload(buffer);
  12981. }
  12982. return texture;
  12983. };
  12984. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12985. var _this = this;
  12986. var rtt = this.createRenderTargetTexture({
  12987. width: destination.width,
  12988. height: destination.height,
  12989. }, {
  12990. generateMipMaps: false,
  12991. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12992. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12993. generateDepthBuffer: false,
  12994. generateStencilBuffer: false
  12995. });
  12996. if (!this._rescalePostProcess) {
  12997. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12998. }
  12999. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13000. _this._rescalePostProcess.onApply = function (effect) {
  13001. effect._bindTexture("textureSampler", source);
  13002. };
  13003. var hostingScene = scene;
  13004. if (!hostingScene) {
  13005. hostingScene = _this.scenes[_this.scenes.length - 1];
  13006. }
  13007. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13008. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13009. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13010. _this.unBindFramebuffer(rtt);
  13011. _this._releaseTexture(rtt);
  13012. if (onComplete) {
  13013. onComplete();
  13014. }
  13015. });
  13016. };
  13017. Engine.prototype._getInternalFormat = function (format) {
  13018. var internalFormat = this._gl.RGBA;
  13019. switch (format) {
  13020. case Engine.TEXTUREFORMAT_ALPHA:
  13021. internalFormat = this._gl.ALPHA;
  13022. break;
  13023. case Engine.TEXTUREFORMAT_LUMINANCE:
  13024. internalFormat = this._gl.LUMINANCE;
  13025. break;
  13026. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13027. internalFormat = this._gl.LUMINANCE_ALPHA;
  13028. break;
  13029. case Engine.TEXTUREFORMAT_RGB:
  13030. case Engine.TEXTUREFORMAT_RGB32F:
  13031. internalFormat = this._gl.RGB;
  13032. break;
  13033. case Engine.TEXTUREFORMAT_RGBA:
  13034. case Engine.TEXTUREFORMAT_RGBA32F:
  13035. internalFormat = this._gl.RGBA;
  13036. break;
  13037. case Engine.TEXTUREFORMAT_R32F:
  13038. internalFormat = this._gl.RED;
  13039. break;
  13040. case Engine.TEXTUREFORMAT_RG32F:
  13041. internalFormat = this._gl.RG;
  13042. break;
  13043. }
  13044. return internalFormat;
  13045. };
  13046. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13047. if (compression === void 0) { compression = null; }
  13048. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13049. if (!texture) {
  13050. return;
  13051. }
  13052. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13053. var internalFormat = this._getInternalFormat(format);
  13054. var textureType = this._getWebGLTextureType(type);
  13055. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13056. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13057. if (!this._doNotHandleContextLost) {
  13058. texture._bufferView = data;
  13059. texture.format = format;
  13060. texture.type = type;
  13061. texture.invertY = invertY;
  13062. texture._compression = compression;
  13063. }
  13064. if (texture.width % 4 !== 0) {
  13065. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13066. }
  13067. if (compression && data) {
  13068. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13069. }
  13070. else {
  13071. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13072. }
  13073. if (texture.generateMipMaps) {
  13074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13075. }
  13076. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13077. // this.resetTextureCache();
  13078. texture.isReady = true;
  13079. };
  13080. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13081. if (compression === void 0) { compression = null; }
  13082. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13084. texture.baseWidth = width;
  13085. texture.baseHeight = height;
  13086. texture.width = width;
  13087. texture.height = height;
  13088. texture.format = format;
  13089. texture.generateMipMaps = generateMipMaps;
  13090. texture.samplingMode = samplingMode;
  13091. texture.invertY = invertY;
  13092. texture._compression = compression;
  13093. texture.type = type;
  13094. if (!this._doNotHandleContextLost) {
  13095. texture._bufferView = data;
  13096. }
  13097. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13098. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13099. // Filters
  13100. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13101. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13102. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13103. if (generateMipMaps) {
  13104. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13105. }
  13106. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13107. this._internalTexturesCache.push(texture);
  13108. return texture;
  13109. };
  13110. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13111. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13112. texture.baseWidth = width;
  13113. texture.baseHeight = height;
  13114. if (generateMipMaps) {
  13115. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13116. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13117. }
  13118. // this.resetTextureCache();
  13119. texture.width = width;
  13120. texture.height = height;
  13121. texture.isReady = false;
  13122. texture.generateMipMaps = generateMipMaps;
  13123. texture.samplingMode = samplingMode;
  13124. this.updateTextureSamplingMode(samplingMode, texture);
  13125. this._internalTexturesCache.push(texture);
  13126. return texture;
  13127. };
  13128. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13129. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13130. if (texture.isCube) {
  13131. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13132. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13133. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13134. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13135. }
  13136. else if (texture.is3D) {
  13137. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13138. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13139. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13140. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13141. }
  13142. else {
  13143. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13144. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13145. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13146. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13147. }
  13148. texture.samplingMode = samplingMode;
  13149. };
  13150. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13151. if (premulAlpha === void 0) { premulAlpha = false; }
  13152. if (!texture) {
  13153. return;
  13154. }
  13155. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13156. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13157. if (premulAlpha) {
  13158. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13159. }
  13160. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13161. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13162. if (texture.generateMipMaps) {
  13163. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13164. }
  13165. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13166. if (premulAlpha) {
  13167. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13168. }
  13169. texture.isReady = true;
  13170. };
  13171. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13172. if (!texture || texture._isDisabled) {
  13173. return;
  13174. }
  13175. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13176. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13177. try {
  13178. // Testing video texture support
  13179. if (this._videoTextureSupported === undefined) {
  13180. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13181. if (this._gl.getError() !== 0) {
  13182. this._videoTextureSupported = false;
  13183. }
  13184. else {
  13185. this._videoTextureSupported = true;
  13186. }
  13187. }
  13188. // Copy video through the current working canvas if video texture is not supported
  13189. if (!this._videoTextureSupported) {
  13190. if (!texture._workingCanvas) {
  13191. texture._workingCanvas = document.createElement("canvas");
  13192. var context = texture._workingCanvas.getContext("2d");
  13193. if (!context) {
  13194. throw new Error("Unable to get 2d context");
  13195. }
  13196. texture._workingContext = context;
  13197. texture._workingCanvas.width = texture.width;
  13198. texture._workingCanvas.height = texture.height;
  13199. }
  13200. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13201. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13202. }
  13203. else {
  13204. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13205. }
  13206. if (texture.generateMipMaps) {
  13207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13208. }
  13209. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13210. // this.resetTextureCache();
  13211. texture.isReady = true;
  13212. }
  13213. catch (ex) {
  13214. // Something unexpected
  13215. // Let's disable the texture
  13216. texture._isDisabled = true;
  13217. }
  13218. };
  13219. /**
  13220. * Updates a depth texture Comparison Mode and Function.
  13221. * If the comparison Function is equal to 0, the mode will be set to none.
  13222. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13223. * @param texture The texture to set the comparison function for
  13224. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13225. */
  13226. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13227. if (this.webGLVersion === 1) {
  13228. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13229. return;
  13230. }
  13231. var gl = this._gl;
  13232. if (texture.isCube) {
  13233. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13234. if (comparisonFunction === 0) {
  13235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13237. }
  13238. else {
  13239. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13240. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13241. }
  13242. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13243. }
  13244. else {
  13245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13246. if (comparisonFunction === 0) {
  13247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13249. }
  13250. else {
  13251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13253. }
  13254. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13255. }
  13256. texture._comparisonFunction = comparisonFunction;
  13257. };
  13258. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13259. var width = size.width || size;
  13260. var height = size.height || size;
  13261. internalTexture.baseWidth = width;
  13262. internalTexture.baseHeight = height;
  13263. internalTexture.width = width;
  13264. internalTexture.height = height;
  13265. internalTexture.isReady = true;
  13266. internalTexture.samples = 1;
  13267. internalTexture.generateMipMaps = false;
  13268. internalTexture._generateDepthBuffer = true;
  13269. internalTexture._generateStencilBuffer = generateStencil;
  13270. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13271. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13272. internalTexture._comparisonFunction = comparisonFunction;
  13273. var gl = this._gl;
  13274. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13275. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13276. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13277. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13278. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13279. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13280. if (comparisonFunction === 0) {
  13281. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13282. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13283. }
  13284. else {
  13285. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13286. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13287. }
  13288. };
  13289. /**
  13290. * Creates a depth stencil texture.
  13291. * This is only available in WebGL 2 or with the depth texture extension available.
  13292. * @param size The size of face edge in the texture.
  13293. * @param options The options defining the texture.
  13294. * @returns The texture
  13295. */
  13296. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13297. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13298. if (!this._caps.depthTextureExtension) {
  13299. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13300. return internalTexture;
  13301. }
  13302. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13303. var gl = this._gl;
  13304. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13305. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13306. if (this.webGLVersion > 1) {
  13307. if (internalOptions.generateStencil) {
  13308. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13309. }
  13310. else {
  13311. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13312. }
  13313. }
  13314. else {
  13315. if (internalOptions.generateStencil) {
  13316. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13317. }
  13318. else {
  13319. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13320. }
  13321. }
  13322. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13323. return internalTexture;
  13324. };
  13325. /**
  13326. * Creates a depth stencil cube texture.
  13327. * This is only available in WebGL 2.
  13328. * @param size The size of face edge in the cube texture.
  13329. * @param options The options defining the cube texture.
  13330. * @returns The cube texture
  13331. */
  13332. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13333. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13334. internalTexture.isCube = true;
  13335. if (this.webGLVersion === 1) {
  13336. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13337. return internalTexture;
  13338. }
  13339. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13340. var gl = this._gl;
  13341. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13342. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13343. // Create the depth/stencil buffer
  13344. for (var face = 0; face < 6; face++) {
  13345. if (internalOptions.generateStencil) {
  13346. 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);
  13347. }
  13348. else {
  13349. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13350. }
  13351. }
  13352. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13353. return internalTexture;
  13354. };
  13355. /**
  13356. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13357. * @param renderTarget The render target to set the frame buffer for
  13358. */
  13359. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13360. // Create the framebuffer
  13361. var internalTexture = renderTarget.getInternalTexture();
  13362. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13363. return;
  13364. }
  13365. var gl = this._gl;
  13366. var depthStencilTexture = renderTarget.depthStencilTexture;
  13367. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13368. if (depthStencilTexture.isCube) {
  13369. if (depthStencilTexture._generateStencilBuffer) {
  13370. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13371. }
  13372. else {
  13373. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13374. }
  13375. }
  13376. else {
  13377. if (depthStencilTexture._generateStencilBuffer) {
  13378. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13379. }
  13380. else {
  13381. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13382. }
  13383. }
  13384. this.bindUnboundFramebuffer(null);
  13385. };
  13386. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13387. var fullOptions = new RenderTargetCreationOptions();
  13388. if (options !== undefined && typeof options === "object") {
  13389. fullOptions.generateMipMaps = options.generateMipMaps;
  13390. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13391. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13392. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13393. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13394. }
  13395. else {
  13396. fullOptions.generateMipMaps = options;
  13397. fullOptions.generateDepthBuffer = true;
  13398. fullOptions.generateStencilBuffer = false;
  13399. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13400. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13401. }
  13402. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13403. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13404. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13405. }
  13406. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13407. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13408. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13409. }
  13410. var gl = this._gl;
  13411. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13412. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13413. var width = size.width || size;
  13414. var height = size.height || size;
  13415. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13416. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13417. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13418. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13419. }
  13420. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13424. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13425. // Create the framebuffer
  13426. var framebuffer = gl.createFramebuffer();
  13427. this.bindUnboundFramebuffer(framebuffer);
  13428. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13429. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13430. if (fullOptions.generateMipMaps) {
  13431. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13432. }
  13433. // Unbind
  13434. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13435. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13436. this.bindUnboundFramebuffer(null);
  13437. texture._framebuffer = framebuffer;
  13438. texture.baseWidth = width;
  13439. texture.baseHeight = height;
  13440. texture.width = width;
  13441. texture.height = height;
  13442. texture.isReady = true;
  13443. texture.samples = 1;
  13444. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13445. texture.samplingMode = fullOptions.samplingMode;
  13446. texture.type = fullOptions.type;
  13447. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13448. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13449. // this.resetTextureCache();
  13450. this._internalTexturesCache.push(texture);
  13451. return texture;
  13452. };
  13453. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13454. var generateMipMaps = false;
  13455. var generateDepthBuffer = true;
  13456. var generateStencilBuffer = false;
  13457. var generateDepthTexture = false;
  13458. var textureCount = 1;
  13459. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13460. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13461. var types = [], samplingModes = [];
  13462. if (options !== undefined) {
  13463. generateMipMaps = options.generateMipMaps;
  13464. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13465. generateStencilBuffer = options.generateStencilBuffer;
  13466. generateDepthTexture = options.generateDepthTexture;
  13467. textureCount = options.textureCount || 1;
  13468. if (options.types) {
  13469. types = options.types;
  13470. }
  13471. if (options.samplingModes) {
  13472. samplingModes = options.samplingModes;
  13473. }
  13474. }
  13475. var gl = this._gl;
  13476. // Create the framebuffer
  13477. var framebuffer = gl.createFramebuffer();
  13478. this.bindUnboundFramebuffer(framebuffer);
  13479. var width = size.width || size;
  13480. var height = size.height || size;
  13481. var textures = [];
  13482. var attachments = [];
  13483. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13484. for (var i = 0; i < textureCount; i++) {
  13485. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13486. var type = types[i] || defaultType;
  13487. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13488. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13490. }
  13491. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13492. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13493. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13494. }
  13495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13496. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13497. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13498. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13499. }
  13500. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13501. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13502. textures.push(texture);
  13503. attachments.push(attachment);
  13504. gl.activeTexture(gl["TEXTURE" + i]);
  13505. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13510. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13511. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13512. if (generateMipMaps) {
  13513. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13514. }
  13515. // Unbind
  13516. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13517. texture._framebuffer = framebuffer;
  13518. texture._depthStencilBuffer = depthStencilBuffer;
  13519. texture.baseWidth = width;
  13520. texture.baseHeight = height;
  13521. texture.width = width;
  13522. texture.height = height;
  13523. texture.isReady = true;
  13524. texture.samples = 1;
  13525. texture.generateMipMaps = generateMipMaps;
  13526. texture.samplingMode = samplingMode;
  13527. texture.type = type;
  13528. texture._generateDepthBuffer = generateDepthBuffer;
  13529. texture._generateStencilBuffer = generateStencilBuffer;
  13530. texture._attachments = attachments;
  13531. this._internalTexturesCache.push(texture);
  13532. }
  13533. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13534. // Depth texture
  13535. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13536. gl.activeTexture(gl.TEXTURE0);
  13537. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13542. 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);
  13543. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13544. depthTexture._framebuffer = framebuffer;
  13545. depthTexture.baseWidth = width;
  13546. depthTexture.baseHeight = height;
  13547. depthTexture.width = width;
  13548. depthTexture.height = height;
  13549. depthTexture.isReady = true;
  13550. depthTexture.samples = 1;
  13551. depthTexture.generateMipMaps = generateMipMaps;
  13552. depthTexture.samplingMode = gl.NEAREST;
  13553. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13554. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13555. textures.push(depthTexture);
  13556. this._internalTexturesCache.push(depthTexture);
  13557. }
  13558. gl.drawBuffers(attachments);
  13559. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13560. this.bindUnboundFramebuffer(null);
  13561. this.resetTextureCache();
  13562. return textures;
  13563. };
  13564. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13565. if (samples === void 0) { samples = 1; }
  13566. var depthStencilBuffer = null;
  13567. var gl = this._gl;
  13568. // Create the depth/stencil buffer
  13569. if (generateStencilBuffer) {
  13570. depthStencilBuffer = gl.createRenderbuffer();
  13571. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13572. if (samples > 1) {
  13573. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13574. }
  13575. else {
  13576. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13577. }
  13578. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13579. }
  13580. else if (generateDepthBuffer) {
  13581. depthStencilBuffer = gl.createRenderbuffer();
  13582. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13583. if (samples > 1) {
  13584. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13585. }
  13586. else {
  13587. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13588. }
  13589. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13590. }
  13591. return depthStencilBuffer;
  13592. };
  13593. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13594. if (this.webGLVersion < 2 || !texture) {
  13595. return 1;
  13596. }
  13597. if (texture.samples === samples) {
  13598. return samples;
  13599. }
  13600. var gl = this._gl;
  13601. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13602. // Dispose previous render buffers
  13603. if (texture._depthStencilBuffer) {
  13604. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13605. texture._depthStencilBuffer = null;
  13606. }
  13607. if (texture._MSAAFramebuffer) {
  13608. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13609. texture._MSAAFramebuffer = null;
  13610. }
  13611. if (texture._MSAARenderBuffer) {
  13612. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13613. texture._MSAARenderBuffer = null;
  13614. }
  13615. if (samples > 1) {
  13616. var framebuffer = gl.createFramebuffer();
  13617. if (!framebuffer) {
  13618. throw new Error("Unable to create multi sampled framebuffer");
  13619. }
  13620. texture._MSAAFramebuffer = framebuffer;
  13621. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13622. var colorRenderbuffer = gl.createRenderbuffer();
  13623. if (!colorRenderbuffer) {
  13624. throw new Error("Unable to create multi sampled framebuffer");
  13625. }
  13626. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13627. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13628. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13629. texture._MSAARenderBuffer = colorRenderbuffer;
  13630. }
  13631. else {
  13632. this.bindUnboundFramebuffer(texture._framebuffer);
  13633. }
  13634. texture.samples = samples;
  13635. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13636. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13637. this.bindUnboundFramebuffer(null);
  13638. return samples;
  13639. };
  13640. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13641. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13642. return 1;
  13643. }
  13644. if (textures[0].samples === samples) {
  13645. return samples;
  13646. }
  13647. var gl = this._gl;
  13648. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13649. // Dispose previous render buffers
  13650. if (textures[0]._depthStencilBuffer) {
  13651. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13652. textures[0]._depthStencilBuffer = null;
  13653. }
  13654. if (textures[0]._MSAAFramebuffer) {
  13655. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13656. textures[0]._MSAAFramebuffer = null;
  13657. }
  13658. for (var i = 0; i < textures.length; i++) {
  13659. if (textures[i]._MSAARenderBuffer) {
  13660. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13661. textures[i]._MSAARenderBuffer = null;
  13662. }
  13663. }
  13664. if (samples > 1) {
  13665. var framebuffer = gl.createFramebuffer();
  13666. if (!framebuffer) {
  13667. throw new Error("Unable to create multi sampled framebuffer");
  13668. }
  13669. this.bindUnboundFramebuffer(framebuffer);
  13670. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13671. var attachments = [];
  13672. for (var i = 0; i < textures.length; i++) {
  13673. var texture = textures[i];
  13674. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13675. var colorRenderbuffer = gl.createRenderbuffer();
  13676. if (!colorRenderbuffer) {
  13677. throw new Error("Unable to create multi sampled framebuffer");
  13678. }
  13679. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13680. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13681. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13682. texture._MSAAFramebuffer = framebuffer;
  13683. texture._MSAARenderBuffer = colorRenderbuffer;
  13684. texture.samples = samples;
  13685. texture._depthStencilBuffer = depthStencilBuffer;
  13686. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13687. attachments.push(attachment);
  13688. }
  13689. gl.drawBuffers(attachments);
  13690. }
  13691. else {
  13692. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13693. }
  13694. this.bindUnboundFramebuffer(null);
  13695. return samples;
  13696. };
  13697. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13698. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13699. };
  13700. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13701. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13702. };
  13703. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13704. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13705. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13706. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13707. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13708. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13709. }
  13710. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13711. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13712. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13713. }
  13714. var gl = this._gl;
  13715. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13716. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13717. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13718. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13719. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13720. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13721. }
  13722. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13723. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13726. for (var face = 0; face < 6; face++) {
  13727. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13728. }
  13729. // Create the framebuffer
  13730. var framebuffer = gl.createFramebuffer();
  13731. this.bindUnboundFramebuffer(framebuffer);
  13732. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13733. // MipMaps
  13734. if (fullOptions.generateMipMaps) {
  13735. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13736. }
  13737. // Unbind
  13738. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13739. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13740. this.bindUnboundFramebuffer(null);
  13741. texture._framebuffer = framebuffer;
  13742. texture.width = size;
  13743. texture.height = size;
  13744. texture.isReady = true;
  13745. texture.isCube = true;
  13746. texture.samples = 1;
  13747. texture.generateMipMaps = fullOptions.generateMipMaps;
  13748. texture.samplingMode = fullOptions.samplingMode;
  13749. texture.type = fullOptions.type;
  13750. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13751. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13752. this._internalTexturesCache.push(texture);
  13753. return texture;
  13754. };
  13755. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13756. var _this = this;
  13757. if (onLoad === void 0) { onLoad = null; }
  13758. if (onError === void 0) { onError = null; }
  13759. if (forcedExtension === void 0) { forcedExtension = null; }
  13760. var callback = function (loadData) {
  13761. if (!loadData) {
  13762. if (onLoad) {
  13763. onLoad(null);
  13764. }
  13765. return;
  13766. }
  13767. var texture = loadData.texture;
  13768. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13769. texture._lodGenerationScale = scale;
  13770. texture._lodGenerationOffset = offset;
  13771. if (_this._caps.textureLOD) {
  13772. // Do not add extra process if texture lod is supported.
  13773. if (onLoad) {
  13774. onLoad(texture);
  13775. }
  13776. return;
  13777. }
  13778. var mipSlices = 3;
  13779. var gl = _this._gl;
  13780. var width = loadData.width;
  13781. if (!width) {
  13782. return;
  13783. }
  13784. var textures = [];
  13785. for (var i = 0; i < mipSlices; i++) {
  13786. //compute LOD from even spacing in smoothness (matching shader calculation)
  13787. var smoothness = i / (mipSlices - 1);
  13788. var roughness = 1 - smoothness;
  13789. var minLODIndex = offset; // roughness = 0
  13790. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13791. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13792. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13793. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13794. glTextureFromLod.isCube = true;
  13795. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13800. if (loadData.isDDS) {
  13801. var info = loadData.info;
  13802. var data = loadData.data;
  13803. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13804. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13805. }
  13806. else {
  13807. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13808. }
  13809. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13810. // Wrap in a base texture for easy binding.
  13811. var lodTexture = new BABYLON.BaseTexture(scene);
  13812. lodTexture.isCube = true;
  13813. lodTexture._texture = glTextureFromLod;
  13814. glTextureFromLod.isReady = true;
  13815. textures.push(lodTexture);
  13816. }
  13817. texture._lodTextureHigh = textures[2];
  13818. texture._lodTextureMid = textures[1];
  13819. texture._lodTextureLow = textures[0];
  13820. if (onLoad) {
  13821. onLoad(texture);
  13822. }
  13823. };
  13824. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13825. };
  13826. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13827. var _this = this;
  13828. if (onLoad === void 0) { onLoad = null; }
  13829. if (onError === void 0) { onError = null; }
  13830. if (forcedExtension === void 0) { forcedExtension = null; }
  13831. var gl = this._gl;
  13832. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13833. texture.isCube = true;
  13834. texture.url = rootUrl;
  13835. texture.generateMipMaps = !noMipmap;
  13836. if (!this._doNotHandleContextLost) {
  13837. texture._extension = forcedExtension;
  13838. texture._files = files;
  13839. }
  13840. var isKTX = false;
  13841. var isDDS = false;
  13842. var lastDot = rootUrl.lastIndexOf('.');
  13843. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13844. if (this._textureFormatInUse) {
  13845. extension = this._textureFormatInUse;
  13846. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13847. isKTX = true;
  13848. }
  13849. else {
  13850. isDDS = (extension === ".dds");
  13851. }
  13852. var onerror = function (request, exception) {
  13853. if (onError && request) {
  13854. onError(request.status + " " + request.statusText, exception);
  13855. }
  13856. };
  13857. if (isKTX) {
  13858. this._loadFile(rootUrl, function (data) {
  13859. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13860. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13861. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13862. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13863. ktx.uploadLevels(_this._gl, !noMipmap);
  13864. _this.setCubeMapTextureParams(gl, loadMipmap);
  13865. texture.width = ktx.pixelWidth;
  13866. texture.height = ktx.pixelHeight;
  13867. texture.isReady = true;
  13868. }, undefined, undefined, true, onerror);
  13869. }
  13870. else if (isDDS) {
  13871. if (files && files.length === 6) {
  13872. this._cascadeLoadFiles(scene, function (imgs) {
  13873. var info;
  13874. var loadMipmap = false;
  13875. var width = 0;
  13876. for (var index = 0; index < imgs.length; index++) {
  13877. var data = imgs[index];
  13878. info = BABYLON.DDSTools.GetDDSInfo(data);
  13879. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13880. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13881. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13882. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13883. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13884. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13885. }
  13886. texture.width = info.width;
  13887. texture.height = info.height;
  13888. texture.type = info.textureType;
  13889. width = info.width;
  13890. }
  13891. _this.setCubeMapTextureParams(gl, loadMipmap);
  13892. texture.isReady = true;
  13893. if (onLoad) {
  13894. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13895. }
  13896. }, files, onError);
  13897. }
  13898. else {
  13899. this._loadFile(rootUrl, function (data) {
  13900. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13901. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13902. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13903. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13904. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13905. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13906. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13907. }
  13908. _this.setCubeMapTextureParams(gl, loadMipmap);
  13909. texture.width = info.width;
  13910. texture.height = info.height;
  13911. texture.isReady = true;
  13912. texture.type = info.textureType;
  13913. if (onLoad) {
  13914. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13915. }
  13916. }, undefined, undefined, true, onerror);
  13917. }
  13918. }
  13919. else {
  13920. if (!files) {
  13921. throw new Error("Cannot load cubemap because files were not defined");
  13922. }
  13923. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13924. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13925. var height = width;
  13926. _this._prepareWorkingCanvas();
  13927. if (!_this._workingCanvas || !_this._workingContext) {
  13928. return;
  13929. }
  13930. _this._workingCanvas.width = width;
  13931. _this._workingCanvas.height = height;
  13932. var faces = [
  13933. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13934. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13935. ];
  13936. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13937. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13938. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13939. for (var index = 0; index < faces.length; index++) {
  13940. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13941. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13942. }
  13943. if (!noMipmap) {
  13944. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13945. }
  13946. _this.setCubeMapTextureParams(gl, !noMipmap);
  13947. texture.width = width;
  13948. texture.height = height;
  13949. texture.isReady = true;
  13950. if (format) {
  13951. texture.format = format;
  13952. }
  13953. texture.onLoadedObservable.notifyObservers(texture);
  13954. texture.onLoadedObservable.clear();
  13955. if (onLoad) {
  13956. onLoad();
  13957. }
  13958. }, files, onError);
  13959. }
  13960. this._internalTexturesCache.push(texture);
  13961. return texture;
  13962. };
  13963. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13968. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13969. // this.resetTextureCache();
  13970. };
  13971. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13972. if (compression === void 0) { compression = null; }
  13973. if (level === void 0) { level = 0; }
  13974. texture._bufferViewArray = data;
  13975. texture.format = format;
  13976. texture.type = type;
  13977. texture.invertY = invertY;
  13978. texture._compression = compression;
  13979. var gl = this._gl;
  13980. var textureType = this._getWebGLTextureType(type);
  13981. var internalFormat = this._getInternalFormat(format);
  13982. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13983. var needConversion = false;
  13984. if (internalFormat === gl.RGB) {
  13985. internalFormat = gl.RGBA;
  13986. needConversion = true;
  13987. }
  13988. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13989. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13990. if (texture.width % 4 !== 0) {
  13991. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13992. }
  13993. // Data are known to be in +X +Y +Z -X -Y -Z
  13994. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13995. var faceData = data[faceIndex];
  13996. if (compression) {
  13997. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13998. }
  13999. else {
  14000. if (needConversion) {
  14001. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14002. }
  14003. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14004. }
  14005. }
  14006. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14007. if (isPot && texture.generateMipMaps && level === 0) {
  14008. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14009. }
  14010. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14011. // this.resetTextureCache();
  14012. texture.isReady = true;
  14013. };
  14014. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14015. if (compression === void 0) { compression = null; }
  14016. var gl = this._gl;
  14017. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14018. texture.isCube = true;
  14019. texture.generateMipMaps = generateMipMaps;
  14020. texture.format = format;
  14021. texture.type = type;
  14022. if (!this._doNotHandleContextLost) {
  14023. texture._bufferViewArray = data;
  14024. }
  14025. var textureType = this._getWebGLTextureType(type);
  14026. var internalFormat = this._getInternalFormat(format);
  14027. if (internalFormat === gl.RGB) {
  14028. internalFormat = gl.RGBA;
  14029. }
  14030. var width = size;
  14031. var height = width;
  14032. texture.width = width;
  14033. texture.height = height;
  14034. // Double check on POT to generate Mips.
  14035. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14036. if (!isPot) {
  14037. generateMipMaps = false;
  14038. }
  14039. // Upload data if needed. The texture won't be ready until then.
  14040. if (data) {
  14041. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14042. }
  14043. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14044. // Filters
  14045. if (data && generateMipMaps) {
  14046. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14047. }
  14048. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14049. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14050. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14051. }
  14052. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14053. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14054. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14055. }
  14056. else {
  14057. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14060. }
  14061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14063. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14064. return texture;
  14065. };
  14066. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14067. var _this = this;
  14068. if (onLoad === void 0) { onLoad = null; }
  14069. if (onError === void 0) { onError = null; }
  14070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14071. if (invertY === void 0) { invertY = false; }
  14072. var gl = this._gl;
  14073. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14074. scene._addPendingData(texture);
  14075. texture.url = url;
  14076. this._internalTexturesCache.push(texture);
  14077. var onerror = function (request, exception) {
  14078. scene._removePendingData(texture);
  14079. if (onError && request) {
  14080. onError(request.status + " " + request.statusText, exception);
  14081. }
  14082. };
  14083. var internalCallback = function (data) {
  14084. var width = texture.width;
  14085. var faceDataArrays = callback(data);
  14086. if (!faceDataArrays) {
  14087. return;
  14088. }
  14089. if (mipmmapGenerator) {
  14090. var textureType = _this._getWebGLTextureType(type);
  14091. var internalFormat = _this._getInternalFormat(format);
  14092. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14093. var needConversion = false;
  14094. if (internalFormat === gl.RGB) {
  14095. internalFormat = gl.RGBA;
  14096. needConversion = true;
  14097. }
  14098. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14099. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14100. var mipData = mipmmapGenerator(faceDataArrays);
  14101. for (var level = 0; level < mipData.length; level++) {
  14102. var mipSize = width >> level;
  14103. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14104. var mipFaceData = mipData[level][faceIndex];
  14105. if (needConversion) {
  14106. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14107. }
  14108. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14109. }
  14110. }
  14111. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14112. }
  14113. else {
  14114. texture.generateMipMaps = !noMipmap;
  14115. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14116. }
  14117. texture.isReady = true;
  14118. // this.resetTextureCache();
  14119. scene._removePendingData(texture);
  14120. if (onLoad) {
  14121. onLoad();
  14122. }
  14123. };
  14124. this._loadFile(url, function (data) {
  14125. internalCallback(data);
  14126. }, undefined, scene.database, true, onerror);
  14127. return texture;
  14128. };
  14129. ;
  14130. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14131. if (compression === void 0) { compression = null; }
  14132. var internalFormat = this._getInternalFormat(format);
  14133. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14134. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14135. if (!this._doNotHandleContextLost) {
  14136. texture._bufferView = data;
  14137. texture.format = format;
  14138. texture.invertY = invertY;
  14139. texture._compression = compression;
  14140. }
  14141. if (texture.width % 4 !== 0) {
  14142. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14143. }
  14144. if (compression && data) {
  14145. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14146. }
  14147. else {
  14148. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14149. }
  14150. if (texture.generateMipMaps) {
  14151. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14152. }
  14153. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14154. // this.resetTextureCache();
  14155. texture.isReady = true;
  14156. };
  14157. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14158. if (compression === void 0) { compression = null; }
  14159. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14160. texture.baseWidth = width;
  14161. texture.baseHeight = height;
  14162. texture.baseDepth = depth;
  14163. texture.width = width;
  14164. texture.height = height;
  14165. texture.depth = depth;
  14166. texture.format = format;
  14167. texture.generateMipMaps = generateMipMaps;
  14168. texture.samplingMode = samplingMode;
  14169. texture.is3D = true;
  14170. if (!this._doNotHandleContextLost) {
  14171. texture._bufferView = data;
  14172. }
  14173. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14174. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14175. // Filters
  14176. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14177. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14179. if (generateMipMaps) {
  14180. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14181. }
  14182. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14183. this._internalTexturesCache.push(texture);
  14184. return texture;
  14185. };
  14186. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14187. var gl = this._gl;
  14188. if (!gl) {
  14189. return;
  14190. }
  14191. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14194. if (!noMipmap && !isCompressed) {
  14195. gl.generateMipmap(gl.TEXTURE_2D);
  14196. }
  14197. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14198. // this.resetTextureCache();
  14199. if (scene) {
  14200. scene._removePendingData(texture);
  14201. }
  14202. texture.onLoadedObservable.notifyObservers(texture);
  14203. texture.onLoadedObservable.clear();
  14204. };
  14205. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14206. var _this = this;
  14207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14208. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14209. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14210. var gl = this._gl;
  14211. if (!gl) {
  14212. return;
  14213. }
  14214. if (!texture._webGLTexture) {
  14215. // this.resetTextureCache();
  14216. if (scene) {
  14217. scene._removePendingData(texture);
  14218. }
  14219. return;
  14220. }
  14221. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14222. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14223. texture.baseWidth = width;
  14224. texture.baseHeight = height;
  14225. texture.width = potWidth;
  14226. texture.height = potHeight;
  14227. texture.isReady = true;
  14228. if (processFunction(potWidth, potHeight, function () {
  14229. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14230. })) {
  14231. // Returning as texture needs extra async steps
  14232. return;
  14233. }
  14234. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14235. };
  14236. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14237. // Create new RGBA data container.
  14238. var rgbaData;
  14239. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14240. rgbaData = new Float32Array(width * height * 4);
  14241. }
  14242. else {
  14243. rgbaData = new Uint32Array(width * height * 4);
  14244. }
  14245. // Convert each pixel.
  14246. for (var x = 0; x < width; x++) {
  14247. for (var y = 0; y < height; y++) {
  14248. var index = (y * width + x) * 3;
  14249. var newIndex = (y * width + x) * 4;
  14250. // Map Old Value to new value.
  14251. rgbaData[newIndex + 0] = rgbData[index + 0];
  14252. rgbaData[newIndex + 1] = rgbData[index + 1];
  14253. rgbaData[newIndex + 2] = rgbData[index + 2];
  14254. // Add fully opaque alpha channel.
  14255. rgbaData[newIndex + 3] = 1;
  14256. }
  14257. }
  14258. return rgbaData;
  14259. };
  14260. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14261. var gl = this._gl;
  14262. if (texture._framebuffer) {
  14263. gl.deleteFramebuffer(texture._framebuffer);
  14264. texture._framebuffer = null;
  14265. }
  14266. if (texture._depthStencilBuffer) {
  14267. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14268. texture._depthStencilBuffer = null;
  14269. }
  14270. if (texture._MSAAFramebuffer) {
  14271. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14272. texture._MSAAFramebuffer = null;
  14273. }
  14274. if (texture._MSAARenderBuffer) {
  14275. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14276. texture._MSAARenderBuffer = null;
  14277. }
  14278. };
  14279. Engine.prototype._releaseTexture = function (texture) {
  14280. var gl = this._gl;
  14281. this._releaseFramebufferObjects(texture);
  14282. gl.deleteTexture(texture._webGLTexture);
  14283. // Unbind channels
  14284. this.unbindAllTextures();
  14285. var index = this._internalTexturesCache.indexOf(texture);
  14286. if (index !== -1) {
  14287. this._internalTexturesCache.splice(index, 1);
  14288. }
  14289. // Integrated fixed lod samplers.
  14290. if (texture._lodTextureHigh) {
  14291. texture._lodTextureHigh.dispose();
  14292. }
  14293. if (texture._lodTextureMid) {
  14294. texture._lodTextureMid.dispose();
  14295. }
  14296. if (texture._lodTextureLow) {
  14297. texture._lodTextureLow.dispose();
  14298. }
  14299. };
  14300. Engine.prototype.setProgram = function (program) {
  14301. if (this._currentProgram !== program) {
  14302. this._gl.useProgram(program);
  14303. this._currentProgram = program;
  14304. }
  14305. };
  14306. Engine.prototype.bindSamplers = function (effect) {
  14307. this.setProgram(effect.getProgram());
  14308. var samplers = effect.getSamplers();
  14309. for (var index = 0; index < samplers.length; index++) {
  14310. var uniform = effect.getUniform(samplers[index]);
  14311. if (uniform) {
  14312. this._boundUniforms[index] = uniform;
  14313. }
  14314. }
  14315. this._currentEffect = null;
  14316. };
  14317. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14318. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14319. return;
  14320. }
  14321. // Remove
  14322. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14323. // Bind last to it
  14324. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14325. // Bind to dummy
  14326. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14327. };
  14328. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14329. if (!internalTexture) {
  14330. return -1;
  14331. }
  14332. internalTexture._initialSlot = channel;
  14333. if (this.disableTextureBindingOptimization) {
  14334. if (channel !== internalTexture._designatedSlot) {
  14335. this._textureCollisions.addCount(1, false);
  14336. }
  14337. }
  14338. else {
  14339. if (channel !== internalTexture._designatedSlot) {
  14340. if (internalTexture._designatedSlot > -1) {
  14341. return internalTexture._designatedSlot;
  14342. }
  14343. else {
  14344. // No slot for this texture, let's pick a new one (if we find a free slot)
  14345. if (this._nextFreeTextureSlots.length) {
  14346. return this._nextFreeTextureSlots[0];
  14347. }
  14348. // We need to recycle the oldest bound texture, sorry.
  14349. this._textureCollisions.addCount(1, false);
  14350. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14351. }
  14352. }
  14353. }
  14354. return channel;
  14355. };
  14356. Engine.prototype._linkTrackers = function (previous, next) {
  14357. previous.next = next;
  14358. next.previous = previous;
  14359. };
  14360. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14361. var currentSlot = internalTexture._designatedSlot;
  14362. if (currentSlot === -1) {
  14363. return -1;
  14364. }
  14365. internalTexture._designatedSlot = -1;
  14366. if (this.disableTextureBindingOptimization) {
  14367. return -1;
  14368. }
  14369. // Remove from bound list
  14370. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14371. // Free the slot
  14372. this._boundTexturesCache[currentSlot] = null;
  14373. this._nextFreeTextureSlots.push(currentSlot);
  14374. return currentSlot;
  14375. };
  14376. Engine.prototype._activateCurrentTexture = function () {
  14377. if (this._currentTextureChannel !== this._activeChannel) {
  14378. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14379. this._currentTextureChannel = this._activeChannel;
  14380. }
  14381. };
  14382. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14383. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14384. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14385. this._activeChannel = texture._designatedSlot;
  14386. }
  14387. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14388. var isTextureForRendering = texture && texture._initialSlot > -1;
  14389. if (currentTextureBound !== texture) {
  14390. if (currentTextureBound) {
  14391. this._removeDesignatedSlot(currentTextureBound);
  14392. }
  14393. this._activateCurrentTexture();
  14394. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14395. this._boundTexturesCache[this._activeChannel] = texture;
  14396. if (texture) {
  14397. if (!this.disableTextureBindingOptimization) {
  14398. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14399. if (slotIndex > -1) {
  14400. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14401. }
  14402. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14403. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14404. }
  14405. texture._designatedSlot = this._activeChannel;
  14406. }
  14407. }
  14408. else if (forTextureDataUpdate) {
  14409. this._activateCurrentTexture();
  14410. }
  14411. if (isTextureForRendering && !forTextureDataUpdate) {
  14412. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14413. }
  14414. };
  14415. Engine.prototype._bindTexture = function (channel, texture) {
  14416. if (channel < 0) {
  14417. return;
  14418. }
  14419. if (texture) {
  14420. channel = this._getCorrectTextureChannel(channel, texture);
  14421. }
  14422. this._activeChannel = channel;
  14423. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14424. };
  14425. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14426. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14427. };
  14428. Engine.prototype.unbindAllTextures = function () {
  14429. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14430. this._activeChannel = channel;
  14431. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14432. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14433. if (this.webGLVersion > 1) {
  14434. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14435. }
  14436. }
  14437. };
  14438. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14439. if (channel < 0) {
  14440. return;
  14441. }
  14442. if (uniform) {
  14443. this._boundUniforms[channel] = uniform;
  14444. }
  14445. this._setTexture(channel, texture);
  14446. };
  14447. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14448. var uniform = this._boundUniforms[sourceSlot];
  14449. if (uniform._currentState === destination) {
  14450. return;
  14451. }
  14452. this._gl.uniform1i(uniform, destination);
  14453. uniform._currentState = destination;
  14454. };
  14455. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14456. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14457. // Not ready?
  14458. if (!texture) {
  14459. if (this._boundTexturesCache[channel] != null) {
  14460. this._activeChannel = channel;
  14461. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14463. if (this.webGLVersion > 1) {
  14464. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14465. }
  14466. }
  14467. return false;
  14468. }
  14469. // Video
  14470. if (texture.video) {
  14471. this._activeChannel = channel;
  14472. texture.update();
  14473. }
  14474. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14475. texture.delayLoad();
  14476. return false;
  14477. }
  14478. var internalTexture;
  14479. if (texture.isReady()) {
  14480. internalTexture = texture.getInternalTexture();
  14481. }
  14482. else if (texture.isCube) {
  14483. internalTexture = this.emptyCubeTexture;
  14484. }
  14485. else if (texture.is3D) {
  14486. internalTexture = this.emptyTexture3D;
  14487. }
  14488. else {
  14489. internalTexture = this.emptyTexture;
  14490. }
  14491. if (!isPartOfTextureArray) {
  14492. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14493. }
  14494. if (this._boundTexturesCache[channel] === internalTexture) {
  14495. this._moveBoundTextureOnTop(internalTexture);
  14496. if (!isPartOfTextureArray) {
  14497. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14498. }
  14499. return false;
  14500. }
  14501. this._activeChannel = channel;
  14502. if (internalTexture && internalTexture.is3D) {
  14503. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14504. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14505. internalTexture._cachedWrapU = texture.wrapU;
  14506. switch (texture.wrapU) {
  14507. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14508. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14509. break;
  14510. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14511. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14512. break;
  14513. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14514. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14515. break;
  14516. }
  14517. }
  14518. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14519. internalTexture._cachedWrapV = texture.wrapV;
  14520. switch (texture.wrapV) {
  14521. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14522. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14523. break;
  14524. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14525. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14526. break;
  14527. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14528. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14529. break;
  14530. }
  14531. }
  14532. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14533. internalTexture._cachedWrapR = texture.wrapR;
  14534. switch (texture.wrapR) {
  14535. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14536. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14537. break;
  14538. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14539. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14540. break;
  14541. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14542. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14543. break;
  14544. }
  14545. }
  14546. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14547. }
  14548. else if (internalTexture && internalTexture.isCube) {
  14549. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14550. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14551. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14552. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14553. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14554. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14555. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14556. }
  14557. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14558. }
  14559. else {
  14560. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14561. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14562. internalTexture._cachedWrapU = texture.wrapU;
  14563. switch (texture.wrapU) {
  14564. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14566. break;
  14567. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14569. break;
  14570. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14571. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14572. break;
  14573. }
  14574. }
  14575. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14576. internalTexture._cachedWrapV = texture.wrapV;
  14577. switch (texture.wrapV) {
  14578. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14579. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14580. break;
  14581. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14582. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14583. break;
  14584. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14585. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14586. break;
  14587. }
  14588. }
  14589. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14590. }
  14591. return true;
  14592. };
  14593. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14594. if (channel < 0 || !uniform) {
  14595. return;
  14596. }
  14597. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14598. this._textureUnits = new Int32Array(textures.length);
  14599. }
  14600. for (var i = 0; i < textures.length; i++) {
  14601. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14602. }
  14603. this._gl.uniform1iv(uniform, this._textureUnits);
  14604. for (var index = 0; index < textures.length; index++) {
  14605. this._setTexture(this._textureUnits[index], textures[index], true);
  14606. }
  14607. };
  14608. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14609. var internalTexture = texture.getInternalTexture();
  14610. if (!internalTexture) {
  14611. return;
  14612. }
  14613. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14614. var value = texture.anisotropicFilteringLevel;
  14615. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14616. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14617. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14618. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14619. }
  14620. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14621. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14622. internalTexture._cachedAnisotropicFilteringLevel = value;
  14623. }
  14624. };
  14625. Engine.prototype.readPixels = function (x, y, width, height) {
  14626. var data = new Uint8Array(height * width * 4);
  14627. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14628. return data;
  14629. };
  14630. /**
  14631. * Add an externaly attached data from its key.
  14632. * This method call will fail and return false, if such key already exists.
  14633. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14634. * @param key the unique key that identifies the data
  14635. * @param data the data object to associate to the key for this Engine instance
  14636. * @return true if no such key were already present and the data was added successfully, false otherwise
  14637. */
  14638. Engine.prototype.addExternalData = function (key, data) {
  14639. if (!this._externalData) {
  14640. this._externalData = new BABYLON.StringDictionary();
  14641. }
  14642. return this._externalData.add(key, data);
  14643. };
  14644. /**
  14645. * Get an externaly attached data from its key
  14646. * @param key the unique key that identifies the data
  14647. * @return the associated data, if present (can be null), or undefined if not present
  14648. */
  14649. Engine.prototype.getExternalData = function (key) {
  14650. if (!this._externalData) {
  14651. this._externalData = new BABYLON.StringDictionary();
  14652. }
  14653. return this._externalData.get(key);
  14654. };
  14655. /**
  14656. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14657. * @param key the unique key that identifies the data
  14658. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14659. * @return the associated data, can be null if the factory returned null.
  14660. */
  14661. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14662. if (!this._externalData) {
  14663. this._externalData = new BABYLON.StringDictionary();
  14664. }
  14665. return this._externalData.getOrAddWithFactory(key, factory);
  14666. };
  14667. /**
  14668. * Remove an externaly attached data from the Engine instance
  14669. * @param key the unique key that identifies the data
  14670. * @return true if the data was successfully removed, false if it doesn't exist
  14671. */
  14672. Engine.prototype.removeExternalData = function (key) {
  14673. if (!this._externalData) {
  14674. this._externalData = new BABYLON.StringDictionary();
  14675. }
  14676. return this._externalData.remove(key);
  14677. };
  14678. Engine.prototype.unbindAllAttributes = function () {
  14679. if (this._mustWipeVertexAttributes) {
  14680. this._mustWipeVertexAttributes = false;
  14681. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14682. this._gl.disableVertexAttribArray(i);
  14683. this._vertexAttribArraysEnabled[i] = false;
  14684. this._currentBufferPointers[i].active = false;
  14685. }
  14686. return;
  14687. }
  14688. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14689. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14690. continue;
  14691. }
  14692. this._gl.disableVertexAttribArray(i);
  14693. this._vertexAttribArraysEnabled[i] = false;
  14694. this._currentBufferPointers[i].active = false;
  14695. }
  14696. };
  14697. Engine.prototype.releaseEffects = function () {
  14698. for (var name in this._compiledEffects) {
  14699. this._deleteProgram(this._compiledEffects[name]._program);
  14700. }
  14701. this._compiledEffects = {};
  14702. };
  14703. // Dispose
  14704. Engine.prototype.dispose = function () {
  14705. this.hideLoadingUI();
  14706. this.stopRenderLoop();
  14707. // Release postProcesses
  14708. while (this.postProcesses.length) {
  14709. this.postProcesses[0].dispose();
  14710. }
  14711. // Empty texture
  14712. if (this._emptyTexture) {
  14713. this._releaseTexture(this._emptyTexture);
  14714. this._emptyTexture = null;
  14715. }
  14716. if (this._emptyCubeTexture) {
  14717. this._releaseTexture(this._emptyCubeTexture);
  14718. this._emptyCubeTexture = null;
  14719. }
  14720. // Rescale PP
  14721. if (this._rescalePostProcess) {
  14722. this._rescalePostProcess.dispose();
  14723. }
  14724. // Release scenes
  14725. while (this.scenes.length) {
  14726. this.scenes[0].dispose();
  14727. }
  14728. // Release audio engine
  14729. if (Engine.audioEngine) {
  14730. Engine.audioEngine.dispose();
  14731. }
  14732. // Release effects
  14733. this.releaseEffects();
  14734. // Unbind
  14735. this.unbindAllAttributes();
  14736. if (this._dummyFramebuffer) {
  14737. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14738. }
  14739. //WebVR
  14740. this.disableVR();
  14741. // Events
  14742. if (BABYLON.Tools.IsWindowObjectExist()) {
  14743. window.removeEventListener("blur", this._onBlur);
  14744. window.removeEventListener("focus", this._onFocus);
  14745. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14746. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14747. if (this._renderingCanvas) {
  14748. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14749. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14750. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14751. if (!this._doNotHandleContextLost) {
  14752. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14753. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14754. }
  14755. }
  14756. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14757. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14758. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14759. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14760. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14761. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14762. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14763. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14764. if (this._onVrDisplayConnect) {
  14765. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14766. if (this._onVrDisplayDisconnect) {
  14767. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14768. }
  14769. if (this._onVrDisplayPresentChange) {
  14770. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14771. }
  14772. this._onVrDisplayConnect = null;
  14773. this._onVrDisplayDisconnect = null;
  14774. }
  14775. }
  14776. // Remove from Instances
  14777. var index = Engine.Instances.indexOf(this);
  14778. if (index >= 0) {
  14779. Engine.Instances.splice(index, 1);
  14780. }
  14781. this._workingCanvas = null;
  14782. this._workingContext = null;
  14783. this._currentBufferPointers = [];
  14784. this._renderingCanvas = null;
  14785. this._currentProgram = null;
  14786. this.onResizeObservable.clear();
  14787. this.onCanvasBlurObservable.clear();
  14788. this.onCanvasFocusObservable.clear();
  14789. this.onCanvasPointerOutObservable.clear();
  14790. this.onBeginFrameObservable.clear();
  14791. this.onEndFrameObservable.clear();
  14792. BABYLON.Effect.ResetCache();
  14793. // Abort active requests
  14794. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14795. var request = _a[_i];
  14796. request.abort();
  14797. }
  14798. };
  14799. // Loading screen
  14800. Engine.prototype.displayLoadingUI = function () {
  14801. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14802. return;
  14803. }
  14804. var loadingScreen = this.loadingScreen;
  14805. if (loadingScreen) {
  14806. loadingScreen.displayLoadingUI();
  14807. }
  14808. };
  14809. Engine.prototype.hideLoadingUI = function () {
  14810. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14811. return;
  14812. }
  14813. var loadingScreen = this.loadingScreen;
  14814. if (loadingScreen) {
  14815. loadingScreen.hideLoadingUI();
  14816. }
  14817. };
  14818. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14819. get: function () {
  14820. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14821. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14822. return this._loadingScreen;
  14823. },
  14824. set: function (loadingScreen) {
  14825. this._loadingScreen = loadingScreen;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14831. set: function (text) {
  14832. this.loadingScreen.loadingUIText = text;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14838. set: function (color) {
  14839. this.loadingScreen.loadingUIBackgroundColor = color;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Engine.prototype.attachContextLostEvent = function (callback) {
  14845. if (this._renderingCanvas) {
  14846. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14847. }
  14848. };
  14849. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14850. if (this._renderingCanvas) {
  14851. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14852. }
  14853. };
  14854. Engine.prototype.getVertexShaderSource = function (program) {
  14855. var shaders = this._gl.getAttachedShaders(program);
  14856. if (!shaders) {
  14857. return null;
  14858. }
  14859. return this._gl.getShaderSource(shaders[0]);
  14860. };
  14861. Engine.prototype.getFragmentShaderSource = function (program) {
  14862. var shaders = this._gl.getAttachedShaders(program);
  14863. if (!shaders) {
  14864. return null;
  14865. }
  14866. return this._gl.getShaderSource(shaders[1]);
  14867. };
  14868. Engine.prototype.getError = function () {
  14869. return this._gl.getError();
  14870. };
  14871. // FPS
  14872. Engine.prototype.getFps = function () {
  14873. return this._fps;
  14874. };
  14875. Engine.prototype.getDeltaTime = function () {
  14876. return this._deltaTime;
  14877. };
  14878. Engine.prototype._measureFps = function () {
  14879. this._performanceMonitor.sampleFrame();
  14880. this._fps = this._performanceMonitor.averageFPS;
  14881. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14882. };
  14883. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14884. if (faceIndex === void 0) { faceIndex = -1; }
  14885. var gl = this._gl;
  14886. if (!this._dummyFramebuffer) {
  14887. var dummy = gl.createFramebuffer();
  14888. if (!dummy) {
  14889. throw new Error("Unable to create dummy framebuffer");
  14890. }
  14891. this._dummyFramebuffer = dummy;
  14892. }
  14893. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14894. if (faceIndex > -1) {
  14895. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14896. }
  14897. else {
  14898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14899. }
  14900. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14901. var buffer;
  14902. switch (readType) {
  14903. case gl.UNSIGNED_BYTE:
  14904. buffer = new Uint8Array(4 * width * height);
  14905. readType = gl.UNSIGNED_BYTE;
  14906. break;
  14907. default:
  14908. buffer = new Float32Array(4 * width * height);
  14909. readType = gl.FLOAT;
  14910. break;
  14911. }
  14912. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14913. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14914. return buffer;
  14915. };
  14916. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14917. if (this._webGLVersion > 1) {
  14918. return this._caps.colorBufferFloat;
  14919. }
  14920. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14921. };
  14922. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14923. if (this._webGLVersion > 1) {
  14924. return this._caps.colorBufferFloat;
  14925. }
  14926. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14927. };
  14928. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14929. Engine.prototype._canRenderToFramebuffer = function (type) {
  14930. var gl = this._gl;
  14931. //clear existing errors
  14932. while (gl.getError() !== gl.NO_ERROR) { }
  14933. var successful = true;
  14934. var texture = gl.createTexture();
  14935. gl.bindTexture(gl.TEXTURE_2D, texture);
  14936. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14939. var fb = gl.createFramebuffer();
  14940. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14941. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14942. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14943. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14944. successful = successful && (gl.getError() === gl.NO_ERROR);
  14945. //try render by clearing frame buffer's color buffer
  14946. if (successful) {
  14947. gl.clear(gl.COLOR_BUFFER_BIT);
  14948. successful = successful && (gl.getError() === gl.NO_ERROR);
  14949. }
  14950. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14951. if (successful) {
  14952. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14953. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14954. var readFormat = gl.RGBA;
  14955. var readType = gl.UNSIGNED_BYTE;
  14956. var buffer = new Uint8Array(4);
  14957. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14958. successful = successful && (gl.getError() === gl.NO_ERROR);
  14959. }
  14960. //clean up
  14961. gl.deleteTexture(texture);
  14962. gl.deleteFramebuffer(fb);
  14963. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14964. //clear accumulated errors
  14965. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14966. return successful;
  14967. };
  14968. Engine.prototype._getWebGLTextureType = function (type) {
  14969. if (type === Engine.TEXTURETYPE_FLOAT) {
  14970. return this._gl.FLOAT;
  14971. }
  14972. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14973. // Add Half Float Constant.
  14974. return this._gl.HALF_FLOAT_OES;
  14975. }
  14976. return this._gl.UNSIGNED_BYTE;
  14977. };
  14978. ;
  14979. /** @ignore */
  14980. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14981. if (this._webGLVersion === 1) {
  14982. return this._gl.RGBA;
  14983. }
  14984. if (type === Engine.TEXTURETYPE_FLOAT) {
  14985. if (format) {
  14986. switch (format) {
  14987. case Engine.TEXTUREFORMAT_R32F:
  14988. return this._gl.R32F;
  14989. case Engine.TEXTUREFORMAT_RG32F:
  14990. return this._gl.RG32F;
  14991. case Engine.TEXTUREFORMAT_RGB32F:
  14992. return this._gl.RGB32F;
  14993. }
  14994. }
  14995. return this._gl.RGBA32F;
  14996. }
  14997. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14998. return this._gl.RGBA16F;
  14999. }
  15000. return this._gl.RGBA;
  15001. };
  15002. ;
  15003. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15004. if (type === Engine.TEXTURETYPE_FLOAT) {
  15005. return this._gl.RGBA32F;
  15006. }
  15007. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15008. return this._gl.RGBA16F;
  15009. }
  15010. return this._gl.RGBA8;
  15011. };
  15012. ;
  15013. Engine.prototype.createQuery = function () {
  15014. return this._gl.createQuery();
  15015. };
  15016. Engine.prototype.deleteQuery = function (query) {
  15017. this._gl.deleteQuery(query);
  15018. return this;
  15019. };
  15020. Engine.prototype.isQueryResultAvailable = function (query) {
  15021. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15022. };
  15023. Engine.prototype.getQueryResult = function (query) {
  15024. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15025. };
  15026. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15027. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15028. this._gl.beginQuery(glAlgorithm, query);
  15029. return this;
  15030. };
  15031. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15032. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15033. this._gl.endQuery(glAlgorithm);
  15034. return this;
  15035. };
  15036. /* Time queries */
  15037. Engine.prototype._createTimeQuery = function () {
  15038. var timerQuery = this._caps.timerQuery;
  15039. if (timerQuery.createQueryEXT) {
  15040. return timerQuery.createQueryEXT();
  15041. }
  15042. return this.createQuery();
  15043. };
  15044. Engine.prototype._deleteTimeQuery = function (query) {
  15045. var timerQuery = this._caps.timerQuery;
  15046. if (timerQuery.deleteQueryEXT) {
  15047. timerQuery.deleteQueryEXT(query);
  15048. return;
  15049. }
  15050. this.deleteQuery(query);
  15051. };
  15052. Engine.prototype._getTimeQueryResult = function (query) {
  15053. var timerQuery = this._caps.timerQuery;
  15054. if (timerQuery.getQueryObjectEXT) {
  15055. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15056. }
  15057. return this.getQueryResult(query);
  15058. };
  15059. Engine.prototype._getTimeQueryAvailability = function (query) {
  15060. var timerQuery = this._caps.timerQuery;
  15061. if (timerQuery.getQueryObjectEXT) {
  15062. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15063. }
  15064. return this.isQueryResultAvailable(query);
  15065. };
  15066. Engine.prototype.startTimeQuery = function () {
  15067. var timerQuery = this._caps.timerQuery;
  15068. if (!timerQuery) {
  15069. return null;
  15070. }
  15071. var token = new BABYLON._TimeToken();
  15072. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15073. if (this._caps.canUseTimestampForTimerQuery) {
  15074. token._startTimeQuery = this._createTimeQuery();
  15075. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15076. }
  15077. else {
  15078. if (this._currentNonTimestampToken) {
  15079. return this._currentNonTimestampToken;
  15080. }
  15081. token._timeElapsedQuery = this._createTimeQuery();
  15082. if (timerQuery.beginQueryEXT) {
  15083. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15084. }
  15085. else {
  15086. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15087. }
  15088. this._currentNonTimestampToken = token;
  15089. }
  15090. return token;
  15091. };
  15092. Engine.prototype.endTimeQuery = function (token) {
  15093. var timerQuery = this._caps.timerQuery;
  15094. if (!timerQuery || !token) {
  15095. return -1;
  15096. }
  15097. if (this._caps.canUseTimestampForTimerQuery) {
  15098. if (!token._startTimeQuery) {
  15099. return -1;
  15100. }
  15101. if (!token._endTimeQuery) {
  15102. token._endTimeQuery = this._createTimeQuery();
  15103. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15104. }
  15105. }
  15106. else if (!token._timeElapsedQueryEnded) {
  15107. if (!token._timeElapsedQuery) {
  15108. return -1;
  15109. }
  15110. if (timerQuery.endQueryEXT) {
  15111. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15112. }
  15113. else {
  15114. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15115. }
  15116. token._timeElapsedQueryEnded = true;
  15117. }
  15118. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15119. var available = false;
  15120. if (token._endTimeQuery) {
  15121. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15122. }
  15123. else if (token._timeElapsedQuery) {
  15124. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15125. }
  15126. if (available && !disjoint) {
  15127. var result = 0;
  15128. if (this._caps.canUseTimestampForTimerQuery) {
  15129. if (!token._startTimeQuery || !token._endTimeQuery) {
  15130. return -1;
  15131. }
  15132. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15133. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15134. result = timeEnd - timeStart;
  15135. this._deleteTimeQuery(token._startTimeQuery);
  15136. this._deleteTimeQuery(token._endTimeQuery);
  15137. token._startTimeQuery = null;
  15138. token._endTimeQuery = null;
  15139. }
  15140. else {
  15141. if (!token._timeElapsedQuery) {
  15142. return -1;
  15143. }
  15144. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15145. this._deleteTimeQuery(token._timeElapsedQuery);
  15146. token._timeElapsedQuery = null;
  15147. token._timeElapsedQueryEnded = false;
  15148. this._currentNonTimestampToken = null;
  15149. }
  15150. return result;
  15151. }
  15152. return -1;
  15153. };
  15154. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15155. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15156. };
  15157. // Transform feedback
  15158. Engine.prototype.createTransformFeedback = function () {
  15159. return this._gl.createTransformFeedback();
  15160. };
  15161. Engine.prototype.deleteTransformFeedback = function (value) {
  15162. this._gl.deleteTransformFeedback(value);
  15163. };
  15164. Engine.prototype.bindTransformFeedback = function (value) {
  15165. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15166. };
  15167. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15168. if (usePoints === void 0) { usePoints = true; }
  15169. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15170. };
  15171. Engine.prototype.endTransformFeedback = function () {
  15172. this._gl.endTransformFeedback();
  15173. };
  15174. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15175. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15176. };
  15177. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15178. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15179. };
  15180. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15181. var _this = this;
  15182. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15183. this._activeRequests.push(request);
  15184. request.onCompleteObservable.add(function (request) {
  15185. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15186. });
  15187. return request;
  15188. };
  15189. /** @ignore */
  15190. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15191. var _this = this;
  15192. return new Promise(function (resolve, reject) {
  15193. _this._loadFile(url, function (data) {
  15194. resolve(data);
  15195. }, undefined, database, useArrayBuffer, function (request, exception) {
  15196. reject(exception);
  15197. });
  15198. });
  15199. };
  15200. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15201. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15202. var onload = function (data) {
  15203. loadedFiles[index] = data;
  15204. loadedFiles._internalCount++;
  15205. if (loadedFiles._internalCount === 6) {
  15206. onfinish(loadedFiles);
  15207. }
  15208. };
  15209. var onerror = function (request, exception) {
  15210. if (onErrorCallBack && request) {
  15211. onErrorCallBack(request.status + " " + request.statusText, exception);
  15212. }
  15213. };
  15214. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15215. };
  15216. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15217. if (onError === void 0) { onError = null; }
  15218. var loadedFiles = [];
  15219. loadedFiles._internalCount = 0;
  15220. for (var index = 0; index < 6; index++) {
  15221. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15222. }
  15223. };
  15224. // Statics
  15225. Engine.isSupported = function () {
  15226. try {
  15227. var tempcanvas = document.createElement("canvas");
  15228. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15229. return gl != null && !!window.WebGLRenderingContext;
  15230. }
  15231. catch (e) {
  15232. return false;
  15233. }
  15234. };
  15235. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15236. Engine.ExceptionList = [
  15237. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15238. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15239. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15240. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15241. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15242. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15243. ];
  15244. Engine.Instances = new Array();
  15245. // Const statics
  15246. Engine._ALPHA_DISABLE = 0;
  15247. Engine._ALPHA_ADD = 1;
  15248. Engine._ALPHA_COMBINE = 2;
  15249. Engine._ALPHA_SUBTRACT = 3;
  15250. Engine._ALPHA_MULTIPLY = 4;
  15251. Engine._ALPHA_MAXIMIZED = 5;
  15252. Engine._ALPHA_ONEONE = 6;
  15253. Engine._ALPHA_PREMULTIPLIED = 7;
  15254. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15255. Engine._ALPHA_INTERPOLATE = 9;
  15256. Engine._ALPHA_SCREENMODE = 10;
  15257. Engine._DELAYLOADSTATE_NONE = 0;
  15258. Engine._DELAYLOADSTATE_LOADED = 1;
  15259. Engine._DELAYLOADSTATE_LOADING = 2;
  15260. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15261. Engine._TEXTUREFORMAT_ALPHA = 0;
  15262. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15263. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15264. Engine._TEXTUREFORMAT_RGB = 4;
  15265. Engine._TEXTUREFORMAT_RGBA = 5;
  15266. Engine._TEXTUREFORMAT_R32F = 6;
  15267. Engine._TEXTUREFORMAT_RG32F = 7;
  15268. Engine._TEXTUREFORMAT_RGB32F = 8;
  15269. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15270. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15271. Engine._TEXTURETYPE_FLOAT = 1;
  15272. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15273. // Depht or Stencil test Constants.
  15274. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15275. 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.
  15276. 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.
  15277. 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.
  15278. 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.
  15279. 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.
  15280. 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.
  15281. 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.
  15282. // Stencil Actions Constants.
  15283. Engine._KEEP = 0x1E00;
  15284. Engine._REPLACE = 0x1E01;
  15285. Engine._INCR = 0x1E02;
  15286. Engine._DECR = 0x1E03;
  15287. Engine._INVERT = 0x150A;
  15288. Engine._INCR_WRAP = 0x8507;
  15289. Engine._DECR_WRAP = 0x8508;
  15290. // Texture rescaling mode
  15291. Engine._SCALEMODE_FLOOR = 1;
  15292. Engine._SCALEMODE_NEAREST = 2;
  15293. Engine._SCALEMODE_CEILING = 3;
  15294. // Updatable statics so stick with vars here
  15295. Engine.CollisionsEpsilon = 0.001;
  15296. Engine.CodeRepository = "src/";
  15297. Engine.ShadersRepository = "src/Shaders/";
  15298. return Engine;
  15299. }());
  15300. BABYLON.Engine = Engine;
  15301. })(BABYLON || (BABYLON = {}));
  15302. //# sourceMappingURL=babylon.engine.js.map
  15303. var BABYLON;
  15304. (function (BABYLON) {
  15305. /**
  15306. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15307. */
  15308. var Node = /** @class */ (function () {
  15309. /**
  15310. * Creates a new Node
  15311. * @param {string} name - the name and id to be given to this node
  15312. * @param {BABYLON.Scene} the scene this node will be added to
  15313. */
  15314. function Node(name, scene) {
  15315. if (scene === void 0) { scene = null; }
  15316. /**
  15317. * Gets or sets a string used to store user defined state for the node
  15318. */
  15319. this.state = "";
  15320. /**
  15321. * Gets or sets an object used to store user defined information for the node
  15322. */
  15323. this.metadata = null;
  15324. /**
  15325. * Gets or sets a boolean used to define if the node must be serialized
  15326. */
  15327. this.doNotSerialize = false;
  15328. /** @ignore */
  15329. this._isDisposed = false;
  15330. /**
  15331. * Gets a list of {BABYLON.Animation} associated with the node
  15332. */
  15333. this.animations = new Array();
  15334. this._ranges = {};
  15335. this._isEnabled = true;
  15336. this._isReady = true;
  15337. /** @ignore */
  15338. this._currentRenderId = -1;
  15339. this._parentRenderId = -1;
  15340. this._animationPropertiesOverride = null;
  15341. /**
  15342. * An event triggered when the mesh is disposed
  15343. * @type {BABYLON.Observable}
  15344. */
  15345. this.onDisposeObservable = new BABYLON.Observable();
  15346. // Behaviors
  15347. this._behaviors = new Array();
  15348. this.name = name;
  15349. this.id = name;
  15350. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15351. this.uniqueId = this._scene.getUniqueId();
  15352. this._initCache();
  15353. }
  15354. /**
  15355. * Gets a boolean indicating if the node has been disposed
  15356. * @returns true if the node was disposed
  15357. */
  15358. Node.prototype.isDisposed = function () {
  15359. return this._isDisposed;
  15360. };
  15361. Object.defineProperty(Node.prototype, "parent", {
  15362. get: function () {
  15363. return this._parentNode;
  15364. },
  15365. /**
  15366. * Gets or sets the parent of the node
  15367. */
  15368. set: function (parent) {
  15369. if (this._parentNode === parent) {
  15370. return;
  15371. }
  15372. // Remove self from list of children of parent
  15373. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15374. var index = this._parentNode._children.indexOf(this);
  15375. if (index !== -1) {
  15376. this._parentNode._children.splice(index, 1);
  15377. }
  15378. }
  15379. // Store new parent
  15380. this._parentNode = parent;
  15381. // Add as child to new parent
  15382. if (this._parentNode) {
  15383. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15384. this._parentNode._children = new Array();
  15385. }
  15386. this._parentNode._children.push(this);
  15387. }
  15388. },
  15389. enumerable: true,
  15390. configurable: true
  15391. });
  15392. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15393. /**
  15394. * Gets or sets the animation properties override
  15395. */
  15396. get: function () {
  15397. return this._animationPropertiesOverride;
  15398. },
  15399. set: function (value) {
  15400. this._animationPropertiesOverride = value;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. /**
  15406. * Gets a string idenfifying the name of the class
  15407. * @returns "Node" string
  15408. */
  15409. Node.prototype.getClassName = function () {
  15410. return "Node";
  15411. };
  15412. Object.defineProperty(Node.prototype, "onDispose", {
  15413. /**
  15414. * Sets a callback that will be raised when the node will be disposed
  15415. */
  15416. set: function (callback) {
  15417. if (this._onDisposeObserver) {
  15418. this.onDisposeObservable.remove(this._onDisposeObserver);
  15419. }
  15420. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15421. },
  15422. enumerable: true,
  15423. configurable: true
  15424. });
  15425. /**
  15426. * Gets the scene of the node
  15427. * @returns a {BABYLON.Scene}
  15428. */
  15429. Node.prototype.getScene = function () {
  15430. return this._scene;
  15431. };
  15432. /**
  15433. * Gets the engine of the node
  15434. * @returns a {BABYLON.Engine}
  15435. */
  15436. Node.prototype.getEngine = function () {
  15437. return this._scene.getEngine();
  15438. };
  15439. /**
  15440. * Attach a behavior to the node
  15441. * @see http://doc.babylonjs.com/features/behaviour
  15442. * @param behavior defines the behavior to attach
  15443. * @returns the current Node
  15444. */
  15445. Node.prototype.addBehavior = function (behavior) {
  15446. var _this = this;
  15447. var index = this._behaviors.indexOf(behavior);
  15448. if (index !== -1) {
  15449. return this;
  15450. }
  15451. behavior.init();
  15452. if (this._scene.isLoading) {
  15453. // We defer the attach when the scene will be loaded
  15454. var observer = this._scene.onDataLoadedObservable.add(function () {
  15455. behavior.attach(_this);
  15456. setTimeout(function () {
  15457. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15458. _this._scene.onDataLoadedObservable.remove(observer);
  15459. }, 0);
  15460. });
  15461. }
  15462. else {
  15463. behavior.attach(this);
  15464. }
  15465. this._behaviors.push(behavior);
  15466. return this;
  15467. };
  15468. /**
  15469. * Remove an attached behavior
  15470. * @see http://doc.babylonjs.com/features/behaviour
  15471. * @param behavior defines the behavior to attach
  15472. * @returns the current Node
  15473. */
  15474. Node.prototype.removeBehavior = function (behavior) {
  15475. var index = this._behaviors.indexOf(behavior);
  15476. if (index === -1) {
  15477. return this;
  15478. }
  15479. this._behaviors[index].detach();
  15480. this._behaviors.splice(index, 1);
  15481. return this;
  15482. };
  15483. Object.defineProperty(Node.prototype, "behaviors", {
  15484. /**
  15485. * Gets the list of attached behaviors
  15486. * @see http://doc.babylonjs.com/features/behaviour
  15487. */
  15488. get: function () {
  15489. return this._behaviors;
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. /**
  15495. * Gets an attached behavior by name
  15496. * @param name defines the name of the behavior to look for
  15497. * @see http://doc.babylonjs.com/features/behaviour
  15498. * @returns null if behavior was not found else the requested behavior
  15499. */
  15500. Node.prototype.getBehaviorByName = function (name) {
  15501. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15502. var behavior = _a[_i];
  15503. if (behavior.name === name) {
  15504. return behavior;
  15505. }
  15506. }
  15507. return null;
  15508. };
  15509. /**
  15510. * Returns the world matrix of the node
  15511. * @returns a matrix containing the node's world matrix
  15512. */
  15513. Node.prototype.getWorldMatrix = function () {
  15514. return BABYLON.Matrix.Identity();
  15515. };
  15516. // override it in derived class if you add new variables to the cache
  15517. // and call the parent class method
  15518. /** @ignore */
  15519. Node.prototype._initCache = function () {
  15520. this._cache = {};
  15521. this._cache.parent = undefined;
  15522. };
  15523. /** @ignore */
  15524. Node.prototype.updateCache = function (force) {
  15525. if (!force && this.isSynchronized())
  15526. return;
  15527. this._cache.parent = this.parent;
  15528. this._updateCache();
  15529. };
  15530. // override it in derived class if you add new variables to the cache
  15531. // and call the parent class method if !ignoreParentClass
  15532. /** @ignore */
  15533. Node.prototype._updateCache = function (ignoreParentClass) {
  15534. };
  15535. // override it in derived class if you add new variables to the cache
  15536. /** @ignore */
  15537. Node.prototype._isSynchronized = function () {
  15538. return true;
  15539. };
  15540. /** @ignore */
  15541. Node.prototype._markSyncedWithParent = function () {
  15542. if (this.parent) {
  15543. this._parentRenderId = this.parent._currentRenderId;
  15544. }
  15545. };
  15546. /** @ignore */
  15547. Node.prototype.isSynchronizedWithParent = function () {
  15548. if (!this.parent) {
  15549. return true;
  15550. }
  15551. if (this._parentRenderId !== this.parent._currentRenderId) {
  15552. return false;
  15553. }
  15554. return this.parent.isSynchronized();
  15555. };
  15556. /** @ignore */
  15557. Node.prototype.isSynchronized = function (updateCache) {
  15558. var check = this.hasNewParent();
  15559. check = check || !this.isSynchronizedWithParent();
  15560. check = check || !this._isSynchronized();
  15561. if (updateCache)
  15562. this.updateCache(true);
  15563. return !check;
  15564. };
  15565. /** @ignore */
  15566. Node.prototype.hasNewParent = function (update) {
  15567. if (this._cache.parent === this.parent)
  15568. return false;
  15569. if (update)
  15570. this._cache.parent = this.parent;
  15571. return true;
  15572. };
  15573. /**
  15574. * Is this node ready to be used/rendered
  15575. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15576. * @return true if the node is ready
  15577. */
  15578. Node.prototype.isReady = function (completeCheck) {
  15579. if (completeCheck === void 0) { completeCheck = false; }
  15580. return this._isReady;
  15581. };
  15582. /**
  15583. * Is this node enabled?
  15584. * 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
  15585. * @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
  15586. * @return whether this node (and its parent) is enabled
  15587. * @see setEnabled
  15588. */
  15589. Node.prototype.isEnabled = function (checkAncestors) {
  15590. if (checkAncestors === void 0) { checkAncestors = true; }
  15591. if (checkAncestors === false) {
  15592. return this._isEnabled;
  15593. }
  15594. if (this._isEnabled === false) {
  15595. return false;
  15596. }
  15597. if (this.parent !== undefined && this.parent !== null) {
  15598. return this.parent.isEnabled(checkAncestors);
  15599. }
  15600. return true;
  15601. };
  15602. /**
  15603. * Set the enabled state of this node
  15604. * @param value defines the new enabled state
  15605. * @see isEnabled
  15606. */
  15607. Node.prototype.setEnabled = function (value) {
  15608. this._isEnabled = value;
  15609. };
  15610. /**
  15611. * Is this node a descendant of the given node?
  15612. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15613. * @param ancestor defines the parent node to inspect
  15614. * @see parent
  15615. * @returns a boolean indicating if this node is a descendant of the given node
  15616. */
  15617. Node.prototype.isDescendantOf = function (ancestor) {
  15618. if (this.parent) {
  15619. if (this.parent === ancestor) {
  15620. return true;
  15621. }
  15622. return this.parent.isDescendantOf(ancestor);
  15623. }
  15624. return false;
  15625. };
  15626. /** @ignore */
  15627. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15628. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15629. if (!this._children) {
  15630. return;
  15631. }
  15632. for (var index = 0; index < this._children.length; index++) {
  15633. var item = this._children[index];
  15634. if (!predicate || predicate(item)) {
  15635. results.push(item);
  15636. }
  15637. if (!directDescendantsOnly) {
  15638. item._getDescendants(results, false, predicate);
  15639. }
  15640. }
  15641. };
  15642. /**
  15643. * Will return all nodes that have this node as ascendant
  15644. * @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
  15645. * @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
  15646. * @return all children nodes of all types
  15647. */
  15648. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15649. var results = new Array();
  15650. this._getDescendants(results, directDescendantsOnly, predicate);
  15651. return results;
  15652. };
  15653. /**
  15654. * Get all child-meshes of this node
  15655. * @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
  15656. * @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
  15657. * @returns an array of {BABYLON.AbstractMesh}
  15658. */
  15659. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15660. var results = [];
  15661. this._getDescendants(results, directDescendantsOnly, function (node) {
  15662. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15663. });
  15664. return results;
  15665. };
  15666. /**
  15667. * Get all child-transformNodes of this node
  15668. * @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
  15669. * @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
  15670. * @returns an array of {BABYLON.TransformNode}
  15671. */
  15672. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15673. var results = [];
  15674. this._getDescendants(results, directDescendantsOnly, function (node) {
  15675. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15676. });
  15677. return results;
  15678. };
  15679. /**
  15680. * Get all direct children of this node
  15681. * @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
  15682. * @returns an array of {BABYLON.Node}
  15683. */
  15684. Node.prototype.getChildren = function (predicate) {
  15685. return this.getDescendants(true, predicate);
  15686. };
  15687. /** @ignore */
  15688. Node.prototype._setReady = function (state) {
  15689. if (state === this._isReady) {
  15690. return;
  15691. }
  15692. if (!state) {
  15693. this._isReady = false;
  15694. return;
  15695. }
  15696. this._isReady = true;
  15697. if (this.onReady) {
  15698. this.onReady(this);
  15699. }
  15700. };
  15701. /**
  15702. * Get an animation by name
  15703. * @param name defines the name of the animation to look for
  15704. * @returns null if not found else the requested animation
  15705. */
  15706. Node.prototype.getAnimationByName = function (name) {
  15707. for (var i = 0; i < this.animations.length; i++) {
  15708. var animation = this.animations[i];
  15709. if (animation.name === name) {
  15710. return animation;
  15711. }
  15712. }
  15713. return null;
  15714. };
  15715. /**
  15716. * Creates an animation range for this node
  15717. * @param name defines the name of the range
  15718. * @param from defines the starting key
  15719. * @param to defines the end key
  15720. */
  15721. Node.prototype.createAnimationRange = function (name, from, to) {
  15722. // check name not already in use
  15723. if (!this._ranges[name]) {
  15724. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15725. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15726. if (this.animations[i]) {
  15727. this.animations[i].createRange(name, from, to);
  15728. }
  15729. }
  15730. }
  15731. };
  15732. /**
  15733. * Delete a specific animation range
  15734. * @param name defines the name of the range to delete
  15735. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15736. */
  15737. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15738. if (deleteFrames === void 0) { deleteFrames = true; }
  15739. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15740. if (this.animations[i]) {
  15741. this.animations[i].deleteRange(name, deleteFrames);
  15742. }
  15743. }
  15744. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15745. };
  15746. /**
  15747. * Get an animation range by name
  15748. * @param name defines the name of the animation range to look for
  15749. * @returns null if not found else the requested animation range
  15750. */
  15751. Node.prototype.getAnimationRange = function (name) {
  15752. return this._ranges[name];
  15753. };
  15754. /**
  15755. * Will start the animation sequence
  15756. * @param name defines the range frames for animation sequence
  15757. * @param loop defines if the animation should loop (false by default)
  15758. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15759. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15760. * @returns the object created for this animation. If range does not exist, it will return null
  15761. */
  15762. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15763. var range = this.getAnimationRange(name);
  15764. if (!range) {
  15765. return null;
  15766. }
  15767. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15768. };
  15769. /**
  15770. * Serialize animation ranges into a JSON compatible object
  15771. * @returns serialization object
  15772. */
  15773. Node.prototype.serializeAnimationRanges = function () {
  15774. var serializationRanges = [];
  15775. for (var name in this._ranges) {
  15776. var localRange = this._ranges[name];
  15777. if (!localRange) {
  15778. continue;
  15779. }
  15780. var range = {};
  15781. range.name = name;
  15782. range.from = localRange.from;
  15783. range.to = localRange.to;
  15784. serializationRanges.push(range);
  15785. }
  15786. return serializationRanges;
  15787. };
  15788. /**
  15789. * Computes the world matrix of the node
  15790. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15791. * @returns the world matrix
  15792. */
  15793. Node.prototype.computeWorldMatrix = function (force) {
  15794. return BABYLON.Matrix.Identity();
  15795. };
  15796. /**
  15797. * Releases all associated resources
  15798. */
  15799. Node.prototype.dispose = function () {
  15800. this.parent = null;
  15801. // Callback
  15802. this.onDisposeObservable.notifyObservers(this);
  15803. this.onDisposeObservable.clear();
  15804. // Behaviors
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. behavior.detach();
  15808. }
  15809. this._behaviors = [];
  15810. this._isDisposed = true;
  15811. };
  15812. /**
  15813. * Parse animation range data from a serialization object and store them into a given node
  15814. * @param node defines where to store the animation ranges
  15815. * @param parsedNode defines the serialization object to read data from
  15816. * @param scene defines the hosting scene
  15817. */
  15818. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15819. if (parsedNode.ranges) {
  15820. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15821. var data = parsedNode.ranges[index];
  15822. node.createAnimationRange(data.name, data.from, data.to);
  15823. }
  15824. }
  15825. };
  15826. __decorate([
  15827. BABYLON.serialize()
  15828. ], Node.prototype, "name", void 0);
  15829. __decorate([
  15830. BABYLON.serialize()
  15831. ], Node.prototype, "id", void 0);
  15832. __decorate([
  15833. BABYLON.serialize()
  15834. ], Node.prototype, "uniqueId", void 0);
  15835. __decorate([
  15836. BABYLON.serialize()
  15837. ], Node.prototype, "state", void 0);
  15838. __decorate([
  15839. BABYLON.serialize()
  15840. ], Node.prototype, "metadata", void 0);
  15841. return Node;
  15842. }());
  15843. BABYLON.Node = Node;
  15844. })(BABYLON || (BABYLON = {}));
  15845. //# sourceMappingURL=babylon.node.js.map
  15846. var BABYLON;
  15847. (function (BABYLON) {
  15848. var BoundingSphere = /** @class */ (function () {
  15849. function BoundingSphere(minimum, maximum) {
  15850. this.minimum = minimum;
  15851. this.maximum = maximum;
  15852. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15853. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15854. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15855. this.radius = distance * 0.5;
  15856. this.centerWorld = BABYLON.Vector3.Zero();
  15857. this._update(BABYLON.Matrix.Identity());
  15858. }
  15859. // Methods
  15860. BoundingSphere.prototype._update = function (world) {
  15861. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15862. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15863. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15864. };
  15865. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15866. for (var i = 0; i < 6; i++) {
  15867. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15868. return false;
  15869. }
  15870. return true;
  15871. };
  15872. BoundingSphere.prototype.intersectsPoint = function (point) {
  15873. var x = this.centerWorld.x - point.x;
  15874. var y = this.centerWorld.y - point.y;
  15875. var z = this.centerWorld.z - point.z;
  15876. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15877. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15878. return false;
  15879. return true;
  15880. };
  15881. // Statics
  15882. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15883. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15884. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15885. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15886. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15887. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15888. return false;
  15889. return true;
  15890. };
  15891. return BoundingSphere;
  15892. }());
  15893. BABYLON.BoundingSphere = BoundingSphere;
  15894. })(BABYLON || (BABYLON = {}));
  15895. //# sourceMappingURL=babylon.boundingSphere.js.map
  15896. var BABYLON;
  15897. (function (BABYLON) {
  15898. var BoundingBox = /** @class */ (function () {
  15899. function BoundingBox(minimum, maximum) {
  15900. this.minimum = minimum;
  15901. this.maximum = maximum;
  15902. this.vectors = new Array();
  15903. this.vectorsWorld = new Array();
  15904. // Bounding vectors
  15905. this.vectors.push(this.minimum.clone());
  15906. this.vectors.push(this.maximum.clone());
  15907. this.vectors.push(this.minimum.clone());
  15908. this.vectors[2].x = this.maximum.x;
  15909. this.vectors.push(this.minimum.clone());
  15910. this.vectors[3].y = this.maximum.y;
  15911. this.vectors.push(this.minimum.clone());
  15912. this.vectors[4].z = this.maximum.z;
  15913. this.vectors.push(this.maximum.clone());
  15914. this.vectors[5].z = this.minimum.z;
  15915. this.vectors.push(this.maximum.clone());
  15916. this.vectors[6].x = this.minimum.x;
  15917. this.vectors.push(this.maximum.clone());
  15918. this.vectors[7].y = this.minimum.y;
  15919. // OBB
  15920. this.center = this.maximum.add(this.minimum).scale(0.5);
  15921. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15922. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15923. // World
  15924. for (var index = 0; index < this.vectors.length; index++) {
  15925. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15926. }
  15927. this.minimumWorld = BABYLON.Vector3.Zero();
  15928. this.maximumWorld = BABYLON.Vector3.Zero();
  15929. this.centerWorld = BABYLON.Vector3.Zero();
  15930. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15931. this._update(BABYLON.Matrix.Identity());
  15932. }
  15933. // Methods
  15934. BoundingBox.prototype.getWorldMatrix = function () {
  15935. return this._worldMatrix;
  15936. };
  15937. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15938. this._worldMatrix.copyFrom(matrix);
  15939. return this;
  15940. };
  15941. BoundingBox.prototype._update = function (world) {
  15942. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15943. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15944. for (var index = 0; index < this.vectors.length; index++) {
  15945. var v = this.vectorsWorld[index];
  15946. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15947. if (v.x < this.minimumWorld.x)
  15948. this.minimumWorld.x = v.x;
  15949. if (v.y < this.minimumWorld.y)
  15950. this.minimumWorld.y = v.y;
  15951. if (v.z < this.minimumWorld.z)
  15952. this.minimumWorld.z = v.z;
  15953. if (v.x > this.maximumWorld.x)
  15954. this.maximumWorld.x = v.x;
  15955. if (v.y > this.maximumWorld.y)
  15956. this.maximumWorld.y = v.y;
  15957. if (v.z > this.maximumWorld.z)
  15958. this.maximumWorld.z = v.z;
  15959. }
  15960. // Extend
  15961. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15962. this.extendSizeWorld.scaleInPlace(0.5);
  15963. // OBB
  15964. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15965. this.centerWorld.scaleInPlace(0.5);
  15966. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15967. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15968. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15969. this._worldMatrix = world;
  15970. };
  15971. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15972. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15973. };
  15974. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15975. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15976. };
  15977. BoundingBox.prototype.intersectsPoint = function (point) {
  15978. var delta = -BABYLON.Epsilon;
  15979. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15980. return false;
  15981. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15982. return false;
  15983. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15984. return false;
  15985. return true;
  15986. };
  15987. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15988. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15989. };
  15990. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15991. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15992. return false;
  15993. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15994. return false;
  15995. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15996. return false;
  15997. return true;
  15998. };
  15999. // Statics
  16000. BoundingBox.Intersects = function (box0, box1) {
  16001. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16002. return false;
  16003. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16004. return false;
  16005. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16006. return false;
  16007. return true;
  16008. };
  16009. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16010. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16011. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16012. return (num <= (sphereRadius * sphereRadius));
  16013. };
  16014. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16015. for (var p = 0; p < 6; p++) {
  16016. for (var i = 0; i < 8; i++) {
  16017. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16018. return false;
  16019. }
  16020. }
  16021. }
  16022. return true;
  16023. };
  16024. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16025. for (var p = 0; p < 6; p++) {
  16026. var inCount = 8;
  16027. for (var i = 0; i < 8; i++) {
  16028. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16029. --inCount;
  16030. }
  16031. else {
  16032. break;
  16033. }
  16034. }
  16035. if (inCount === 0)
  16036. return false;
  16037. }
  16038. return true;
  16039. };
  16040. return BoundingBox;
  16041. }());
  16042. BABYLON.BoundingBox = BoundingBox;
  16043. })(BABYLON || (BABYLON = {}));
  16044. //# sourceMappingURL=babylon.boundingBox.js.map
  16045. var BABYLON;
  16046. (function (BABYLON) {
  16047. var computeBoxExtents = function (axis, box) {
  16048. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16049. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16050. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16051. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16052. var r = r0 + r1 + r2;
  16053. return {
  16054. min: p - r,
  16055. max: p + r
  16056. };
  16057. };
  16058. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16059. var axisOverlap = function (axis, box0, box1) {
  16060. var result0 = computeBoxExtents(axis, box0);
  16061. var result1 = computeBoxExtents(axis, box1);
  16062. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16063. };
  16064. var BoundingInfo = /** @class */ (function () {
  16065. function BoundingInfo(minimum, maximum) {
  16066. this.minimum = minimum;
  16067. this.maximum = maximum;
  16068. this._isLocked = false;
  16069. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16070. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16071. }
  16072. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16073. get: function () {
  16074. return this._isLocked;
  16075. },
  16076. set: function (value) {
  16077. this._isLocked = value;
  16078. },
  16079. enumerable: true,
  16080. configurable: true
  16081. });
  16082. // Methods
  16083. BoundingInfo.prototype.update = function (world) {
  16084. if (this._isLocked) {
  16085. return;
  16086. }
  16087. this.boundingBox._update(world);
  16088. this.boundingSphere._update(world);
  16089. };
  16090. /**
  16091. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16092. * @param center New center of the bounding info
  16093. * @param extend New extend of the bounding info
  16094. */
  16095. BoundingInfo.prototype.centerOn = function (center, extend) {
  16096. this.minimum = center.subtract(extend);
  16097. this.maximum = center.add(extend);
  16098. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16099. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16100. return this;
  16101. };
  16102. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16103. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16104. return false;
  16105. return this.boundingBox.isInFrustum(frustumPlanes);
  16106. };
  16107. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16108. /**
  16109. * Gets the world distance between the min and max points of the bounding box
  16110. */
  16111. get: function () {
  16112. var boundingBox = this.boundingBox;
  16113. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16114. return size.length();
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16120. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16121. };
  16122. BoundingInfo.prototype._checkCollision = function (collider) {
  16123. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16124. };
  16125. BoundingInfo.prototype.intersectsPoint = function (point) {
  16126. if (!this.boundingSphere.centerWorld) {
  16127. return false;
  16128. }
  16129. if (!this.boundingSphere.intersectsPoint(point)) {
  16130. return false;
  16131. }
  16132. if (!this.boundingBox.intersectsPoint(point)) {
  16133. return false;
  16134. }
  16135. return true;
  16136. };
  16137. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16138. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16139. return false;
  16140. }
  16141. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16142. return false;
  16143. }
  16144. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16145. return false;
  16146. }
  16147. if (!precise) {
  16148. return true;
  16149. }
  16150. var box0 = this.boundingBox;
  16151. var box1 = boundingInfo.boundingBox;
  16152. if (!axisOverlap(box0.directions[0], box0, box1))
  16153. return false;
  16154. if (!axisOverlap(box0.directions[1], box0, box1))
  16155. return false;
  16156. if (!axisOverlap(box0.directions[2], box0, box1))
  16157. return false;
  16158. if (!axisOverlap(box1.directions[0], box0, box1))
  16159. return false;
  16160. if (!axisOverlap(box1.directions[1], box0, box1))
  16161. return false;
  16162. if (!axisOverlap(box1.directions[2], box0, box1))
  16163. return false;
  16164. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16165. return false;
  16166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16167. return false;
  16168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16169. return false;
  16170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16171. return false;
  16172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16173. return false;
  16174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16175. return false;
  16176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16177. return false;
  16178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16179. return false;
  16180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16181. return false;
  16182. return true;
  16183. };
  16184. return BoundingInfo;
  16185. }());
  16186. BABYLON.BoundingInfo = BoundingInfo;
  16187. })(BABYLON || (BABYLON = {}));
  16188. //# sourceMappingURL=babylon.boundingInfo.js.map
  16189. var BABYLON;
  16190. (function (BABYLON) {
  16191. var TransformNode = /** @class */ (function (_super) {
  16192. __extends(TransformNode, _super);
  16193. function TransformNode(name, scene, isPure) {
  16194. if (scene === void 0) { scene = null; }
  16195. if (isPure === void 0) { isPure = true; }
  16196. var _this = _super.call(this, name, scene) || this;
  16197. // Properties
  16198. _this._rotation = BABYLON.Vector3.Zero();
  16199. _this._scaling = BABYLON.Vector3.One();
  16200. _this._isDirty = false;
  16201. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16202. _this.scalingDeterminant = 1;
  16203. _this.infiniteDistance = false;
  16204. _this.position = BABYLON.Vector3.Zero();
  16205. _this._localWorld = BABYLON.Matrix.Zero();
  16206. _this._worldMatrix = BABYLON.Matrix.Zero();
  16207. _this._worldMatrixDeterminant = 0;
  16208. _this._absolutePosition = BABYLON.Vector3.Zero();
  16209. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16210. _this._postMultiplyPivotMatrix = false;
  16211. _this._isWorldMatrixFrozen = false;
  16212. /**
  16213. * An event triggered after the world matrix is updated
  16214. * @type {BABYLON.Observable}
  16215. */
  16216. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16217. _this._nonUniformScaling = false;
  16218. if (isPure) {
  16219. _this.getScene().addTransformNode(_this);
  16220. }
  16221. return _this;
  16222. }
  16223. Object.defineProperty(TransformNode.prototype, "rotation", {
  16224. /**
  16225. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16226. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16227. * Default : (0.0, 0.0, 0.0)
  16228. */
  16229. get: function () {
  16230. return this._rotation;
  16231. },
  16232. set: function (newRotation) {
  16233. this._rotation = newRotation;
  16234. },
  16235. enumerable: true,
  16236. configurable: true
  16237. });
  16238. Object.defineProperty(TransformNode.prototype, "scaling", {
  16239. /**
  16240. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16241. * Default : (1.0, 1.0, 1.0)
  16242. */
  16243. get: function () {
  16244. return this._scaling;
  16245. },
  16246. /**
  16247. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16248. * Default : (1.0, 1.0, 1.0)
  16249. */
  16250. set: function (newScaling) {
  16251. this._scaling = newScaling;
  16252. },
  16253. enumerable: true,
  16254. configurable: true
  16255. });
  16256. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16257. /**
  16258. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16259. * It's null by default.
  16260. * 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)
  16261. */
  16262. get: function () {
  16263. return this._rotationQuaternion;
  16264. },
  16265. set: function (quaternion) {
  16266. this._rotationQuaternion = quaternion;
  16267. //reset the rotation vector.
  16268. if (quaternion && this.rotation.length()) {
  16269. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16270. }
  16271. },
  16272. enumerable: true,
  16273. configurable: true
  16274. });
  16275. /**
  16276. * Returns the latest update of the World matrix
  16277. * Returns a Matrix.
  16278. */
  16279. TransformNode.prototype.getWorldMatrix = function () {
  16280. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16281. this.computeWorldMatrix();
  16282. }
  16283. return this._worldMatrix;
  16284. };
  16285. /**
  16286. * Returns the latest update of the World matrix determinant.
  16287. */
  16288. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16289. return this._worldMatrixDeterminant;
  16290. };
  16291. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16292. /**
  16293. * Returns directly the latest state of the mesh World matrix.
  16294. * A Matrix is returned.
  16295. */
  16296. get: function () {
  16297. return this._worldMatrix;
  16298. },
  16299. enumerable: true,
  16300. configurable: true
  16301. });
  16302. /**
  16303. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16304. * Returns the AbstractMesh.
  16305. */
  16306. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16307. this._poseMatrix.copyFrom(matrix);
  16308. return this;
  16309. };
  16310. /**
  16311. * Returns the mesh Pose matrix.
  16312. * Returned object : Matrix
  16313. */
  16314. TransformNode.prototype.getPoseMatrix = function () {
  16315. return this._poseMatrix;
  16316. };
  16317. TransformNode.prototype._isSynchronized = function () {
  16318. if (this._isDirty) {
  16319. return false;
  16320. }
  16321. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16322. return false;
  16323. if (this._cache.pivotMatrixUpdated) {
  16324. return false;
  16325. }
  16326. if (this.infiniteDistance) {
  16327. return false;
  16328. }
  16329. if (!this._cache.position.equals(this.position))
  16330. return false;
  16331. if (this.rotationQuaternion) {
  16332. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16333. return false;
  16334. }
  16335. if (!this._cache.rotation.equals(this.rotation))
  16336. return false;
  16337. if (!this._cache.scaling.equals(this.scaling))
  16338. return false;
  16339. return true;
  16340. };
  16341. TransformNode.prototype._initCache = function () {
  16342. _super.prototype._initCache.call(this);
  16343. this._cache.localMatrixUpdated = false;
  16344. this._cache.position = BABYLON.Vector3.Zero();
  16345. this._cache.scaling = BABYLON.Vector3.Zero();
  16346. this._cache.rotation = BABYLON.Vector3.Zero();
  16347. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16348. this._cache.billboardMode = -1;
  16349. };
  16350. TransformNode.prototype.markAsDirty = function (property) {
  16351. if (property === "rotation") {
  16352. this.rotationQuaternion = null;
  16353. }
  16354. this._currentRenderId = Number.MAX_VALUE;
  16355. this._isDirty = true;
  16356. return this;
  16357. };
  16358. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16359. /**
  16360. * Returns the current mesh absolute position.
  16361. * Retuns a Vector3.
  16362. */
  16363. get: function () {
  16364. return this._absolutePosition;
  16365. },
  16366. enumerable: true,
  16367. configurable: true
  16368. });
  16369. /**
  16370. * Sets a new matrix to apply before all other transformation
  16371. * @param matrix defines the transform matrix
  16372. * @returns the current TransformNode
  16373. */
  16374. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16375. return this.setPivotMatrix(matrix, false);
  16376. };
  16377. /**
  16378. * Sets a new pivot matrix to the current node
  16379. * @param matrix defines the new pivot matrix to use
  16380. * @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
  16381. * @returns the current TransformNode
  16382. */
  16383. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16384. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16385. this._pivotMatrix = matrix.clone();
  16386. this._cache.pivotMatrixUpdated = true;
  16387. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16388. if (this._postMultiplyPivotMatrix) {
  16389. if (!this._pivotMatrixInverse) {
  16390. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16391. }
  16392. else {
  16393. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16394. }
  16395. }
  16396. return this;
  16397. };
  16398. /**
  16399. * Returns the mesh pivot matrix.
  16400. * Default : Identity.
  16401. * A Matrix is returned.
  16402. */
  16403. TransformNode.prototype.getPivotMatrix = function () {
  16404. return this._pivotMatrix;
  16405. };
  16406. /**
  16407. * Prevents the World matrix to be computed any longer.
  16408. * Returns the AbstractMesh.
  16409. */
  16410. TransformNode.prototype.freezeWorldMatrix = function () {
  16411. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16412. this.computeWorldMatrix(true);
  16413. this._isWorldMatrixFrozen = true;
  16414. return this;
  16415. };
  16416. /**
  16417. * Allows back the World matrix computation.
  16418. * Returns the AbstractMesh.
  16419. */
  16420. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16421. this._isWorldMatrixFrozen = false;
  16422. this.computeWorldMatrix(true);
  16423. return this;
  16424. };
  16425. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16426. /**
  16427. * True if the World matrix has been frozen.
  16428. * Returns a boolean.
  16429. */
  16430. get: function () {
  16431. return this._isWorldMatrixFrozen;
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. /**
  16437. * Retuns the mesh absolute position in the World.
  16438. * Returns a Vector3.
  16439. */
  16440. TransformNode.prototype.getAbsolutePosition = function () {
  16441. this.computeWorldMatrix();
  16442. return this._absolutePosition;
  16443. };
  16444. /**
  16445. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16446. * Returns the AbstractMesh.
  16447. */
  16448. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16449. if (!absolutePosition) {
  16450. return this;
  16451. }
  16452. var absolutePositionX;
  16453. var absolutePositionY;
  16454. var absolutePositionZ;
  16455. if (absolutePosition.x === undefined) {
  16456. if (arguments.length < 3) {
  16457. return this;
  16458. }
  16459. absolutePositionX = arguments[0];
  16460. absolutePositionY = arguments[1];
  16461. absolutePositionZ = arguments[2];
  16462. }
  16463. else {
  16464. absolutePositionX = absolutePosition.x;
  16465. absolutePositionY = absolutePosition.y;
  16466. absolutePositionZ = absolutePosition.z;
  16467. }
  16468. if (this.parent) {
  16469. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16470. invertParentWorldMatrix.invert();
  16471. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16472. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16473. }
  16474. else {
  16475. this.position.x = absolutePositionX;
  16476. this.position.y = absolutePositionY;
  16477. this.position.z = absolutePositionZ;
  16478. }
  16479. return this;
  16480. };
  16481. /**
  16482. * Sets the mesh position in its local space.
  16483. * Returns the AbstractMesh.
  16484. */
  16485. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16486. this.computeWorldMatrix();
  16487. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16488. return this;
  16489. };
  16490. /**
  16491. * Returns the mesh position in the local space from the current World matrix values.
  16492. * Returns a new Vector3.
  16493. */
  16494. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16495. this.computeWorldMatrix();
  16496. var invLocalWorldMatrix = this._localWorld.clone();
  16497. invLocalWorldMatrix.invert();
  16498. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16499. };
  16500. /**
  16501. * Translates the mesh along the passed Vector3 in its local space.
  16502. * Returns the AbstractMesh.
  16503. */
  16504. TransformNode.prototype.locallyTranslate = function (vector3) {
  16505. this.computeWorldMatrix(true);
  16506. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16507. return this;
  16508. };
  16509. /**
  16510. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16511. * @param targetPoint the position (must be in same space as current mesh) to look at
  16512. * @param yawCor optional yaw (y-axis) correction in radians
  16513. * @param pitchCor optional pitch (x-axis) correction in radians
  16514. * @param rollCor optional roll (z-axis) correction in radians
  16515. * @param space the choosen space of the target
  16516. * @returns the TransformNode.
  16517. */
  16518. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16519. if (yawCor === void 0) { yawCor = 0; }
  16520. if (pitchCor === void 0) { pitchCor = 0; }
  16521. if (rollCor === void 0) { rollCor = 0; }
  16522. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16523. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16524. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16525. targetPoint.subtractToRef(pos, dv);
  16526. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16527. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16528. var pitch = Math.atan2(dv.y, len);
  16529. if (this.rotationQuaternion) {
  16530. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16531. }
  16532. else {
  16533. this.rotation.x = pitch + pitchCor;
  16534. this.rotation.y = yaw + yawCor;
  16535. this.rotation.z = rollCor;
  16536. }
  16537. return this;
  16538. };
  16539. /**
  16540. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16541. * This Vector3 is expressed in the World space.
  16542. */
  16543. TransformNode.prototype.getDirection = function (localAxis) {
  16544. var result = BABYLON.Vector3.Zero();
  16545. this.getDirectionToRef(localAxis, result);
  16546. return result;
  16547. };
  16548. /**
  16549. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16550. * localAxis is expressed in the mesh local space.
  16551. * result is computed in the Wordl space from the mesh World matrix.
  16552. * Returns the AbstractMesh.
  16553. */
  16554. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16555. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16556. return this;
  16557. };
  16558. /**
  16559. * Sets a new pivot point to the current node
  16560. * @param point defines the new pivot point to use
  16561. * @param space defines if the point is in world or local space (local by default)
  16562. * @returns the current TransformNode
  16563. */
  16564. TransformNode.prototype.setPivotPoint = function (point, space) {
  16565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16566. if (this.getScene().getRenderId() == 0) {
  16567. this.computeWorldMatrix(true);
  16568. }
  16569. var wm = this.getWorldMatrix();
  16570. if (space == BABYLON.Space.WORLD) {
  16571. var tmat = BABYLON.Tmp.Matrix[0];
  16572. wm.invertToRef(tmat);
  16573. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16574. }
  16575. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16576. };
  16577. /**
  16578. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16579. */
  16580. TransformNode.prototype.getPivotPoint = function () {
  16581. var point = BABYLON.Vector3.Zero();
  16582. this.getPivotPointToRef(point);
  16583. return point;
  16584. };
  16585. /**
  16586. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16587. * Returns the AbstractMesh.
  16588. */
  16589. TransformNode.prototype.getPivotPointToRef = function (result) {
  16590. result.x = -this._pivotMatrix.m[12];
  16591. result.y = -this._pivotMatrix.m[13];
  16592. result.z = -this._pivotMatrix.m[14];
  16593. return this;
  16594. };
  16595. /**
  16596. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16597. */
  16598. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16599. var point = BABYLON.Vector3.Zero();
  16600. this.getAbsolutePivotPointToRef(point);
  16601. return point;
  16602. };
  16603. /**
  16604. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16605. * Returns the AbstractMesh.
  16606. */
  16607. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16608. result.x = this._pivotMatrix.m[12];
  16609. result.y = this._pivotMatrix.m[13];
  16610. result.z = this._pivotMatrix.m[14];
  16611. this.getPivotPointToRef(result);
  16612. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16613. return this;
  16614. };
  16615. /**
  16616. * Defines the passed node as the parent of the current node.
  16617. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16618. * Returns the TransformNode.
  16619. */
  16620. TransformNode.prototype.setParent = function (node) {
  16621. if (node === null) {
  16622. var rotation = BABYLON.Tmp.Quaternion[0];
  16623. var position = BABYLON.Tmp.Vector3[0];
  16624. var scale = BABYLON.Tmp.Vector3[1];
  16625. if (this.parent && this.parent.computeWorldMatrix) {
  16626. this.parent.computeWorldMatrix(true);
  16627. }
  16628. this.computeWorldMatrix(true);
  16629. this.getWorldMatrix().decompose(scale, rotation, position);
  16630. if (this.rotationQuaternion) {
  16631. this.rotationQuaternion.copyFrom(rotation);
  16632. }
  16633. else {
  16634. rotation.toEulerAnglesToRef(this.rotation);
  16635. }
  16636. this.scaling.x = scale.x;
  16637. this.scaling.y = scale.y;
  16638. this.scaling.z = scale.z;
  16639. this.position.x = position.x;
  16640. this.position.y = position.y;
  16641. this.position.z = position.z;
  16642. }
  16643. else {
  16644. var rotation = BABYLON.Tmp.Quaternion[0];
  16645. var position = BABYLON.Tmp.Vector3[0];
  16646. var scale = BABYLON.Tmp.Vector3[1];
  16647. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16648. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16649. this.computeWorldMatrix(true);
  16650. node.computeWorldMatrix(true);
  16651. node.getWorldMatrix().invertToRef(invParentMatrix);
  16652. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16653. diffMatrix.decompose(scale, rotation, position);
  16654. if (this.rotationQuaternion) {
  16655. this.rotationQuaternion.copyFrom(rotation);
  16656. }
  16657. else {
  16658. rotation.toEulerAnglesToRef(this.rotation);
  16659. }
  16660. this.position.x = position.x;
  16661. this.position.y = position.y;
  16662. this.position.z = position.z;
  16663. this.scaling.x = scale.x;
  16664. this.scaling.y = scale.y;
  16665. this.scaling.z = scale.z;
  16666. }
  16667. this.parent = node;
  16668. return this;
  16669. };
  16670. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16671. get: function () {
  16672. return this._nonUniformScaling;
  16673. },
  16674. enumerable: true,
  16675. configurable: true
  16676. });
  16677. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16678. if (this._nonUniformScaling === value) {
  16679. return false;
  16680. }
  16681. this._nonUniformScaling = true;
  16682. return true;
  16683. };
  16684. /**
  16685. * Attach the current TransformNode to another TransformNode associated with a bone
  16686. * @param bone Bone affecting the TransformNode
  16687. * @param affectedTransformNode TransformNode associated with the bone
  16688. */
  16689. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16690. this._transformToBoneReferal = affectedTransformNode;
  16691. this.parent = bone;
  16692. if (bone.getWorldMatrix().determinant() < 0) {
  16693. this.scalingDeterminant *= -1;
  16694. }
  16695. return this;
  16696. };
  16697. TransformNode.prototype.detachFromBone = function () {
  16698. if (!this.parent) {
  16699. return this;
  16700. }
  16701. if (this.parent.getWorldMatrix().determinant() < 0) {
  16702. this.scalingDeterminant *= -1;
  16703. }
  16704. this._transformToBoneReferal = null;
  16705. this.parent = null;
  16706. return this;
  16707. };
  16708. /**
  16709. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16710. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16711. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16712. * The passed axis is also normalized.
  16713. * Returns the AbstractMesh.
  16714. */
  16715. TransformNode.prototype.rotate = function (axis, amount, space) {
  16716. axis.normalize();
  16717. if (!this.rotationQuaternion) {
  16718. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16719. this.rotation = BABYLON.Vector3.Zero();
  16720. }
  16721. var rotationQuaternion;
  16722. if (!space || space === BABYLON.Space.LOCAL) {
  16723. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16724. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16725. }
  16726. else {
  16727. if (this.parent) {
  16728. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16729. invertParentWorldMatrix.invert();
  16730. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16731. }
  16732. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16733. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16734. }
  16735. return this;
  16736. };
  16737. /**
  16738. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16739. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16740. * The passed axis is also normalized.
  16741. * Returns the AbstractMesh.
  16742. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16743. */
  16744. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16745. axis.normalize();
  16746. if (!this.rotationQuaternion) {
  16747. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16748. this.rotation.copyFromFloats(0, 0, 0);
  16749. }
  16750. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16751. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16752. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16753. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16754. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16755. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16756. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16757. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16758. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16759. return this;
  16760. };
  16761. /**
  16762. * Translates the mesh along the axis vector for the passed distance in the given space.
  16763. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16764. * Returns the AbstractMesh.
  16765. */
  16766. TransformNode.prototype.translate = function (axis, distance, space) {
  16767. var displacementVector = axis.scale(distance);
  16768. if (!space || space === BABYLON.Space.LOCAL) {
  16769. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16770. this.setPositionWithLocalVector(tempV3);
  16771. }
  16772. else {
  16773. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16774. }
  16775. return this;
  16776. };
  16777. /**
  16778. * Adds a rotation step to the mesh current rotation.
  16779. * x, y, z are Euler angles expressed in radians.
  16780. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16781. * This means this rotation is made in the mesh local space only.
  16782. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16783. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16784. * ```javascript
  16785. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16786. * ```
  16787. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16788. * 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.
  16789. * Returns the AbstractMesh.
  16790. */
  16791. TransformNode.prototype.addRotation = function (x, y, z) {
  16792. var rotationQuaternion;
  16793. if (this.rotationQuaternion) {
  16794. rotationQuaternion = this.rotationQuaternion;
  16795. }
  16796. else {
  16797. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16798. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16799. }
  16800. var accumulation = BABYLON.Tmp.Quaternion[0];
  16801. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16802. rotationQuaternion.multiplyInPlace(accumulation);
  16803. if (!this.rotationQuaternion) {
  16804. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16805. }
  16806. return this;
  16807. };
  16808. /**
  16809. * Computes the mesh World matrix and returns it.
  16810. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16811. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16812. * If the parameter `force`is set to `true`, the actual computation is done.
  16813. * Returns the mesh World Matrix.
  16814. */
  16815. TransformNode.prototype.computeWorldMatrix = function (force) {
  16816. if (this._isWorldMatrixFrozen) {
  16817. return this._worldMatrix;
  16818. }
  16819. if (!force && this.isSynchronized(true)) {
  16820. return this._worldMatrix;
  16821. }
  16822. this._cache.position.copyFrom(this.position);
  16823. this._cache.scaling.copyFrom(this.scaling);
  16824. this._cache.pivotMatrixUpdated = false;
  16825. this._cache.billboardMode = this.billboardMode;
  16826. this._currentRenderId = this.getScene().getRenderId();
  16827. this._isDirty = false;
  16828. // Scaling
  16829. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16830. // Rotation
  16831. //rotate, if quaternion is set and rotation was used
  16832. if (this.rotationQuaternion) {
  16833. var len = this.rotation.length();
  16834. if (len) {
  16835. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16836. this.rotation.copyFromFloats(0, 0, 0);
  16837. }
  16838. }
  16839. if (this.rotationQuaternion) {
  16840. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16841. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16842. }
  16843. else {
  16844. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16845. this._cache.rotation.copyFrom(this.rotation);
  16846. }
  16847. // Translation
  16848. var camera = this.getScene().activeCamera;
  16849. if (this.infiniteDistance && !this.parent && camera) {
  16850. var cameraWorldMatrix = camera.getWorldMatrix();
  16851. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16852. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16853. }
  16854. else {
  16855. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16856. }
  16857. // Composing transformations
  16858. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16859. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16860. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16861. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16862. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16863. // Need to decompose each rotation here
  16864. var currentPosition = BABYLON.Tmp.Vector3[3];
  16865. if (this.parent && this.parent.getWorldMatrix) {
  16866. if (this._transformToBoneReferal) {
  16867. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16868. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16869. }
  16870. else {
  16871. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16872. }
  16873. }
  16874. else {
  16875. currentPosition.copyFrom(this.position);
  16876. }
  16877. currentPosition.subtractInPlace(camera.globalPosition);
  16878. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16879. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16880. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16881. }
  16882. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16883. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16884. }
  16885. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16886. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16887. }
  16888. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16889. }
  16890. else {
  16891. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16892. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16893. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16894. }
  16895. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16896. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16897. }
  16898. // Local world
  16899. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16900. // Parent
  16901. if (this.parent && this.parent.getWorldMatrix) {
  16902. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16903. if (this._transformToBoneReferal) {
  16904. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16905. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16906. }
  16907. else {
  16908. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16909. }
  16910. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16911. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16912. this._worldMatrix.copyFrom(this._localWorld);
  16913. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16914. }
  16915. else {
  16916. if (this._transformToBoneReferal) {
  16917. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16918. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16919. }
  16920. else {
  16921. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16922. }
  16923. }
  16924. this._markSyncedWithParent();
  16925. }
  16926. else {
  16927. this._worldMatrix.copyFrom(this._localWorld);
  16928. }
  16929. // Post multiply inverse of pivotMatrix
  16930. if (this._postMultiplyPivotMatrix) {
  16931. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16932. }
  16933. // Normal matrix
  16934. if (this.scaling.isNonUniform) {
  16935. this._updateNonUniformScalingState(true);
  16936. }
  16937. else if (this.parent && this.parent._nonUniformScaling) {
  16938. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16939. }
  16940. else {
  16941. this._updateNonUniformScalingState(false);
  16942. }
  16943. this._afterComputeWorldMatrix();
  16944. // Absolute position
  16945. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16946. // Callbacks
  16947. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16948. if (!this._poseMatrix) {
  16949. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16950. }
  16951. // Cache the determinant
  16952. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16953. return this._worldMatrix;
  16954. };
  16955. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16956. };
  16957. /**
  16958. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16959. * @param func: callback function to add
  16960. *
  16961. * Returns the TransformNode.
  16962. */
  16963. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16964. this.onAfterWorldMatrixUpdateObservable.add(func);
  16965. return this;
  16966. };
  16967. /**
  16968. * Removes a registered callback function.
  16969. * Returns the TransformNode.
  16970. */
  16971. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16972. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16973. return this;
  16974. };
  16975. /**
  16976. * Clone the current transform node
  16977. * Returns the new transform node
  16978. * @param name Name of the new clone
  16979. * @param newParent New parent for the clone
  16980. * @param doNotCloneChildren Do not clone children hierarchy
  16981. */
  16982. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16983. var _this = this;
  16984. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16985. result.name = name;
  16986. result.id = name;
  16987. if (newParent) {
  16988. result.parent = newParent;
  16989. }
  16990. if (!doNotCloneChildren) {
  16991. // Children
  16992. var directDescendants = this.getDescendants(true);
  16993. for (var index = 0; index < directDescendants.length; index++) {
  16994. var child = directDescendants[index];
  16995. if (child.clone) {
  16996. child.clone(name + "." + child.name, result);
  16997. }
  16998. }
  16999. }
  17000. return result;
  17001. };
  17002. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17003. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17004. serializationObject.type = this.getClassName();
  17005. // Parent
  17006. if (this.parent) {
  17007. serializationObject.parentId = this.parent.id;
  17008. }
  17009. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17010. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17011. }
  17012. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17013. serializationObject.isEnabled = this.isEnabled();
  17014. // Parent
  17015. if (this.parent) {
  17016. serializationObject.parentId = this.parent.id;
  17017. }
  17018. return serializationObject;
  17019. };
  17020. // Statics
  17021. /**
  17022. * Returns a new TransformNode object parsed from the source provided.
  17023. * The parameter `parsedMesh` is the source.
  17024. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17025. */
  17026. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17027. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17028. if (BABYLON.Tags) {
  17029. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17030. }
  17031. if (parsedTransformNode.localMatrix) {
  17032. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17033. }
  17034. else if (parsedTransformNode.pivotMatrix) {
  17035. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17036. }
  17037. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17038. // Parent
  17039. if (parsedTransformNode.parentId) {
  17040. transformNode._waitingParentId = parsedTransformNode.parentId;
  17041. }
  17042. return transformNode;
  17043. };
  17044. /**
  17045. * Disposes the TransformNode.
  17046. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17047. * Returns nothing.
  17048. */
  17049. TransformNode.prototype.dispose = function (doNotRecurse) {
  17050. // Animations
  17051. this.getScene().stopAnimation(this);
  17052. // Remove from scene
  17053. this.getScene().removeTransformNode(this);
  17054. if (!doNotRecurse) {
  17055. // Children
  17056. var objects = this.getDescendants(true);
  17057. for (var index = 0; index < objects.length; index++) {
  17058. objects[index].dispose();
  17059. }
  17060. }
  17061. else {
  17062. var childMeshes = this.getChildMeshes(true);
  17063. for (index = 0; index < childMeshes.length; index++) {
  17064. var child = childMeshes[index];
  17065. child.parent = null;
  17066. child.computeWorldMatrix(true);
  17067. }
  17068. }
  17069. this.onAfterWorldMatrixUpdateObservable.clear();
  17070. _super.prototype.dispose.call(this);
  17071. };
  17072. // Statics
  17073. TransformNode.BILLBOARDMODE_NONE = 0;
  17074. TransformNode.BILLBOARDMODE_X = 1;
  17075. TransformNode.BILLBOARDMODE_Y = 2;
  17076. TransformNode.BILLBOARDMODE_Z = 4;
  17077. TransformNode.BILLBOARDMODE_ALL = 7;
  17078. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17079. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17080. __decorate([
  17081. BABYLON.serializeAsVector3()
  17082. ], TransformNode.prototype, "_rotation", void 0);
  17083. __decorate([
  17084. BABYLON.serializeAsQuaternion()
  17085. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17086. __decorate([
  17087. BABYLON.serializeAsVector3()
  17088. ], TransformNode.prototype, "_scaling", void 0);
  17089. __decorate([
  17090. BABYLON.serialize()
  17091. ], TransformNode.prototype, "billboardMode", void 0);
  17092. __decorate([
  17093. BABYLON.serialize()
  17094. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17095. __decorate([
  17096. BABYLON.serialize()
  17097. ], TransformNode.prototype, "infiniteDistance", void 0);
  17098. __decorate([
  17099. BABYLON.serializeAsVector3()
  17100. ], TransformNode.prototype, "position", void 0);
  17101. return TransformNode;
  17102. }(BABYLON.Node));
  17103. BABYLON.TransformNode = TransformNode;
  17104. })(BABYLON || (BABYLON = {}));
  17105. //# sourceMappingURL=babylon.transformNode.js.map
  17106. var BABYLON;
  17107. (function (BABYLON) {
  17108. var AbstractMesh = /** @class */ (function (_super) {
  17109. __extends(AbstractMesh, _super);
  17110. // Constructor
  17111. function AbstractMesh(name, scene) {
  17112. if (scene === void 0) { scene = null; }
  17113. var _this = _super.call(this, name, scene, false) || this;
  17114. _this._facetNb = 0; // facet number
  17115. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17116. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17117. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17118. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17119. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17120. _this._subDiv = {
  17121. max: 1,
  17122. X: 1,
  17123. Y: 1,
  17124. Z: 1
  17125. };
  17126. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17127. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17128. // Events
  17129. /**
  17130. * An event triggered when this mesh collides with another one
  17131. * @type {BABYLON.Observable}
  17132. */
  17133. _this.onCollideObservable = new BABYLON.Observable();
  17134. /**
  17135. * An event triggered when the collision's position changes
  17136. * @type {BABYLON.Observable}
  17137. */
  17138. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17139. /**
  17140. * An event triggered when material is changed
  17141. * @type {BABYLON.Observable}
  17142. */
  17143. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17144. // Properties
  17145. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17146. /**
  17147. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17148. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17149. * or
  17150. * 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.
  17151. * for more info check WebGl documentations
  17152. */
  17153. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17154. /**
  17155. * 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:
  17156. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17157. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17158. * 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.
  17159. */
  17160. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17161. /**
  17162. * 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.
  17163. * The default value is -1 which means don't break the query and wait till the result.
  17164. */
  17165. _this.occlusionRetryCount = -1;
  17166. _this._occlusionInternalRetryCounter = 0;
  17167. _this._isOccluded = false;
  17168. _this._isOcclusionQueryInProgress = false;
  17169. _this._visibility = 1.0;
  17170. _this.alphaIndex = Number.MAX_VALUE;
  17171. _this.isVisible = true;
  17172. _this.isPickable = true;
  17173. _this.showBoundingBox = false;
  17174. _this.showSubMeshesBoundingBox = false;
  17175. _this.isBlocker = false;
  17176. _this.enablePointerMoveEvents = false;
  17177. _this.renderingGroupId = 0;
  17178. _this._receiveShadows = false;
  17179. _this.renderOutline = false;
  17180. _this.outlineColor = BABYLON.Color3.Red();
  17181. _this.outlineWidth = 0.02;
  17182. _this.renderOverlay = false;
  17183. _this.overlayColor = BABYLON.Color3.Red();
  17184. _this.overlayAlpha = 0.5;
  17185. _this._hasVertexAlpha = false;
  17186. _this._useVertexColors = true;
  17187. _this._computeBonesUsingShaders = true;
  17188. _this._numBoneInfluencers = 4;
  17189. _this._applyFog = true;
  17190. _this.useOctreeForRenderingSelection = true;
  17191. _this.useOctreeForPicking = true;
  17192. _this.useOctreeForCollisions = true;
  17193. _this._layerMask = 0x0FFFFFFF;
  17194. /**
  17195. * True if the mesh must be rendered in any case.
  17196. */
  17197. _this.alwaysSelectAsActiveMesh = false;
  17198. /**
  17199. * This scene's action manager
  17200. * @type {BABYLON.ActionManager}
  17201. */
  17202. _this.actionManager = null;
  17203. // Physics
  17204. _this.physicsImpostor = null;
  17205. // Collisions
  17206. _this._checkCollisions = false;
  17207. _this._collisionMask = -1;
  17208. _this._collisionGroup = -1;
  17209. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17210. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17211. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17212. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17213. // Edges
  17214. _this.edgesWidth = 1;
  17215. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17216. // Cache
  17217. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17218. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17219. _this._renderId = 0;
  17220. _this._intersectionsInProgress = new Array();
  17221. _this._unIndexed = false;
  17222. _this._lightSources = new Array();
  17223. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17224. if (collidedMesh === void 0) { collidedMesh = null; }
  17225. //TODO move this to the collision coordinator!
  17226. if (_this.getScene().workerCollisions)
  17227. newPosition.multiplyInPlace(_this._collider._radius);
  17228. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17229. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17230. _this.position.addInPlace(_this._diffPositionForCollisions);
  17231. }
  17232. if (collidedMesh) {
  17233. _this.onCollideObservable.notifyObservers(collidedMesh);
  17234. }
  17235. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17236. };
  17237. _this.getScene().addMesh(_this);
  17238. _this._resyncLightSources();
  17239. return _this;
  17240. }
  17241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17242. get: function () {
  17243. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17249. get: function () {
  17250. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17256. get: function () {
  17257. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17263. get: function () {
  17264. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17270. get: function () {
  17271. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17277. /**
  17278. * Read-only : the number of facets in the mesh
  17279. */
  17280. get: function () {
  17281. return this._facetNb;
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17287. /**
  17288. * The number (integer) of subdivisions per axis in the partioning space
  17289. */
  17290. get: function () {
  17291. return this._partitioningSubdivisions;
  17292. },
  17293. set: function (nb) {
  17294. this._partitioningSubdivisions = nb;
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17300. /**
  17301. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17302. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17303. */
  17304. get: function () {
  17305. return this._partitioningBBoxRatio;
  17306. },
  17307. set: function (ratio) {
  17308. this._partitioningBBoxRatio = ratio;
  17309. },
  17310. enumerable: true,
  17311. configurable: true
  17312. });
  17313. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17314. /**
  17315. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17316. * Works only for updatable meshes.
  17317. * Doesn't work with multi-materials.
  17318. */
  17319. get: function () {
  17320. return this._facetDepthSort;
  17321. },
  17322. set: function (sort) {
  17323. this._facetDepthSort = sort;
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17329. /**
  17330. * The location (Vector3) where the facet depth sort must be computed from.
  17331. * By default, the active camera position.
  17332. * Used only when facet depth sort is enabled.
  17333. */
  17334. get: function () {
  17335. return this._facetDepthSortFrom;
  17336. },
  17337. set: function (location) {
  17338. this._facetDepthSortFrom = location;
  17339. },
  17340. enumerable: true,
  17341. configurable: true
  17342. });
  17343. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17344. /**
  17345. * Read-only boolean : is the feature facetData enabled ?
  17346. */
  17347. get: function () {
  17348. return this._facetDataEnabled;
  17349. },
  17350. enumerable: true,
  17351. configurable: true
  17352. });
  17353. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17354. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17355. return false;
  17356. }
  17357. this._markSubMeshesAsMiscDirty();
  17358. return true;
  17359. };
  17360. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17361. set: function (callback) {
  17362. if (this._onCollideObserver) {
  17363. this.onCollideObservable.remove(this._onCollideObserver);
  17364. }
  17365. this._onCollideObserver = this.onCollideObservable.add(callback);
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17371. set: function (callback) {
  17372. if (this._onCollisionPositionChangeObserver) {
  17373. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17374. }
  17375. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17376. },
  17377. enumerable: true,
  17378. configurable: true
  17379. });
  17380. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17381. /**
  17382. * 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.
  17383. */
  17384. get: function () {
  17385. return this._isOccluded;
  17386. },
  17387. set: function (value) {
  17388. this._isOccluded = value;
  17389. },
  17390. enumerable: true,
  17391. configurable: true
  17392. });
  17393. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17394. /**
  17395. * Flag to check the progress status of the query
  17396. */
  17397. get: function () {
  17398. return this._isOcclusionQueryInProgress;
  17399. },
  17400. enumerable: true,
  17401. configurable: true
  17402. });
  17403. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17404. /**
  17405. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17406. */
  17407. get: function () {
  17408. return this._visibility;
  17409. },
  17410. /**
  17411. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17412. */
  17413. set: function (value) {
  17414. if (this._visibility === value) {
  17415. return;
  17416. }
  17417. this._visibility = value;
  17418. this._markSubMeshesAsMiscDirty();
  17419. },
  17420. enumerable: true,
  17421. configurable: true
  17422. });
  17423. Object.defineProperty(AbstractMesh.prototype, "material", {
  17424. get: function () {
  17425. return this._material;
  17426. },
  17427. set: function (value) {
  17428. if (this._material === value) {
  17429. return;
  17430. }
  17431. this._material = value;
  17432. if (this.onMaterialChangedObservable.hasObservers) {
  17433. this.onMaterialChangedObservable.notifyObservers(this);
  17434. }
  17435. if (!this.subMeshes) {
  17436. return;
  17437. }
  17438. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17439. var subMesh = _a[_i];
  17440. subMesh.setEffect(null);
  17441. }
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17447. get: function () {
  17448. return this._receiveShadows;
  17449. },
  17450. set: function (value) {
  17451. if (this._receiveShadows === value) {
  17452. return;
  17453. }
  17454. this._receiveShadows = value;
  17455. this._markSubMeshesAsLightDirty();
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17461. get: function () {
  17462. return this._hasVertexAlpha;
  17463. },
  17464. set: function (value) {
  17465. if (this._hasVertexAlpha === value) {
  17466. return;
  17467. }
  17468. this._hasVertexAlpha = value;
  17469. this._markSubMeshesAsAttributesDirty();
  17470. this._markSubMeshesAsMiscDirty();
  17471. },
  17472. enumerable: true,
  17473. configurable: true
  17474. });
  17475. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17476. get: function () {
  17477. return this._useVertexColors;
  17478. },
  17479. set: function (value) {
  17480. if (this._useVertexColors === value) {
  17481. return;
  17482. }
  17483. this._useVertexColors = value;
  17484. this._markSubMeshesAsAttributesDirty();
  17485. },
  17486. enumerable: true,
  17487. configurable: true
  17488. });
  17489. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17490. get: function () {
  17491. return this._computeBonesUsingShaders;
  17492. },
  17493. set: function (value) {
  17494. if (this._computeBonesUsingShaders === value) {
  17495. return;
  17496. }
  17497. this._computeBonesUsingShaders = value;
  17498. this._markSubMeshesAsAttributesDirty();
  17499. },
  17500. enumerable: true,
  17501. configurable: true
  17502. });
  17503. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17504. get: function () {
  17505. return this._numBoneInfluencers;
  17506. },
  17507. set: function (value) {
  17508. if (this._numBoneInfluencers === value) {
  17509. return;
  17510. }
  17511. this._numBoneInfluencers = value;
  17512. this._markSubMeshesAsAttributesDirty();
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17518. get: function () {
  17519. return this._applyFog;
  17520. },
  17521. set: function (value) {
  17522. if (this._applyFog === value) {
  17523. return;
  17524. }
  17525. this._applyFog = value;
  17526. this._markSubMeshesAsMiscDirty();
  17527. },
  17528. enumerable: true,
  17529. configurable: true
  17530. });
  17531. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17532. get: function () {
  17533. return this._layerMask;
  17534. },
  17535. set: function (value) {
  17536. if (value === this._layerMask) {
  17537. return;
  17538. }
  17539. this._layerMask = value;
  17540. this._resyncLightSources();
  17541. },
  17542. enumerable: true,
  17543. configurable: true
  17544. });
  17545. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17546. get: function () {
  17547. return this._collisionMask;
  17548. },
  17549. set: function (mask) {
  17550. this._collisionMask = !isNaN(mask) ? mask : -1;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17556. get: function () {
  17557. return this._collisionGroup;
  17558. },
  17559. set: function (mask) {
  17560. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17566. get: function () {
  17567. return null;
  17568. },
  17569. enumerable: true,
  17570. configurable: true
  17571. });
  17572. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17573. get: function () {
  17574. return this._skeleton;
  17575. },
  17576. set: function (value) {
  17577. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17578. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17579. }
  17580. if (value && value.needInitialSkinMatrix) {
  17581. value._registerMeshWithPoseMatrix(this);
  17582. }
  17583. this._skeleton = value;
  17584. if (!this._skeleton) {
  17585. this._bonesTransformMatrices = null;
  17586. }
  17587. this._markSubMeshesAsAttributesDirty();
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. /**
  17593. * Returns the string "AbstractMesh"
  17594. */
  17595. AbstractMesh.prototype.getClassName = function () {
  17596. return "AbstractMesh";
  17597. };
  17598. /**
  17599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17600. */
  17601. AbstractMesh.prototype.toString = function (fullDetails) {
  17602. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17603. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17604. if (this._skeleton) {
  17605. ret += ", skeleton: " + this._skeleton.name;
  17606. }
  17607. if (fullDetails) {
  17608. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17609. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17610. }
  17611. return ret;
  17612. };
  17613. AbstractMesh.prototype._rebuild = function () {
  17614. if (this._occlusionQuery) {
  17615. this._occlusionQuery = null;
  17616. }
  17617. if (this._edgesRenderer) {
  17618. this._edgesRenderer._rebuild();
  17619. }
  17620. if (!this.subMeshes) {
  17621. return;
  17622. }
  17623. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17624. var subMesh = _a[_i];
  17625. subMesh._rebuild();
  17626. }
  17627. };
  17628. AbstractMesh.prototype._resyncLightSources = function () {
  17629. this._lightSources.length = 0;
  17630. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17631. var light = _a[_i];
  17632. if (!light.isEnabled()) {
  17633. continue;
  17634. }
  17635. if (light.canAffectMesh(this)) {
  17636. this._lightSources.push(light);
  17637. }
  17638. }
  17639. this._markSubMeshesAsLightDirty();
  17640. };
  17641. AbstractMesh.prototype._resyncLighSource = function (light) {
  17642. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17643. var index = this._lightSources.indexOf(light);
  17644. if (index === -1) {
  17645. if (!isIn) {
  17646. return;
  17647. }
  17648. this._lightSources.push(light);
  17649. }
  17650. else {
  17651. if (isIn) {
  17652. return;
  17653. }
  17654. this._lightSources.splice(index, 1);
  17655. }
  17656. this._markSubMeshesAsLightDirty();
  17657. };
  17658. AbstractMesh.prototype._removeLightSource = function (light) {
  17659. var index = this._lightSources.indexOf(light);
  17660. if (index === -1) {
  17661. return;
  17662. }
  17663. this._lightSources.splice(index, 1);
  17664. this._markSubMeshesAsLightDirty();
  17665. };
  17666. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17667. if (!this.subMeshes) {
  17668. return;
  17669. }
  17670. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17671. var subMesh = _a[_i];
  17672. if (subMesh._materialDefines) {
  17673. func(subMesh._materialDefines);
  17674. }
  17675. }
  17676. };
  17677. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17678. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17679. };
  17680. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17681. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17682. };
  17683. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17684. if (!this.subMeshes) {
  17685. return;
  17686. }
  17687. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17688. var subMesh = _a[_i];
  17689. var material = subMesh.getMaterial();
  17690. if (material) {
  17691. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17692. }
  17693. }
  17694. };
  17695. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17696. /**
  17697. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17698. * Default : (1.0, 1.0, 1.0)
  17699. */
  17700. get: function () {
  17701. return this._scaling;
  17702. },
  17703. /**
  17704. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17705. * Default : (1.0, 1.0, 1.0)
  17706. */
  17707. set: function (newScaling) {
  17708. this._scaling = newScaling;
  17709. if (this.physicsImpostor) {
  17710. this.physicsImpostor.forceUpdate();
  17711. }
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. // Methods
  17717. /**
  17718. * Disables the mesh edger rendering mode.
  17719. * Returns the AbstractMesh.
  17720. */
  17721. AbstractMesh.prototype.disableEdgesRendering = function () {
  17722. if (this._edgesRenderer) {
  17723. this._edgesRenderer.dispose();
  17724. this._edgesRenderer = null;
  17725. }
  17726. return this;
  17727. };
  17728. /**
  17729. * Enables the edge rendering mode on the mesh.
  17730. * This mode makes the mesh edges visible.
  17731. * Returns the AbstractMesh.
  17732. */
  17733. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17734. if (epsilon === void 0) { epsilon = 0.95; }
  17735. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17736. this.disableEdgesRendering();
  17737. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17738. return this;
  17739. };
  17740. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17741. /**
  17742. * Returns true if the mesh is blocked. Used by the class Mesh.
  17743. * Returns the boolean `false` by default.
  17744. */
  17745. get: function () {
  17746. return false;
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. /**
  17752. * Returns the mesh itself by default, used by the class Mesh.
  17753. * Returned type : AbstractMesh
  17754. */
  17755. AbstractMesh.prototype.getLOD = function (camera) {
  17756. return this;
  17757. };
  17758. /**
  17759. * Returns 0 by default, used by the class Mesh.
  17760. * Returns an integer.
  17761. */
  17762. AbstractMesh.prototype.getTotalVertices = function () {
  17763. return 0;
  17764. };
  17765. /**
  17766. * Returns null by default, used by the class Mesh.
  17767. * Returned type : integer array
  17768. */
  17769. AbstractMesh.prototype.getIndices = function () {
  17770. return null;
  17771. };
  17772. /**
  17773. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17774. * Returned type : float array or Float32Array
  17775. */
  17776. AbstractMesh.prototype.getVerticesData = function (kind) {
  17777. return null;
  17778. };
  17779. /**
  17780. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17781. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17782. * The `data` are either a numeric array either a Float32Array.
  17783. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17784. * 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).
  17785. * Note that a new underlying VertexBuffer object is created each call.
  17786. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17787. *
  17788. * Possible `kind` values :
  17789. * - BABYLON.VertexBuffer.PositionKind
  17790. * - BABYLON.VertexBuffer.UVKind
  17791. * - BABYLON.VertexBuffer.UV2Kind
  17792. * - BABYLON.VertexBuffer.UV3Kind
  17793. * - BABYLON.VertexBuffer.UV4Kind
  17794. * - BABYLON.VertexBuffer.UV5Kind
  17795. * - BABYLON.VertexBuffer.UV6Kind
  17796. * - BABYLON.VertexBuffer.ColorKind
  17797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17801. *
  17802. * Returns the Mesh.
  17803. */
  17804. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17805. return this;
  17806. };
  17807. /**
  17808. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17809. * If the mesh has no geometry, it is simply returned as it is.
  17810. * The `data` are either a numeric array either a Float32Array.
  17811. * No new underlying VertexBuffer object is created.
  17812. * 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.
  17813. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17814. *
  17815. * Possible `kind` values :
  17816. * - BABYLON.VertexBuffer.PositionKind
  17817. * - BABYLON.VertexBuffer.UVKind
  17818. * - BABYLON.VertexBuffer.UV2Kind
  17819. * - BABYLON.VertexBuffer.UV3Kind
  17820. * - BABYLON.VertexBuffer.UV4Kind
  17821. * - BABYLON.VertexBuffer.UV5Kind
  17822. * - BABYLON.VertexBuffer.UV6Kind
  17823. * - BABYLON.VertexBuffer.ColorKind
  17824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17828. *
  17829. * Returns the Mesh.
  17830. */
  17831. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17832. return this;
  17833. };
  17834. /**
  17835. * Sets the mesh indices.
  17836. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17837. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17838. * This method creates a new index buffer each call.
  17839. * Returns the Mesh.
  17840. */
  17841. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17842. return this;
  17843. };
  17844. /** Returns false by default, used by the class Mesh.
  17845. * Returns a boolean
  17846. */
  17847. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17848. return false;
  17849. };
  17850. /**
  17851. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17852. * Returns a BoundingInfo
  17853. */
  17854. AbstractMesh.prototype.getBoundingInfo = function () {
  17855. if (this._masterMesh) {
  17856. return this._masterMesh.getBoundingInfo();
  17857. }
  17858. if (!this._boundingInfo) {
  17859. // this._boundingInfo is being created here
  17860. this._updateBoundingInfo();
  17861. }
  17862. // cannot be null.
  17863. return this._boundingInfo;
  17864. };
  17865. /**
  17866. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17867. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17868. */
  17869. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17870. if (includeDescendants === void 0) { includeDescendants = true; }
  17871. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17872. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17873. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17874. if (maxDimension === 0) {
  17875. return this;
  17876. }
  17877. var scale = 1 / maxDimension;
  17878. this.scaling.scaleInPlace(scale);
  17879. return this;
  17880. };
  17881. /**
  17882. * Sets a mesh new object BoundingInfo.
  17883. * Returns the AbstractMesh.
  17884. */
  17885. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17886. this._boundingInfo = boundingInfo;
  17887. return this;
  17888. };
  17889. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17890. get: function () {
  17891. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. AbstractMesh.prototype._preActivate = function () {
  17897. };
  17898. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17899. };
  17900. AbstractMesh.prototype._activate = function (renderId) {
  17901. this._renderId = renderId;
  17902. };
  17903. /**
  17904. * Returns the latest update of the World matrix
  17905. * Returns a Matrix.
  17906. */
  17907. AbstractMesh.prototype.getWorldMatrix = function () {
  17908. if (this._masterMesh) {
  17909. return this._masterMesh.getWorldMatrix();
  17910. }
  17911. return _super.prototype.getWorldMatrix.call(this);
  17912. };
  17913. /**
  17914. * Returns the latest update of the World matrix determinant.
  17915. */
  17916. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17917. if (this._masterMesh) {
  17918. return this._masterMesh._getWorldMatrixDeterminant();
  17919. }
  17920. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17921. };
  17922. // ================================== Point of View Movement =================================
  17923. /**
  17924. * Perform relative position change from the point of view of behind the front of the mesh.
  17925. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17926. * Supports definition of mesh facing forward or backward.
  17927. * @param {number} amountRight
  17928. * @param {number} amountUp
  17929. * @param {number} amountForward
  17930. *
  17931. * Returns the AbstractMesh.
  17932. */
  17933. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17934. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17935. return this;
  17936. };
  17937. /**
  17938. * Calculate relative position change from the point of view of behind the front of the mesh.
  17939. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17940. * Supports definition of mesh facing forward or backward.
  17941. * @param {number} amountRight
  17942. * @param {number} amountUp
  17943. * @param {number} amountForward
  17944. *
  17945. * Returns a new Vector3.
  17946. */
  17947. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17948. var rotMatrix = new BABYLON.Matrix();
  17949. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17950. rotQuaternion.toRotationMatrix(rotMatrix);
  17951. var translationDelta = BABYLON.Vector3.Zero();
  17952. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17954. return translationDelta;
  17955. };
  17956. // ================================== Point of View Rotation =================================
  17957. /**
  17958. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17959. * Supports definition of mesh facing forward or backward.
  17960. * @param {number} flipBack
  17961. * @param {number} twirlClockwise
  17962. * @param {number} tiltRight
  17963. *
  17964. * Returns the AbstractMesh.
  17965. */
  17966. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17967. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17968. return this;
  17969. };
  17970. /**
  17971. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17972. * Supports definition of mesh facing forward or backward.
  17973. * @param {number} flipBack
  17974. * @param {number} twirlClockwise
  17975. * @param {number} tiltRight
  17976. *
  17977. * Returns a new Vector3.
  17978. */
  17979. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17980. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17981. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17982. };
  17983. /**
  17984. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17985. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17986. */
  17987. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17988. if (includeDescendants === void 0) { includeDescendants = true; }
  17989. this.computeWorldMatrix(true);
  17990. var min;
  17991. var max;
  17992. var boundingInfo = this.getBoundingInfo();
  17993. if (!this.subMeshes) {
  17994. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17995. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17996. }
  17997. else {
  17998. min = boundingInfo.boundingBox.minimumWorld;
  17999. max = boundingInfo.boundingBox.maximumWorld;
  18000. }
  18001. if (includeDescendants) {
  18002. var descendants = this.getDescendants(false);
  18003. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18004. var descendant = descendants_1[_i];
  18005. var childMesh = descendant;
  18006. childMesh.computeWorldMatrix(true);
  18007. //make sure we have the needed params to get mix and max
  18008. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18009. continue;
  18010. }
  18011. var childBoundingInfo = childMesh.getBoundingInfo();
  18012. var boundingBox = childBoundingInfo.boundingBox;
  18013. var minBox = boundingBox.minimumWorld;
  18014. var maxBox = boundingBox.maximumWorld;
  18015. BABYLON.Tools.CheckExtends(minBox, min, max);
  18016. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18017. }
  18018. }
  18019. return {
  18020. min: min,
  18021. max: max
  18022. };
  18023. };
  18024. /**
  18025. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18026. * Returns the AbstractMesh.
  18027. */
  18028. AbstractMesh.prototype._updateBoundingInfo = function () {
  18029. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18030. this._boundingInfo.update(this.worldMatrixFromCache);
  18031. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18032. return this;
  18033. };
  18034. /**
  18035. * Update a mesh's children BoundingInfo objects only.
  18036. * Returns the AbstractMesh.
  18037. */
  18038. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18039. if (!this.subMeshes) {
  18040. return this;
  18041. }
  18042. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18043. var subMesh = this.subMeshes[subIndex];
  18044. if (!subMesh.IsGlobal) {
  18045. subMesh.updateBoundingInfo(matrix);
  18046. }
  18047. }
  18048. return this;
  18049. };
  18050. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18051. // Bounding info
  18052. this._updateBoundingInfo();
  18053. };
  18054. /**
  18055. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18056. * A mesh is in the frustum if its bounding box intersects the frustum.
  18057. * Boolean returned.
  18058. */
  18059. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18060. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18061. };
  18062. /**
  18063. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18064. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18065. * Boolean returned.
  18066. */
  18067. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18068. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18069. ;
  18070. };
  18071. /**
  18072. * True if the mesh intersects another mesh or a SolidParticle object.
  18073. * 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)
  18074. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18075. * Returns a boolean.
  18076. */
  18077. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18078. if (precise === void 0) { precise = false; }
  18079. if (!this._boundingInfo || !mesh._boundingInfo) {
  18080. return false;
  18081. }
  18082. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18083. return true;
  18084. }
  18085. if (includeDescendants) {
  18086. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18087. var child = _a[_i];
  18088. if (child.intersectsMesh(mesh, precise, true)) {
  18089. return true;
  18090. }
  18091. }
  18092. }
  18093. return false;
  18094. };
  18095. /**
  18096. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18097. * Returns a boolean.
  18098. */
  18099. AbstractMesh.prototype.intersectsPoint = function (point) {
  18100. if (!this._boundingInfo) {
  18101. return false;
  18102. }
  18103. return this._boundingInfo.intersectsPoint(point);
  18104. };
  18105. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18106. return this.physicsImpostor;
  18107. };
  18108. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18109. if (camera === void 0) { camera = null; }
  18110. if (!camera) {
  18111. camera = this.getScene().activeCamera;
  18112. }
  18113. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18114. };
  18115. /**
  18116. * Returns the distance from the mesh to the active camera.
  18117. * Returns a float.
  18118. */
  18119. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18120. if (camera === void 0) { camera = null; }
  18121. if (!camera) {
  18122. camera = this.getScene().activeCamera;
  18123. }
  18124. return this.absolutePosition.subtract(camera.position).length();
  18125. };
  18126. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18127. if (!this.physicsImpostor) {
  18128. return this;
  18129. }
  18130. this.physicsImpostor.applyImpulse(force, contactPoint);
  18131. return this;
  18132. };
  18133. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18134. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18135. return this;
  18136. }
  18137. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18138. mainPivot: pivot1,
  18139. connectedPivot: pivot2,
  18140. nativeParams: options
  18141. });
  18142. return this;
  18143. };
  18144. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18145. // Collisions
  18146. /**
  18147. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18148. * Default `false`.
  18149. */
  18150. get: function () {
  18151. return this._checkCollisions;
  18152. },
  18153. set: function (collisionEnabled) {
  18154. this._checkCollisions = collisionEnabled;
  18155. if (this.getScene().workerCollisions) {
  18156. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18157. }
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18163. /**
  18164. * Gets Collider object used to compute collisions (not physics)
  18165. */
  18166. get: function () {
  18167. return this._collider;
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18173. var globalPosition = this.getAbsolutePosition();
  18174. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18175. if (!this._collider) {
  18176. this._collider = new BABYLON.Collider();
  18177. }
  18178. this._collider._radius = this.ellipsoid;
  18179. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18180. return this;
  18181. };
  18182. // Submeshes octree
  18183. /**
  18184. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18185. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18186. * Returns an Octree of submeshes.
  18187. */
  18188. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18189. if (maxCapacity === void 0) { maxCapacity = 64; }
  18190. if (maxDepth === void 0) { maxDepth = 2; }
  18191. if (!this._submeshesOctree) {
  18192. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18193. }
  18194. this.computeWorldMatrix(true);
  18195. var boundingInfo = this.getBoundingInfo();
  18196. // Update octree
  18197. var bbox = boundingInfo.boundingBox;
  18198. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18199. return this._submeshesOctree;
  18200. };
  18201. // Collisions
  18202. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18203. this._generatePointsArray();
  18204. if (!this._positions) {
  18205. return this;
  18206. }
  18207. // Transformation
  18208. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18209. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18210. subMesh._lastColliderWorldVertices = [];
  18211. subMesh._trianglePlanes = [];
  18212. var start = subMesh.verticesStart;
  18213. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18214. for (var i = start; i < end; i++) {
  18215. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18216. }
  18217. }
  18218. // Collide
  18219. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18220. if (collider.collisionFound) {
  18221. collider.collidedMesh = this;
  18222. }
  18223. return this;
  18224. };
  18225. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18226. var subMeshes;
  18227. var len;
  18228. // Octrees
  18229. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18230. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18231. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18232. len = intersections.length;
  18233. subMeshes = intersections.data;
  18234. }
  18235. else {
  18236. subMeshes = this.subMeshes;
  18237. len = subMeshes.length;
  18238. }
  18239. for (var index = 0; index < len; index++) {
  18240. var subMesh = subMeshes[index];
  18241. // Bounding test
  18242. if (len > 1 && !subMesh._checkCollision(collider))
  18243. continue;
  18244. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18245. }
  18246. return this;
  18247. };
  18248. AbstractMesh.prototype._checkCollision = function (collider) {
  18249. // Bounding box test
  18250. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18251. return this;
  18252. // Transformation matrix
  18253. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18254. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18255. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18256. return this;
  18257. };
  18258. // Picking
  18259. AbstractMesh.prototype._generatePointsArray = function () {
  18260. return false;
  18261. };
  18262. /**
  18263. * Checks if the passed Ray intersects with the mesh.
  18264. * Returns an object PickingInfo.
  18265. */
  18266. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18267. var pickingInfo = new BABYLON.PickingInfo();
  18268. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18269. return pickingInfo;
  18270. }
  18271. if (!this._generatePointsArray()) {
  18272. return pickingInfo;
  18273. }
  18274. var intersectInfo = null;
  18275. // Octrees
  18276. var subMeshes;
  18277. var len;
  18278. if (this._submeshesOctree && this.useOctreeForPicking) {
  18279. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18280. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18281. len = intersections.length;
  18282. subMeshes = intersections.data;
  18283. }
  18284. else {
  18285. subMeshes = this.subMeshes;
  18286. len = subMeshes.length;
  18287. }
  18288. for (var index = 0; index < len; index++) {
  18289. var subMesh = subMeshes[index];
  18290. // Bounding test
  18291. if (len > 1 && !subMesh.canIntersects(ray))
  18292. continue;
  18293. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18294. if (currentIntersectInfo) {
  18295. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18296. intersectInfo = currentIntersectInfo;
  18297. intersectInfo.subMeshId = index;
  18298. if (fastCheck) {
  18299. break;
  18300. }
  18301. }
  18302. }
  18303. }
  18304. if (intersectInfo) {
  18305. // Get picked point
  18306. var world = this.getWorldMatrix();
  18307. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18308. var direction = ray.direction.clone();
  18309. direction = direction.scale(intersectInfo.distance);
  18310. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18311. var pickedPoint = worldOrigin.add(worldDirection);
  18312. // Return result
  18313. pickingInfo.hit = true;
  18314. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18315. pickingInfo.pickedPoint = pickedPoint;
  18316. pickingInfo.pickedMesh = this;
  18317. pickingInfo.bu = intersectInfo.bu || 0;
  18318. pickingInfo.bv = intersectInfo.bv || 0;
  18319. pickingInfo.faceId = intersectInfo.faceId;
  18320. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18321. return pickingInfo;
  18322. }
  18323. return pickingInfo;
  18324. };
  18325. /**
  18326. * Clones the mesh, used by the class Mesh.
  18327. * Just returns `null` for an AbstractMesh.
  18328. */
  18329. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18330. return null;
  18331. };
  18332. /**
  18333. * Disposes all the mesh submeshes.
  18334. * Returns the AbstractMesh.
  18335. */
  18336. AbstractMesh.prototype.releaseSubMeshes = function () {
  18337. if (this.subMeshes) {
  18338. while (this.subMeshes.length) {
  18339. this.subMeshes[0].dispose();
  18340. }
  18341. }
  18342. else {
  18343. this.subMeshes = new Array();
  18344. }
  18345. return this;
  18346. };
  18347. /**
  18348. * Disposes the AbstractMesh.
  18349. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18350. * Returns nothing.
  18351. */
  18352. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18353. var _this = this;
  18354. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18355. var index;
  18356. // Action manager
  18357. if (this.actionManager !== undefined && this.actionManager !== null) {
  18358. this.actionManager.dispose();
  18359. this.actionManager = null;
  18360. }
  18361. // Skeleton
  18362. this.skeleton = null;
  18363. // Physics
  18364. if (this.physicsImpostor) {
  18365. this.physicsImpostor.dispose();
  18366. }
  18367. // Intersections in progress
  18368. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18369. var other = this._intersectionsInProgress[index];
  18370. var pos = other._intersectionsInProgress.indexOf(this);
  18371. other._intersectionsInProgress.splice(pos, 1);
  18372. }
  18373. this._intersectionsInProgress = [];
  18374. // Lights
  18375. var lights = this.getScene().lights;
  18376. lights.forEach(function (light) {
  18377. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18378. if (meshIndex !== -1) {
  18379. light.includedOnlyMeshes.splice(meshIndex, 1);
  18380. }
  18381. meshIndex = light.excludedMeshes.indexOf(_this);
  18382. if (meshIndex !== -1) {
  18383. light.excludedMeshes.splice(meshIndex, 1);
  18384. }
  18385. // Shadow generators
  18386. var generator = light.getShadowGenerator();
  18387. if (generator) {
  18388. var shadowMap = generator.getShadowMap();
  18389. if (shadowMap && shadowMap.renderList) {
  18390. meshIndex = shadowMap.renderList.indexOf(_this);
  18391. if (meshIndex !== -1) {
  18392. shadowMap.renderList.splice(meshIndex, 1);
  18393. }
  18394. }
  18395. }
  18396. });
  18397. // Edges
  18398. if (this._edgesRenderer) {
  18399. this._edgesRenderer.dispose();
  18400. this._edgesRenderer = null;
  18401. }
  18402. // SubMeshes
  18403. if (this.getClassName() !== "InstancedMesh") {
  18404. this.releaseSubMeshes();
  18405. }
  18406. // Octree
  18407. var sceneOctree = this.getScene().selectionOctree;
  18408. if (sceneOctree !== undefined && sceneOctree !== null) {
  18409. var index = sceneOctree.dynamicContent.indexOf(this);
  18410. if (index !== -1) {
  18411. sceneOctree.dynamicContent.splice(index, 1);
  18412. }
  18413. }
  18414. // Query
  18415. var engine = this.getScene().getEngine();
  18416. if (this._occlusionQuery) {
  18417. this._isOcclusionQueryInProgress = false;
  18418. engine.deleteQuery(this._occlusionQuery);
  18419. this._occlusionQuery = null;
  18420. }
  18421. // Engine
  18422. engine.wipeCaches();
  18423. // Remove from scene
  18424. this.getScene().removeMesh(this);
  18425. if (disposeMaterialAndTextures) {
  18426. if (this.material) {
  18427. this.material.dispose(false, true);
  18428. }
  18429. }
  18430. if (!doNotRecurse) {
  18431. // Particles
  18432. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18433. if (this.getScene().particleSystems[index].emitter === this) {
  18434. this.getScene().particleSystems[index].dispose();
  18435. index--;
  18436. }
  18437. }
  18438. }
  18439. // facet data
  18440. if (this._facetDataEnabled) {
  18441. this.disableFacetData();
  18442. }
  18443. this.onAfterWorldMatrixUpdateObservable.clear();
  18444. this.onCollideObservable.clear();
  18445. this.onCollisionPositionChangeObservable.clear();
  18446. _super.prototype.dispose.call(this, doNotRecurse);
  18447. };
  18448. /**
  18449. * Adds the passed mesh as a child to the current mesh.
  18450. * Returns the AbstractMesh.
  18451. */
  18452. AbstractMesh.prototype.addChild = function (mesh) {
  18453. mesh.setParent(this);
  18454. return this;
  18455. };
  18456. /**
  18457. * Removes the passed mesh from the current mesh children list.
  18458. * Returns the AbstractMesh.
  18459. */
  18460. AbstractMesh.prototype.removeChild = function (mesh) {
  18461. mesh.setParent(null);
  18462. return this;
  18463. };
  18464. // Facet data
  18465. /**
  18466. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18467. * Returns the AbstractMesh.
  18468. */
  18469. AbstractMesh.prototype._initFacetData = function () {
  18470. if (!this._facetNormals) {
  18471. this._facetNormals = new Array();
  18472. }
  18473. if (!this._facetPositions) {
  18474. this._facetPositions = new Array();
  18475. }
  18476. if (!this._facetPartitioning) {
  18477. this._facetPartitioning = new Array();
  18478. }
  18479. this._facetNb = (this.getIndices().length / 3) | 0;
  18480. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18481. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18482. for (var f = 0; f < this._facetNb; f++) {
  18483. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18484. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18485. }
  18486. this._facetDataEnabled = true;
  18487. return this;
  18488. };
  18489. /**
  18490. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18491. * This method can be called within the render loop.
  18492. * 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.
  18493. * Returns the AbstractMesh.
  18494. */
  18495. AbstractMesh.prototype.updateFacetData = function () {
  18496. if (!this._facetDataEnabled) {
  18497. this._initFacetData();
  18498. }
  18499. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18500. var indices = this.getIndices();
  18501. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18502. var bInfo = this.getBoundingInfo();
  18503. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18504. // init arrays, matrix and sort function on first call
  18505. this._facetDepthSortEnabled = true;
  18506. if (indices instanceof Uint16Array) {
  18507. this._depthSortedIndices = new Uint16Array(indices);
  18508. }
  18509. else if (indices instanceof Uint32Array) {
  18510. this._depthSortedIndices = new Uint32Array(indices);
  18511. }
  18512. else {
  18513. var needs32bits = false;
  18514. for (var i = 0; i < indices.length; i++) {
  18515. if (indices[i] > 65535) {
  18516. needs32bits = true;
  18517. break;
  18518. }
  18519. }
  18520. if (needs32bits) {
  18521. this._depthSortedIndices = new Uint32Array(indices);
  18522. }
  18523. else {
  18524. this._depthSortedIndices = new Uint16Array(indices);
  18525. }
  18526. }
  18527. this._facetDepthSortFunction = function (f1, f2) {
  18528. return (f2.sqDistance - f1.sqDistance);
  18529. };
  18530. if (!this._facetDepthSortFrom) {
  18531. var camera = this.getScene().activeCamera;
  18532. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18533. }
  18534. this._depthSortedFacets = [];
  18535. for (var f = 0; f < this._facetNb; f++) {
  18536. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18537. this._depthSortedFacets.push(depthSortedFacet);
  18538. }
  18539. this._invertedMatrix = BABYLON.Matrix.Identity();
  18540. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18541. }
  18542. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18543. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18544. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18545. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18546. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18547. this._subDiv.max = this._partitioningSubdivisions;
  18548. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18549. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18550. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18551. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18552. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18553. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18554. // set the parameters for ComputeNormals()
  18555. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18556. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18557. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18558. this._facetParameters.bInfo = bInfo;
  18559. this._facetParameters.bbSize = this._bbSize;
  18560. this._facetParameters.subDiv = this._subDiv;
  18561. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18562. this._facetParameters.depthSort = this._facetDepthSort;
  18563. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18564. this.computeWorldMatrix(true);
  18565. this._worldMatrix.invertToRef(this._invertedMatrix);
  18566. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18567. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18568. }
  18569. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18570. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18571. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18572. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18573. var l = (this._depthSortedIndices.length / 3) | 0;
  18574. for (var f = 0; f < l; f++) {
  18575. var sind = this._depthSortedFacets[f].ind;
  18576. this._depthSortedIndices[f * 3] = indices[sind];
  18577. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18578. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18579. }
  18580. this.updateIndices(this._depthSortedIndices);
  18581. }
  18582. return this;
  18583. };
  18584. /**
  18585. * Returns the facetLocalNormals array.
  18586. * The normals are expressed in the mesh local space.
  18587. */
  18588. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18589. if (!this._facetNormals) {
  18590. this.updateFacetData();
  18591. }
  18592. return this._facetNormals;
  18593. };
  18594. /**
  18595. * Returns the facetLocalPositions array.
  18596. * The facet positions are expressed in the mesh local space.
  18597. */
  18598. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18599. if (!this._facetPositions) {
  18600. this.updateFacetData();
  18601. }
  18602. return this._facetPositions;
  18603. };
  18604. /**
  18605. * Returns the facetLocalPartioning array.
  18606. */
  18607. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18608. if (!this._facetPartitioning) {
  18609. this.updateFacetData();
  18610. }
  18611. return this._facetPartitioning;
  18612. };
  18613. /**
  18614. * Returns the i-th facet position in the world system.
  18615. * This method allocates a new Vector3 per call.
  18616. */
  18617. AbstractMesh.prototype.getFacetPosition = function (i) {
  18618. var pos = BABYLON.Vector3.Zero();
  18619. this.getFacetPositionToRef(i, pos);
  18620. return pos;
  18621. };
  18622. /**
  18623. * Sets the reference Vector3 with the i-th facet position in the world system.
  18624. * Returns the AbstractMesh.
  18625. */
  18626. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18627. var localPos = (this.getFacetLocalPositions())[i];
  18628. var world = this.getWorldMatrix();
  18629. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18630. return this;
  18631. };
  18632. /**
  18633. * Returns the i-th facet normal in the world system.
  18634. * This method allocates a new Vector3 per call.
  18635. */
  18636. AbstractMesh.prototype.getFacetNormal = function (i) {
  18637. var norm = BABYLON.Vector3.Zero();
  18638. this.getFacetNormalToRef(i, norm);
  18639. return norm;
  18640. };
  18641. /**
  18642. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18643. * Returns the AbstractMesh.
  18644. */
  18645. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18646. var localNorm = (this.getFacetLocalNormals())[i];
  18647. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18648. return this;
  18649. };
  18650. /**
  18651. * 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).
  18652. */
  18653. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18654. var bInfo = this.getBoundingInfo();
  18655. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18656. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18657. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18658. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18659. return null;
  18660. }
  18661. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18662. };
  18663. /**
  18664. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18665. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18666. * 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.
  18667. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18668. * 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.
  18669. */
  18670. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18671. if (checkFace === void 0) { checkFace = false; }
  18672. if (facing === void 0) { facing = true; }
  18673. var world = this.getWorldMatrix();
  18674. var invMat = BABYLON.Tmp.Matrix[5];
  18675. world.invertToRef(invMat);
  18676. var invVect = BABYLON.Tmp.Vector3[8];
  18677. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18678. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18679. if (projected) {
  18680. // tranform the local computed projected vector to world coordinates
  18681. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18682. }
  18683. return closest;
  18684. };
  18685. /**
  18686. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18687. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18688. * 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.
  18689. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18690. * 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.
  18691. */
  18692. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18693. if (checkFace === void 0) { checkFace = false; }
  18694. if (facing === void 0) { facing = true; }
  18695. var closest = null;
  18696. var tmpx = 0.0;
  18697. var tmpy = 0.0;
  18698. var tmpz = 0.0;
  18699. var d = 0.0; // tmp dot facet normal * facet position
  18700. var t0 = 0.0;
  18701. var projx = 0.0;
  18702. var projy = 0.0;
  18703. var projz = 0.0;
  18704. // Get all the facets in the same partitioning block than (x, y, z)
  18705. var facetPositions = this.getFacetLocalPositions();
  18706. var facetNormals = this.getFacetLocalNormals();
  18707. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18708. if (!facetsInBlock) {
  18709. return null;
  18710. }
  18711. // Get the closest facet to (x, y, z)
  18712. var shortest = Number.MAX_VALUE; // init distance vars
  18713. var tmpDistance = shortest;
  18714. var fib; // current facet in the block
  18715. var norm; // current facet normal
  18716. var p0; // current facet barycenter position
  18717. // loop on all the facets in the current partitioning block
  18718. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18719. fib = facetsInBlock[idx];
  18720. norm = facetNormals[fib];
  18721. p0 = facetPositions[fib];
  18722. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18723. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18724. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18725. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18726. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18727. projx = x + norm.x * t0;
  18728. projy = y + norm.y * t0;
  18729. projz = z + norm.z * t0;
  18730. tmpx = projx - x;
  18731. tmpy = projy - y;
  18732. tmpz = projz - z;
  18733. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18734. if (tmpDistance < shortest) {
  18735. shortest = tmpDistance;
  18736. closest = fib;
  18737. if (projected) {
  18738. projected.x = projx;
  18739. projected.y = projy;
  18740. projected.z = projz;
  18741. }
  18742. }
  18743. }
  18744. }
  18745. return closest;
  18746. };
  18747. /**
  18748. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18749. */
  18750. AbstractMesh.prototype.getFacetDataParameters = function () {
  18751. return this._facetParameters;
  18752. };
  18753. /**
  18754. * Disables the feature FacetData and frees the related memory.
  18755. * Returns the AbstractMesh.
  18756. */
  18757. AbstractMesh.prototype.disableFacetData = function () {
  18758. if (this._facetDataEnabled) {
  18759. this._facetDataEnabled = false;
  18760. this._facetPositions = new Array();
  18761. this._facetNormals = new Array();
  18762. this._facetPartitioning = new Array();
  18763. this._facetParameters = null;
  18764. this._depthSortedIndices = new Uint32Array(0);
  18765. }
  18766. return this;
  18767. };
  18768. /**
  18769. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18770. * Returns the mesh.
  18771. */
  18772. AbstractMesh.prototype.updateIndices = function (indices) {
  18773. return this;
  18774. };
  18775. /**
  18776. * The mesh Geometry. Actually used by the Mesh object.
  18777. * Returns a blank geometry object.
  18778. */
  18779. /**
  18780. * Creates new normals data for the mesh.
  18781. * @param updatable.
  18782. */
  18783. AbstractMesh.prototype.createNormals = function (updatable) {
  18784. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18785. var indices = this.getIndices();
  18786. var normals;
  18787. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18788. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18789. }
  18790. else {
  18791. normals = [];
  18792. }
  18793. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18794. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18795. };
  18796. /**
  18797. * Align the mesh with a normal.
  18798. * Returns the mesh.
  18799. */
  18800. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18801. if (!upDirection) {
  18802. upDirection = BABYLON.Axis.Y;
  18803. }
  18804. var axisX = BABYLON.Tmp.Vector3[0];
  18805. var axisZ = BABYLON.Tmp.Vector3[1];
  18806. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18807. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18808. if (this.rotationQuaternion) {
  18809. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18810. }
  18811. else {
  18812. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18813. }
  18814. return this;
  18815. };
  18816. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18817. var engine = this.getEngine();
  18818. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18819. this._isOccluded = false;
  18820. return;
  18821. }
  18822. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18823. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18824. if (isOcclusionQueryAvailable) {
  18825. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18826. this._isOcclusionQueryInProgress = false;
  18827. this._occlusionInternalRetryCounter = 0;
  18828. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18829. }
  18830. else {
  18831. this._occlusionInternalRetryCounter++;
  18832. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18833. this._isOcclusionQueryInProgress = false;
  18834. this._occlusionInternalRetryCounter = 0;
  18835. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18836. // if strict continue the last state of the object.
  18837. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18838. }
  18839. else {
  18840. return;
  18841. }
  18842. }
  18843. }
  18844. var scene = this.getScene();
  18845. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18846. if (!this._occlusionQuery) {
  18847. this._occlusionQuery = engine.createQuery();
  18848. }
  18849. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18850. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18851. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18852. this._isOcclusionQueryInProgress = true;
  18853. };
  18854. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18855. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18856. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18857. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18858. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18859. return AbstractMesh;
  18860. }(BABYLON.TransformNode));
  18861. BABYLON.AbstractMesh = AbstractMesh;
  18862. })(BABYLON || (BABYLON = {}));
  18863. //# sourceMappingURL=babylon.abstractMesh.js.map
  18864. var BABYLON;
  18865. (function (BABYLON) {
  18866. /**
  18867. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18868. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18869. * 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.
  18870. */
  18871. var Light = /** @class */ (function (_super) {
  18872. __extends(Light, _super);
  18873. /**
  18874. * Creates a Light object in the scene.
  18875. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18876. * @param name The firendly name of the light
  18877. * @param scene The scene the light belongs too
  18878. */
  18879. function Light(name, scene) {
  18880. var _this = _super.call(this, name, scene) || this;
  18881. /**
  18882. * Diffuse gives the basic color to an object.
  18883. */
  18884. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18885. /**
  18886. * Specular produces a highlight color on an object.
  18887. * Note: This is note affecting PBR materials.
  18888. */
  18889. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18890. /**
  18891. * Strength of the light.
  18892. * Note: By default it is define in the framework own unit.
  18893. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18894. */
  18895. _this.intensity = 1.0;
  18896. /**
  18897. * Defines how far from the source the light is impacting in scene units.
  18898. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18899. */
  18900. _this.range = Number.MAX_VALUE;
  18901. /**
  18902. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18903. * of light.
  18904. */
  18905. _this._photometricScale = 1.0;
  18906. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18907. _this._radius = 0.00001;
  18908. /**
  18909. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18910. * exceeding the number allowed of the materials.
  18911. */
  18912. _this.renderPriority = 0;
  18913. /**
  18914. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18915. * the current shadow generator.
  18916. */
  18917. _this.shadowEnabled = true;
  18918. _this._excludeWithLayerMask = 0;
  18919. _this._includeOnlyWithLayerMask = 0;
  18920. _this._lightmapMode = 0;
  18921. /**
  18922. * @ignore Internal use only.
  18923. */
  18924. _this._excludedMeshesIds = new Array();
  18925. /**
  18926. * @ignore Internal use only.
  18927. */
  18928. _this._includedOnlyMeshesIds = new Array();
  18929. _this.getScene().addLight(_this);
  18930. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18931. _this._buildUniformLayout();
  18932. _this.includedOnlyMeshes = new Array();
  18933. _this.excludedMeshes = new Array();
  18934. _this._resyncMeshes();
  18935. return _this;
  18936. }
  18937. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18938. /**
  18939. * If every light affecting the material is in this lightmapMode,
  18940. * material.lightmapTexture adds or multiplies
  18941. * (depends on material.useLightmapAsShadowmap)
  18942. * after every other light calculations.
  18943. */
  18944. get: function () {
  18945. return Light._LIGHTMAP_DEFAULT;
  18946. },
  18947. enumerable: true,
  18948. configurable: true
  18949. });
  18950. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18951. /**
  18952. * material.lightmapTexture as only diffuse lighting from this light
  18953. * adds only specular lighting from this light
  18954. * adds dynamic shadows
  18955. */
  18956. get: function () {
  18957. return Light._LIGHTMAP_SPECULAR;
  18958. },
  18959. enumerable: true,
  18960. configurable: true
  18961. });
  18962. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18963. /**
  18964. * material.lightmapTexture as only lighting
  18965. * no light calculation from this light
  18966. * only adds dynamic shadows from this light
  18967. */
  18968. get: function () {
  18969. return Light._LIGHTMAP_SHADOWSONLY;
  18970. },
  18971. enumerable: true,
  18972. configurable: true
  18973. });
  18974. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18975. /**
  18976. * Each light type uses the default quantity according to its type:
  18977. * point/spot lights use luminous intensity
  18978. * directional lights use illuminance
  18979. */
  18980. get: function () {
  18981. return Light._INTENSITYMODE_AUTOMATIC;
  18982. },
  18983. enumerable: true,
  18984. configurable: true
  18985. });
  18986. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18987. /**
  18988. * lumen (lm)
  18989. */
  18990. get: function () {
  18991. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18992. },
  18993. enumerable: true,
  18994. configurable: true
  18995. });
  18996. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18997. /**
  18998. * candela (lm/sr)
  18999. */
  19000. get: function () {
  19001. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19002. },
  19003. enumerable: true,
  19004. configurable: true
  19005. });
  19006. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19007. /**
  19008. * lux (lm/m^2)
  19009. */
  19010. get: function () {
  19011. return Light._INTENSITYMODE_ILLUMINANCE;
  19012. },
  19013. enumerable: true,
  19014. configurable: true
  19015. });
  19016. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19017. /**
  19018. * nit (cd/m^2)
  19019. */
  19020. get: function () {
  19021. return Light._INTENSITYMODE_LUMINANCE;
  19022. },
  19023. enumerable: true,
  19024. configurable: true
  19025. });
  19026. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19027. /**
  19028. * Light type const id of the point light.
  19029. */
  19030. get: function () {
  19031. return Light._LIGHTTYPEID_POINTLIGHT;
  19032. },
  19033. enumerable: true,
  19034. configurable: true
  19035. });
  19036. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19037. /**
  19038. * Light type const id of the directional light.
  19039. */
  19040. get: function () {
  19041. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19042. },
  19043. enumerable: true,
  19044. configurable: true
  19045. });
  19046. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19047. /**
  19048. * Light type const id of the spot light.
  19049. */
  19050. get: function () {
  19051. return Light._LIGHTTYPEID_SPOTLIGHT;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19057. /**
  19058. * Light type const id of the hemispheric light.
  19059. */
  19060. get: function () {
  19061. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19062. },
  19063. enumerable: true,
  19064. configurable: true
  19065. });
  19066. Object.defineProperty(Light.prototype, "intensityMode", {
  19067. /**
  19068. * Gets the photometric scale used to interpret the intensity.
  19069. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19070. */
  19071. get: function () {
  19072. return this._intensityMode;
  19073. },
  19074. /**
  19075. * Sets the photometric scale used to interpret the intensity.
  19076. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19077. */
  19078. set: function (value) {
  19079. this._intensityMode = value;
  19080. this._computePhotometricScale();
  19081. },
  19082. enumerable: true,
  19083. configurable: true
  19084. });
  19085. ;
  19086. ;
  19087. Object.defineProperty(Light.prototype, "radius", {
  19088. /**
  19089. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19090. */
  19091. get: function () {
  19092. return this._radius;
  19093. },
  19094. /**
  19095. * sets the light radius used by PBR Materials to simulate soft area lights.
  19096. */
  19097. set: function (value) {
  19098. this._radius = value;
  19099. this._computePhotometricScale();
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. ;
  19105. ;
  19106. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19107. /**
  19108. * Gets the only meshes impacted by this light.
  19109. */
  19110. get: function () {
  19111. return this._includedOnlyMeshes;
  19112. },
  19113. /**
  19114. * Sets the only meshes impacted by this light.
  19115. */
  19116. set: function (value) {
  19117. this._includedOnlyMeshes = value;
  19118. this._hookArrayForIncludedOnly(value);
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19124. /**
  19125. * Gets the meshes not impacted by this light.
  19126. */
  19127. get: function () {
  19128. return this._excludedMeshes;
  19129. },
  19130. /**
  19131. * Sets the meshes not impacted by this light.
  19132. */
  19133. set: function (value) {
  19134. this._excludedMeshes = value;
  19135. this._hookArrayForExcluded(value);
  19136. },
  19137. enumerable: true,
  19138. configurable: true
  19139. });
  19140. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19141. /**
  19142. * Gets the layer id use to find what meshes are not impacted by the light.
  19143. * Inactive if 0
  19144. */
  19145. get: function () {
  19146. return this._excludeWithLayerMask;
  19147. },
  19148. /**
  19149. * Sets the layer id use to find what meshes are not impacted by the light.
  19150. * Inactive if 0
  19151. */
  19152. set: function (value) {
  19153. this._excludeWithLayerMask = value;
  19154. this._resyncMeshes();
  19155. },
  19156. enumerable: true,
  19157. configurable: true
  19158. });
  19159. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19160. /**
  19161. * Gets the layer id use to find what meshes are impacted by the light.
  19162. * Inactive if 0
  19163. */
  19164. get: function () {
  19165. return this._includeOnlyWithLayerMask;
  19166. },
  19167. /**
  19168. * Sets the layer id use to find what meshes are impacted by the light.
  19169. * Inactive if 0
  19170. */
  19171. set: function (value) {
  19172. this._includeOnlyWithLayerMask = value;
  19173. this._resyncMeshes();
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. Object.defineProperty(Light.prototype, "lightmapMode", {
  19179. /**
  19180. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19181. */
  19182. get: function () {
  19183. return this._lightmapMode;
  19184. },
  19185. /**
  19186. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19187. */
  19188. set: function (value) {
  19189. if (this._lightmapMode === value) {
  19190. return;
  19191. }
  19192. this._lightmapMode = value;
  19193. this._markMeshesAsLightDirty();
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. /**
  19199. * Returns the string "Light".
  19200. * @returns the class name
  19201. */
  19202. Light.prototype.getClassName = function () {
  19203. return "Light";
  19204. };
  19205. /**
  19206. * Converts the light information to a readable string for debug purpose.
  19207. * @param fullDetails Supports for multiple levels of logging within scene loading
  19208. * @returns the human readable light info
  19209. */
  19210. Light.prototype.toString = function (fullDetails) {
  19211. var ret = "Name: " + this.name;
  19212. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19213. if (this.animations) {
  19214. for (var i = 0; i < this.animations.length; i++) {
  19215. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19216. }
  19217. }
  19218. if (fullDetails) {
  19219. }
  19220. return ret;
  19221. };
  19222. /**
  19223. * Set the enabled state of this node.
  19224. * @param value - the new enabled state
  19225. * @see isEnabled
  19226. */
  19227. Light.prototype.setEnabled = function (value) {
  19228. _super.prototype.setEnabled.call(this, value);
  19229. this._resyncMeshes();
  19230. };
  19231. /**
  19232. * Returns the Light associated shadow generator if any.
  19233. * @return the associated shadow generator.
  19234. */
  19235. Light.prototype.getShadowGenerator = function () {
  19236. return this._shadowGenerator;
  19237. };
  19238. /**
  19239. * Returns a Vector3, the absolute light position in the World.
  19240. * @returns the world space position of the light
  19241. */
  19242. Light.prototype.getAbsolutePosition = function () {
  19243. return BABYLON.Vector3.Zero();
  19244. };
  19245. /**
  19246. * Specifies if the light will affect the passed mesh.
  19247. * @param mesh The mesh to test against the light
  19248. * @return true the mesh is affected otherwise, false.
  19249. */
  19250. Light.prototype.canAffectMesh = function (mesh) {
  19251. if (!mesh) {
  19252. return true;
  19253. }
  19254. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19255. return false;
  19256. }
  19257. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19258. return false;
  19259. }
  19260. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19261. return false;
  19262. }
  19263. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19264. return false;
  19265. }
  19266. return true;
  19267. };
  19268. /**
  19269. * Computes and Returns the light World matrix.
  19270. * @returns the world matrix
  19271. */
  19272. Light.prototype.getWorldMatrix = function () {
  19273. this._currentRenderId = this.getScene().getRenderId();
  19274. var worldMatrix = this._getWorldMatrix();
  19275. if (this.parent && this.parent.getWorldMatrix) {
  19276. if (!this._parentedWorldMatrix) {
  19277. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19278. }
  19279. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19280. this._markSyncedWithParent();
  19281. return this._parentedWorldMatrix;
  19282. }
  19283. return worldMatrix;
  19284. };
  19285. /**
  19286. * Sort function to order lights for rendering.
  19287. * @param a First Light object to compare to second.
  19288. * @param b Second Light object to compare first.
  19289. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19290. */
  19291. Light.CompareLightsPriority = function (a, b) {
  19292. //shadow-casting lights have priority over non-shadow-casting lights
  19293. //the renderPrioirty is a secondary sort criterion
  19294. if (a.shadowEnabled !== b.shadowEnabled) {
  19295. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19296. }
  19297. return b.renderPriority - a.renderPriority;
  19298. };
  19299. /**
  19300. * Disposes the light.
  19301. */
  19302. Light.prototype.dispose = function () {
  19303. if (this._shadowGenerator) {
  19304. this._shadowGenerator.dispose();
  19305. this._shadowGenerator = null;
  19306. }
  19307. // Animations
  19308. this.getScene().stopAnimation(this);
  19309. // Remove from meshes
  19310. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19311. var mesh = _a[_i];
  19312. mesh._removeLightSource(this);
  19313. }
  19314. this._uniformBuffer.dispose();
  19315. // Remove from scene
  19316. this.getScene().removeLight(this);
  19317. _super.prototype.dispose.call(this);
  19318. };
  19319. /**
  19320. * Returns the light type ID (integer).
  19321. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19322. */
  19323. Light.prototype.getTypeID = function () {
  19324. return 0;
  19325. };
  19326. /**
  19327. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19328. * @returns the scaled intensity in intensity mode unit
  19329. */
  19330. Light.prototype.getScaledIntensity = function () {
  19331. return this._photometricScale * this.intensity;
  19332. };
  19333. /**
  19334. * Returns a new Light object, named "name", from the current one.
  19335. * @param name The name of the cloned light
  19336. * @returns the new created light
  19337. */
  19338. Light.prototype.clone = function (name) {
  19339. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19340. if (!constructor) {
  19341. return null;
  19342. }
  19343. return BABYLON.SerializationHelper.Clone(constructor, this);
  19344. };
  19345. /**
  19346. * Serializes the current light into a Serialization object.
  19347. * @returns the serialized object.
  19348. */
  19349. Light.prototype.serialize = function () {
  19350. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19351. // Type
  19352. serializationObject.type = this.getTypeID();
  19353. // Parent
  19354. if (this.parent) {
  19355. serializationObject.parentId = this.parent.id;
  19356. }
  19357. // Inclusion / exclusions
  19358. if (this.excludedMeshes.length > 0) {
  19359. serializationObject.excludedMeshesIds = [];
  19360. this.excludedMeshes.forEach(function (mesh) {
  19361. serializationObject.excludedMeshesIds.push(mesh.id);
  19362. });
  19363. }
  19364. if (this.includedOnlyMeshes.length > 0) {
  19365. serializationObject.includedOnlyMeshesIds = [];
  19366. this.includedOnlyMeshes.forEach(function (mesh) {
  19367. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19368. });
  19369. }
  19370. // Animations
  19371. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19372. serializationObject.ranges = this.serializeAnimationRanges();
  19373. return serializationObject;
  19374. };
  19375. /**
  19376. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19377. * This new light is named "name" and added to the passed scene.
  19378. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19379. * @param name The friendly name of the light
  19380. * @param scene The scene the new light will belong to
  19381. * @returns the constructor function
  19382. */
  19383. Light.GetConstructorFromName = function (type, name, scene) {
  19384. switch (type) {
  19385. case 0:
  19386. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19387. case 1:
  19388. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19389. case 2:
  19390. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19391. case 3:
  19392. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19393. }
  19394. return null;
  19395. };
  19396. /**
  19397. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19398. * @param parsedLight The JSON representation of the light
  19399. * @param scene The scene to create the parsed light in
  19400. * @returns the created light after parsing
  19401. */
  19402. Light.Parse = function (parsedLight, scene) {
  19403. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19404. if (!constructor) {
  19405. return null;
  19406. }
  19407. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19408. // Inclusion / exclusions
  19409. if (parsedLight.excludedMeshesIds) {
  19410. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19411. }
  19412. if (parsedLight.includedOnlyMeshesIds) {
  19413. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19414. }
  19415. // Parent
  19416. if (parsedLight.parentId) {
  19417. light._waitingParentId = parsedLight.parentId;
  19418. }
  19419. // Animations
  19420. if (parsedLight.animations) {
  19421. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19422. var parsedAnimation = parsedLight.animations[animationIndex];
  19423. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19424. }
  19425. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19426. }
  19427. if (parsedLight.autoAnimate) {
  19428. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19429. }
  19430. return light;
  19431. };
  19432. Light.prototype._hookArrayForExcluded = function (array) {
  19433. var _this = this;
  19434. var oldPush = array.push;
  19435. array.push = function () {
  19436. var items = [];
  19437. for (var _i = 0; _i < arguments.length; _i++) {
  19438. items[_i] = arguments[_i];
  19439. }
  19440. var result = oldPush.apply(array, items);
  19441. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19442. var item = items_1[_a];
  19443. item._resyncLighSource(_this);
  19444. }
  19445. return result;
  19446. };
  19447. var oldSplice = array.splice;
  19448. array.splice = function (index, deleteCount) {
  19449. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19450. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19451. var item = deleted_1[_i];
  19452. item._resyncLighSource(_this);
  19453. }
  19454. return deleted;
  19455. };
  19456. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19457. var item = array_1[_i];
  19458. item._resyncLighSource(this);
  19459. }
  19460. };
  19461. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19462. var _this = this;
  19463. var oldPush = array.push;
  19464. array.push = function () {
  19465. var items = [];
  19466. for (var _i = 0; _i < arguments.length; _i++) {
  19467. items[_i] = arguments[_i];
  19468. }
  19469. var result = oldPush.apply(array, items);
  19470. _this._resyncMeshes();
  19471. return result;
  19472. };
  19473. var oldSplice = array.splice;
  19474. array.splice = function (index, deleteCount) {
  19475. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19476. _this._resyncMeshes();
  19477. return deleted;
  19478. };
  19479. this._resyncMeshes();
  19480. };
  19481. Light.prototype._resyncMeshes = function () {
  19482. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19483. var mesh = _a[_i];
  19484. mesh._resyncLighSource(this);
  19485. }
  19486. };
  19487. /**
  19488. * Forces the meshes to update their light related information in their rendering used effects
  19489. * @ignore Internal Use Only
  19490. */
  19491. Light.prototype._markMeshesAsLightDirty = function () {
  19492. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19493. var mesh = _a[_i];
  19494. if (mesh._lightSources.indexOf(this) !== -1) {
  19495. mesh._markSubMeshesAsLightDirty();
  19496. }
  19497. }
  19498. };
  19499. /**
  19500. * Recomputes the cached photometric scale if needed.
  19501. */
  19502. Light.prototype._computePhotometricScale = function () {
  19503. this._photometricScale = this._getPhotometricScale();
  19504. this.getScene().resetCachedMaterial();
  19505. };
  19506. /**
  19507. * Returns the Photometric Scale according to the light type and intensity mode.
  19508. */
  19509. Light.prototype._getPhotometricScale = function () {
  19510. var photometricScale = 0.0;
  19511. var lightTypeID = this.getTypeID();
  19512. //get photometric mode
  19513. var photometricMode = this.intensityMode;
  19514. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19515. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19516. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19517. }
  19518. else {
  19519. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19520. }
  19521. }
  19522. //compute photometric scale
  19523. switch (lightTypeID) {
  19524. case Light.LIGHTTYPEID_POINTLIGHT:
  19525. case Light.LIGHTTYPEID_SPOTLIGHT:
  19526. switch (photometricMode) {
  19527. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19528. photometricScale = 1.0 / (4.0 * Math.PI);
  19529. break;
  19530. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19531. photometricScale = 1.0;
  19532. break;
  19533. case Light.INTENSITYMODE_LUMINANCE:
  19534. photometricScale = this.radius * this.radius;
  19535. break;
  19536. }
  19537. break;
  19538. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19539. switch (photometricMode) {
  19540. case Light.INTENSITYMODE_ILLUMINANCE:
  19541. photometricScale = 1.0;
  19542. break;
  19543. case Light.INTENSITYMODE_LUMINANCE:
  19544. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19545. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19546. var apexAngleRadians = this.radius;
  19547. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19548. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19549. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19550. photometricScale = solidAngle;
  19551. break;
  19552. }
  19553. break;
  19554. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19555. // No fall off in hemisperic light.
  19556. photometricScale = 1.0;
  19557. break;
  19558. }
  19559. return photometricScale;
  19560. };
  19561. /**
  19562. * Reorder the light in the scene according to their defined priority.
  19563. * @ignore Internal Use Only
  19564. */
  19565. Light.prototype._reorderLightsInScene = function () {
  19566. var scene = this.getScene();
  19567. if (this._renderPriority != 0) {
  19568. scene.requireLightSorting = true;
  19569. }
  19570. this.getScene().sortLightsByPriority();
  19571. };
  19572. //lightmapMode Consts
  19573. Light._LIGHTMAP_DEFAULT = 0;
  19574. Light._LIGHTMAP_SPECULAR = 1;
  19575. Light._LIGHTMAP_SHADOWSONLY = 2;
  19576. // Intensity Mode Consts
  19577. Light._INTENSITYMODE_AUTOMATIC = 0;
  19578. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19579. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19580. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19581. Light._INTENSITYMODE_LUMINANCE = 4;
  19582. // Light types ids const.
  19583. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19584. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19585. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19586. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19587. __decorate([
  19588. BABYLON.serializeAsColor3()
  19589. ], Light.prototype, "diffuse", void 0);
  19590. __decorate([
  19591. BABYLON.serializeAsColor3()
  19592. ], Light.prototype, "specular", void 0);
  19593. __decorate([
  19594. BABYLON.serialize()
  19595. ], Light.prototype, "intensity", void 0);
  19596. __decorate([
  19597. BABYLON.serialize()
  19598. ], Light.prototype, "range", void 0);
  19599. __decorate([
  19600. BABYLON.serialize()
  19601. ], Light.prototype, "intensityMode", null);
  19602. __decorate([
  19603. BABYLON.serialize()
  19604. ], Light.prototype, "radius", null);
  19605. __decorate([
  19606. BABYLON.serialize()
  19607. ], Light.prototype, "_renderPriority", void 0);
  19608. __decorate([
  19609. BABYLON.expandToProperty("_reorderLightsInScene")
  19610. ], Light.prototype, "renderPriority", void 0);
  19611. __decorate([
  19612. BABYLON.serialize()
  19613. ], Light.prototype, "shadowEnabled", void 0);
  19614. __decorate([
  19615. BABYLON.serialize("excludeWithLayerMask")
  19616. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19617. __decorate([
  19618. BABYLON.serialize("includeOnlyWithLayerMask")
  19619. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19620. __decorate([
  19621. BABYLON.serialize("lightmapMode")
  19622. ], Light.prototype, "_lightmapMode", void 0);
  19623. return Light;
  19624. }(BABYLON.Node));
  19625. BABYLON.Light = Light;
  19626. })(BABYLON || (BABYLON = {}));
  19627. //# sourceMappingURL=babylon.light.js.map
  19628. var BABYLON;
  19629. (function (BABYLON) {
  19630. var Camera = /** @class */ (function (_super) {
  19631. __extends(Camera, _super);
  19632. function Camera(name, position, scene) {
  19633. var _this = _super.call(this, name, scene) || this;
  19634. /**
  19635. * The vector the camera should consider as up.
  19636. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19637. */
  19638. _this.upVector = BABYLON.Vector3.Up();
  19639. _this.orthoLeft = null;
  19640. _this.orthoRight = null;
  19641. _this.orthoBottom = null;
  19642. _this.orthoTop = null;
  19643. /**
  19644. * FOV is set in Radians. (default is 0.8)
  19645. */
  19646. _this.fov = 0.8;
  19647. _this.minZ = 1;
  19648. _this.maxZ = 10000.0;
  19649. _this.inertia = 0.9;
  19650. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19651. _this.isIntermediate = false;
  19652. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19653. /**
  19654. * Restricts the camera to viewing objects with the same layerMask.
  19655. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19656. */
  19657. _this.layerMask = 0x0FFFFFFF;
  19658. /**
  19659. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19660. */
  19661. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19662. // Camera rig members
  19663. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19664. _this._rigCameras = new Array();
  19665. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19666. _this._skipRendering = false;
  19667. _this.customRenderTargets = new Array();
  19668. // Observables
  19669. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19670. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19671. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19672. _this.onRestoreStateObservable = new BABYLON.Observable();
  19673. // Cache
  19674. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19675. _this._projectionMatrix = new BABYLON.Matrix();
  19676. _this._doNotComputeProjectionMatrix = false;
  19677. _this._postProcesses = new Array();
  19678. _this._transformMatrix = BABYLON.Matrix.Zero();
  19679. _this._activeMeshes = new BABYLON.SmartArray(256);
  19680. _this._globalPosition = BABYLON.Vector3.Zero();
  19681. _this._refreshFrustumPlanes = true;
  19682. _this.getScene().addCamera(_this);
  19683. if (!_this.getScene().activeCamera) {
  19684. _this.getScene().activeCamera = _this;
  19685. }
  19686. _this.position = position;
  19687. return _this;
  19688. }
  19689. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19690. get: function () {
  19691. return Camera._PERSPECTIVE_CAMERA;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19697. get: function () {
  19698. return Camera._ORTHOGRAPHIC_CAMERA;
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19704. /**
  19705. * This is the default FOV mode for perspective cameras.
  19706. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19707. *
  19708. */
  19709. get: function () {
  19710. return Camera._FOVMODE_VERTICAL_FIXED;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19716. /**
  19717. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19718. *
  19719. */
  19720. get: function () {
  19721. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19727. get: function () {
  19728. return Camera._RIG_MODE_NONE;
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19734. get: function () {
  19735. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19741. get: function () {
  19742. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19743. },
  19744. enumerable: true,
  19745. configurable: true
  19746. });
  19747. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19748. get: function () {
  19749. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19750. },
  19751. enumerable: true,
  19752. configurable: true
  19753. });
  19754. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19755. get: function () {
  19756. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19762. get: function () {
  19763. return Camera._RIG_MODE_VR;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19769. get: function () {
  19770. return Camera._RIG_MODE_WEBVR;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. /**
  19776. * Store current camera state (fov, position, etc..)
  19777. */
  19778. Camera.prototype.storeState = function () {
  19779. this._stateStored = true;
  19780. this._storedFov = this.fov;
  19781. return this;
  19782. };
  19783. /**
  19784. * Restores the camera state values if it has been stored. You must call storeState() first
  19785. */
  19786. Camera.prototype._restoreStateValues = function () {
  19787. if (!this._stateStored) {
  19788. return false;
  19789. }
  19790. this.fov = this._storedFov;
  19791. return true;
  19792. };
  19793. /**
  19794. * Restored camera state. You must call storeState() first
  19795. */
  19796. Camera.prototype.restoreState = function () {
  19797. if (this._restoreStateValues()) {
  19798. this.onRestoreStateObservable.notifyObservers(this);
  19799. return true;
  19800. }
  19801. return false;
  19802. };
  19803. Camera.prototype.getClassName = function () {
  19804. return "Camera";
  19805. };
  19806. /**
  19807. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19808. */
  19809. Camera.prototype.toString = function (fullDetails) {
  19810. var ret = "Name: " + this.name;
  19811. ret += ", type: " + this.getClassName();
  19812. if (this.animations) {
  19813. for (var i = 0; i < this.animations.length; i++) {
  19814. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19815. }
  19816. }
  19817. if (fullDetails) {
  19818. }
  19819. return ret;
  19820. };
  19821. Object.defineProperty(Camera.prototype, "globalPosition", {
  19822. get: function () {
  19823. return this._globalPosition;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Camera.prototype.getActiveMeshes = function () {
  19829. return this._activeMeshes;
  19830. };
  19831. Camera.prototype.isActiveMesh = function (mesh) {
  19832. return (this._activeMeshes.indexOf(mesh) !== -1);
  19833. };
  19834. //Cache
  19835. Camera.prototype._initCache = function () {
  19836. _super.prototype._initCache.call(this);
  19837. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19838. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19839. this._cache.mode = undefined;
  19840. this._cache.minZ = undefined;
  19841. this._cache.maxZ = undefined;
  19842. this._cache.fov = undefined;
  19843. this._cache.fovMode = undefined;
  19844. this._cache.aspectRatio = undefined;
  19845. this._cache.orthoLeft = undefined;
  19846. this._cache.orthoRight = undefined;
  19847. this._cache.orthoBottom = undefined;
  19848. this._cache.orthoTop = undefined;
  19849. this._cache.renderWidth = undefined;
  19850. this._cache.renderHeight = undefined;
  19851. };
  19852. Camera.prototype._updateCache = function (ignoreParentClass) {
  19853. if (!ignoreParentClass) {
  19854. _super.prototype._updateCache.call(this);
  19855. }
  19856. this._cache.position.copyFrom(this.position);
  19857. this._cache.upVector.copyFrom(this.upVector);
  19858. };
  19859. // Synchronized
  19860. Camera.prototype._isSynchronized = function () {
  19861. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19862. };
  19863. Camera.prototype._isSynchronizedViewMatrix = function () {
  19864. if (!_super.prototype._isSynchronized.call(this))
  19865. return false;
  19866. return this._cache.position.equals(this.position)
  19867. && this._cache.upVector.equals(this.upVector)
  19868. && this.isSynchronizedWithParent();
  19869. };
  19870. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19871. var check = this._cache.mode === this.mode
  19872. && this._cache.minZ === this.minZ
  19873. && this._cache.maxZ === this.maxZ;
  19874. if (!check) {
  19875. return false;
  19876. }
  19877. var engine = this.getEngine();
  19878. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19879. check = this._cache.fov === this.fov
  19880. && this._cache.fovMode === this.fovMode
  19881. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19882. }
  19883. else {
  19884. check = this._cache.orthoLeft === this.orthoLeft
  19885. && this._cache.orthoRight === this.orthoRight
  19886. && this._cache.orthoBottom === this.orthoBottom
  19887. && this._cache.orthoTop === this.orthoTop
  19888. && this._cache.renderWidth === engine.getRenderWidth()
  19889. && this._cache.renderHeight === engine.getRenderHeight();
  19890. }
  19891. return check;
  19892. };
  19893. // Controls
  19894. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19895. };
  19896. Camera.prototype.detachControl = function (element) {
  19897. };
  19898. Camera.prototype.update = function () {
  19899. this._checkInputs();
  19900. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19901. this._updateRigCameras();
  19902. }
  19903. };
  19904. Camera.prototype._checkInputs = function () {
  19905. this.onAfterCheckInputsObservable.notifyObservers(this);
  19906. };
  19907. Object.defineProperty(Camera.prototype, "rigCameras", {
  19908. get: function () {
  19909. return this._rigCameras;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19915. get: function () {
  19916. return this._rigPostProcess;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19922. // invalidate framebuffer
  19923. if (this._postProcesses.length > 0) {
  19924. this._postProcesses[0].markTextureDirty();
  19925. }
  19926. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19927. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19928. var cam = this._rigCameras[i];
  19929. var rigPostProcess = cam._rigPostProcess;
  19930. // for VR rig, there does not have to be a post process
  19931. if (rigPostProcess) {
  19932. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19933. if (isPass) {
  19934. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19935. cam.isIntermediate = this._postProcesses.length === 0;
  19936. }
  19937. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19938. rigPostProcess.markTextureDirty();
  19939. }
  19940. else {
  19941. cam._postProcesses = this._postProcesses.slice(0);
  19942. }
  19943. }
  19944. };
  19945. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19946. if (insertAt === void 0) { insertAt = null; }
  19947. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19948. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19949. return 0;
  19950. }
  19951. if (insertAt == null || insertAt < 0) {
  19952. this._postProcesses.push(postProcess);
  19953. }
  19954. else {
  19955. this._postProcesses.splice(insertAt, 0, postProcess);
  19956. }
  19957. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19958. return this._postProcesses.indexOf(postProcess);
  19959. };
  19960. Camera.prototype.detachPostProcess = function (postProcess) {
  19961. var idx = this._postProcesses.indexOf(postProcess);
  19962. if (idx !== -1) {
  19963. this._postProcesses.splice(idx, 1);
  19964. }
  19965. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19966. };
  19967. Camera.prototype.getWorldMatrix = function () {
  19968. if (!this._worldMatrix) {
  19969. this._worldMatrix = BABYLON.Matrix.Identity();
  19970. }
  19971. var viewMatrix = this.getViewMatrix();
  19972. viewMatrix.invertToRef(this._worldMatrix);
  19973. return this._worldMatrix;
  19974. };
  19975. Camera.prototype._getViewMatrix = function () {
  19976. return BABYLON.Matrix.Identity();
  19977. };
  19978. Camera.prototype.getViewMatrix = function (force) {
  19979. if (!force && this._isSynchronizedViewMatrix()) {
  19980. return this._computedViewMatrix;
  19981. }
  19982. this.updateCache();
  19983. this._computedViewMatrix = this._getViewMatrix();
  19984. this._currentRenderId = this.getScene().getRenderId();
  19985. this._refreshFrustumPlanes = true;
  19986. if (!this.parent || !this.parent.getWorldMatrix) {
  19987. this._globalPosition.copyFrom(this.position);
  19988. }
  19989. else {
  19990. if (!this._worldMatrix) {
  19991. this._worldMatrix = BABYLON.Matrix.Identity();
  19992. }
  19993. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19994. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19995. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19996. this._computedViewMatrix.invert();
  19997. this._markSyncedWithParent();
  19998. }
  19999. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20000. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20001. }
  20002. this.onViewMatrixChangedObservable.notifyObservers(this);
  20003. return this._computedViewMatrix;
  20004. };
  20005. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20006. this._doNotComputeProjectionMatrix = true;
  20007. if (projection !== undefined) {
  20008. this._projectionMatrix = projection;
  20009. }
  20010. };
  20011. ;
  20012. Camera.prototype.unfreezeProjectionMatrix = function () {
  20013. this._doNotComputeProjectionMatrix = false;
  20014. };
  20015. ;
  20016. Camera.prototype.getProjectionMatrix = function (force) {
  20017. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20018. return this._projectionMatrix;
  20019. }
  20020. // Cache
  20021. this._cache.mode = this.mode;
  20022. this._cache.minZ = this.minZ;
  20023. this._cache.maxZ = this.maxZ;
  20024. // Matrix
  20025. this._refreshFrustumPlanes = true;
  20026. var engine = this.getEngine();
  20027. var scene = this.getScene();
  20028. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20029. this._cache.fov = this.fov;
  20030. this._cache.fovMode = this.fovMode;
  20031. this._cache.aspectRatio = engine.getAspectRatio(this);
  20032. if (this.minZ <= 0) {
  20033. this.minZ = 0.1;
  20034. }
  20035. if (scene.useRightHandedSystem) {
  20036. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20037. }
  20038. else {
  20039. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20040. }
  20041. }
  20042. else {
  20043. var halfWidth = engine.getRenderWidth() / 2.0;
  20044. var halfHeight = engine.getRenderHeight() / 2.0;
  20045. if (scene.useRightHandedSystem) {
  20046. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20047. }
  20048. else {
  20049. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20050. }
  20051. this._cache.orthoLeft = this.orthoLeft;
  20052. this._cache.orthoRight = this.orthoRight;
  20053. this._cache.orthoBottom = this.orthoBottom;
  20054. this._cache.orthoTop = this.orthoTop;
  20055. this._cache.renderWidth = engine.getRenderWidth();
  20056. this._cache.renderHeight = engine.getRenderHeight();
  20057. }
  20058. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20059. return this._projectionMatrix;
  20060. };
  20061. Camera.prototype.getTranformationMatrix = function () {
  20062. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20063. return this._transformMatrix;
  20064. };
  20065. Camera.prototype.updateFrustumPlanes = function () {
  20066. if (!this._refreshFrustumPlanes) {
  20067. return;
  20068. }
  20069. this.getTranformationMatrix();
  20070. if (!this._frustumPlanes) {
  20071. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20072. }
  20073. else {
  20074. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20075. }
  20076. this._refreshFrustumPlanes = false;
  20077. };
  20078. Camera.prototype.isInFrustum = function (target) {
  20079. this.updateFrustumPlanes();
  20080. return target.isInFrustum(this._frustumPlanes);
  20081. };
  20082. Camera.prototype.isCompletelyInFrustum = function (target) {
  20083. this.updateFrustumPlanes();
  20084. return target.isCompletelyInFrustum(this._frustumPlanes);
  20085. };
  20086. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20087. if (length === void 0) { length = 100; }
  20088. if (!transform) {
  20089. transform = this.getWorldMatrix();
  20090. }
  20091. if (!origin) {
  20092. origin = this.position;
  20093. }
  20094. var forward = new BABYLON.Vector3(0, 0, 1);
  20095. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20096. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20097. return new BABYLON.Ray(origin, direction, length);
  20098. };
  20099. Camera.prototype.dispose = function () {
  20100. // Observables
  20101. this.onViewMatrixChangedObservable.clear();
  20102. this.onProjectionMatrixChangedObservable.clear();
  20103. this.onAfterCheckInputsObservable.clear();
  20104. this.onRestoreStateObservable.clear();
  20105. // Inputs
  20106. if (this.inputs) {
  20107. this.inputs.clear();
  20108. }
  20109. // Animations
  20110. this.getScene().stopAnimation(this);
  20111. // Remove from scene
  20112. this.getScene().removeCamera(this);
  20113. while (this._rigCameras.length > 0) {
  20114. var camera = this._rigCameras.pop();
  20115. if (camera) {
  20116. camera.dispose();
  20117. }
  20118. }
  20119. // Postprocesses
  20120. if (this._rigPostProcess) {
  20121. this._rigPostProcess.dispose(this);
  20122. this._rigPostProcess = null;
  20123. this._postProcesses = [];
  20124. }
  20125. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20126. this._rigPostProcess = null;
  20127. this._postProcesses = [];
  20128. }
  20129. else {
  20130. var i = this._postProcesses.length;
  20131. while (--i >= 0) {
  20132. this._postProcesses[i].dispose(this);
  20133. }
  20134. }
  20135. // Render targets
  20136. var i = this.customRenderTargets.length;
  20137. while (--i >= 0) {
  20138. this.customRenderTargets[i].dispose();
  20139. }
  20140. this.customRenderTargets = [];
  20141. // Active Meshes
  20142. this._activeMeshes.dispose();
  20143. _super.prototype.dispose.call(this);
  20144. };
  20145. Object.defineProperty(Camera.prototype, "leftCamera", {
  20146. // ---- Camera rigs section ----
  20147. get: function () {
  20148. if (this._rigCameras.length < 1) {
  20149. return null;
  20150. }
  20151. return this._rigCameras[0];
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. Object.defineProperty(Camera.prototype, "rightCamera", {
  20157. get: function () {
  20158. if (this._rigCameras.length < 2) {
  20159. return null;
  20160. }
  20161. return this._rigCameras[1];
  20162. },
  20163. enumerable: true,
  20164. configurable: true
  20165. });
  20166. Camera.prototype.getLeftTarget = function () {
  20167. if (this._rigCameras.length < 1) {
  20168. return null;
  20169. }
  20170. return this._rigCameras[0].getTarget();
  20171. };
  20172. Camera.prototype.getRightTarget = function () {
  20173. if (this._rigCameras.length < 2) {
  20174. return null;
  20175. }
  20176. return this._rigCameras[1].getTarget();
  20177. };
  20178. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20179. if (this.cameraRigMode === mode) {
  20180. return;
  20181. }
  20182. while (this._rigCameras.length > 0) {
  20183. var camera = this._rigCameras.pop();
  20184. if (camera) {
  20185. camera.dispose();
  20186. }
  20187. }
  20188. this.cameraRigMode = mode;
  20189. this._cameraRigParams = {};
  20190. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20191. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20192. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20193. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20194. // create the rig cameras, unless none
  20195. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20196. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20197. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20198. if (leftCamera && rightCamera) {
  20199. this._rigCameras.push(leftCamera);
  20200. this._rigCameras.push(rightCamera);
  20201. }
  20202. }
  20203. switch (this.cameraRigMode) {
  20204. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20205. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20206. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20207. break;
  20208. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20209. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20210. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20211. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20212. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20213. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20214. break;
  20215. case Camera.RIG_MODE_VR:
  20216. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20217. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20218. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20219. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20220. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20221. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20222. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20223. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20224. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20225. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20226. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20227. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20228. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20229. if (metrics.compensateDistortion) {
  20230. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20231. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20232. }
  20233. break;
  20234. case Camera.RIG_MODE_WEBVR:
  20235. if (rigParams.vrDisplay) {
  20236. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20237. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20238. //Left eye
  20239. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20240. this._rigCameras[0].setCameraRigParameter("left", true);
  20241. //leaving this for future reference
  20242. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20243. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20244. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20245. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20247. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20248. this._rigCameras[0].parent = this;
  20249. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20250. //Right eye
  20251. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20252. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20253. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20254. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20255. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20256. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20257. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20258. this._rigCameras[1].parent = this;
  20259. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20260. if (Camera.UseAlternateWebVRRendering) {
  20261. this._rigCameras[1]._skipRendering = true;
  20262. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20263. }
  20264. }
  20265. break;
  20266. }
  20267. this._cascadePostProcessesToRigCams();
  20268. this.update();
  20269. };
  20270. Camera.prototype._getVRProjectionMatrix = function () {
  20271. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20272. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20273. return this._projectionMatrix;
  20274. };
  20275. Camera.prototype._updateCameraRotationMatrix = function () {
  20276. //Here for WebVR
  20277. };
  20278. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20279. //Here for WebVR
  20280. };
  20281. /**
  20282. * This function MUST be overwritten by the different WebVR cameras available.
  20283. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20284. */
  20285. Camera.prototype._getWebVRProjectionMatrix = function () {
  20286. return BABYLON.Matrix.Identity();
  20287. };
  20288. /**
  20289. * This function MUST be overwritten by the different WebVR cameras available.
  20290. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20291. */
  20292. Camera.prototype._getWebVRViewMatrix = function () {
  20293. return BABYLON.Matrix.Identity();
  20294. };
  20295. Camera.prototype.setCameraRigParameter = function (name, value) {
  20296. if (!this._cameraRigParams) {
  20297. this._cameraRigParams = {};
  20298. }
  20299. this._cameraRigParams[name] = value;
  20300. //provisionnally:
  20301. if (name === "interaxialDistance") {
  20302. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20303. }
  20304. };
  20305. /**
  20306. * needs to be overridden by children so sub has required properties to be copied
  20307. */
  20308. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20309. return null;
  20310. };
  20311. /**
  20312. * May need to be overridden by children
  20313. */
  20314. Camera.prototype._updateRigCameras = function () {
  20315. for (var i = 0; i < this._rigCameras.length; i++) {
  20316. this._rigCameras[i].minZ = this.minZ;
  20317. this._rigCameras[i].maxZ = this.maxZ;
  20318. this._rigCameras[i].fov = this.fov;
  20319. }
  20320. // only update viewport when ANAGLYPH
  20321. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20322. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20323. }
  20324. };
  20325. Camera.prototype._setupInputs = function () {
  20326. };
  20327. Camera.prototype.serialize = function () {
  20328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20329. // Type
  20330. serializationObject.type = this.getClassName();
  20331. // Parent
  20332. if (this.parent) {
  20333. serializationObject.parentId = this.parent.id;
  20334. }
  20335. if (this.inputs) {
  20336. this.inputs.serialize(serializationObject);
  20337. }
  20338. // Animations
  20339. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20340. serializationObject.ranges = this.serializeAnimationRanges();
  20341. return serializationObject;
  20342. };
  20343. Camera.prototype.clone = function (name) {
  20344. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20345. };
  20346. Camera.prototype.getDirection = function (localAxis) {
  20347. var result = BABYLON.Vector3.Zero();
  20348. this.getDirectionToRef(localAxis, result);
  20349. return result;
  20350. };
  20351. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20352. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20353. };
  20354. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20355. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20356. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20357. switch (type) {
  20358. case "ArcRotateCamera":
  20359. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20360. case "DeviceOrientationCamera":
  20361. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20362. case "FollowCamera":
  20363. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20364. case "ArcFollowCamera":
  20365. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20366. case "GamepadCamera":
  20367. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20368. case "TouchCamera":
  20369. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20370. case "VirtualJoysticksCamera":
  20371. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20372. case "WebVRFreeCamera":
  20373. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20374. case "WebVRGamepadCamera":
  20375. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20376. case "VRDeviceOrientationFreeCamera":
  20377. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20378. case "VRDeviceOrientationGamepadCamera":
  20379. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20380. case "AnaglyphArcRotateCamera":
  20381. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20382. case "AnaglyphFreeCamera":
  20383. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20384. case "AnaglyphGamepadCamera":
  20385. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20386. case "AnaglyphUniversalCamera":
  20387. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20388. case "StereoscopicArcRotateCamera":
  20389. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20390. case "StereoscopicFreeCamera":
  20391. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20392. case "StereoscopicGamepadCamera":
  20393. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20394. case "StereoscopicUniversalCamera":
  20395. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20396. case "FreeCamera":// Forcing Universal here
  20397. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20398. default:// Universal Camera is the default value
  20399. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20400. }
  20401. };
  20402. Camera.prototype.computeWorldMatrix = function () {
  20403. return this.getWorldMatrix();
  20404. };
  20405. Camera.Parse = function (parsedCamera, scene) {
  20406. var type = parsedCamera.type;
  20407. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20408. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20409. // Parent
  20410. if (parsedCamera.parentId) {
  20411. camera._waitingParentId = parsedCamera.parentId;
  20412. }
  20413. //If camera has an input manager, let it parse inputs settings
  20414. if (camera.inputs) {
  20415. camera.inputs.parse(parsedCamera);
  20416. camera._setupInputs();
  20417. }
  20418. if (camera.setPosition) {
  20419. camera.position.copyFromFloats(0, 0, 0);
  20420. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20421. }
  20422. // Target
  20423. if (parsedCamera.target) {
  20424. if (camera.setTarget) {
  20425. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20426. }
  20427. }
  20428. // Apply 3d rig, when found
  20429. if (parsedCamera.cameraRigMode) {
  20430. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20431. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20432. }
  20433. // Animations
  20434. if (parsedCamera.animations) {
  20435. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20436. var parsedAnimation = parsedCamera.animations[animationIndex];
  20437. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20438. }
  20439. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20440. }
  20441. if (parsedCamera.autoAnimate) {
  20442. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20443. }
  20444. return camera;
  20445. };
  20446. // Statics
  20447. Camera._PERSPECTIVE_CAMERA = 0;
  20448. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20449. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20450. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20451. Camera._RIG_MODE_NONE = 0;
  20452. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20453. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20454. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20455. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20456. Camera._RIG_MODE_VR = 20;
  20457. Camera._RIG_MODE_WEBVR = 21;
  20458. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20459. Camera.UseAlternateWebVRRendering = false;
  20460. __decorate([
  20461. BABYLON.serializeAsVector3()
  20462. ], Camera.prototype, "position", void 0);
  20463. __decorate([
  20464. BABYLON.serializeAsVector3()
  20465. ], Camera.prototype, "upVector", void 0);
  20466. __decorate([
  20467. BABYLON.serialize()
  20468. ], Camera.prototype, "orthoLeft", void 0);
  20469. __decorate([
  20470. BABYLON.serialize()
  20471. ], Camera.prototype, "orthoRight", void 0);
  20472. __decorate([
  20473. BABYLON.serialize()
  20474. ], Camera.prototype, "orthoBottom", void 0);
  20475. __decorate([
  20476. BABYLON.serialize()
  20477. ], Camera.prototype, "orthoTop", void 0);
  20478. __decorate([
  20479. BABYLON.serialize()
  20480. ], Camera.prototype, "fov", void 0);
  20481. __decorate([
  20482. BABYLON.serialize()
  20483. ], Camera.prototype, "minZ", void 0);
  20484. __decorate([
  20485. BABYLON.serialize()
  20486. ], Camera.prototype, "maxZ", void 0);
  20487. __decorate([
  20488. BABYLON.serialize()
  20489. ], Camera.prototype, "inertia", void 0);
  20490. __decorate([
  20491. BABYLON.serialize()
  20492. ], Camera.prototype, "mode", void 0);
  20493. __decorate([
  20494. BABYLON.serialize()
  20495. ], Camera.prototype, "layerMask", void 0);
  20496. __decorate([
  20497. BABYLON.serialize()
  20498. ], Camera.prototype, "fovMode", void 0);
  20499. __decorate([
  20500. BABYLON.serialize()
  20501. ], Camera.prototype, "cameraRigMode", void 0);
  20502. __decorate([
  20503. BABYLON.serialize()
  20504. ], Camera.prototype, "interaxialDistance", void 0);
  20505. __decorate([
  20506. BABYLON.serialize()
  20507. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20508. return Camera;
  20509. }(BABYLON.Node));
  20510. BABYLON.Camera = Camera;
  20511. })(BABYLON || (BABYLON = {}));
  20512. //# sourceMappingURL=babylon.camera.js.map
  20513. var BABYLON;
  20514. (function (BABYLON) {
  20515. var RenderingManager = /** @class */ (function () {
  20516. function RenderingManager(scene) {
  20517. this._renderingGroups = new Array();
  20518. this._autoClearDepthStencil = {};
  20519. this._customOpaqueSortCompareFn = {};
  20520. this._customAlphaTestSortCompareFn = {};
  20521. this._customTransparentSortCompareFn = {};
  20522. this._renderinGroupInfo = null;
  20523. this._scene = scene;
  20524. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20525. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20526. }
  20527. }
  20528. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20529. if (depth === void 0) { depth = true; }
  20530. if (stencil === void 0) { stencil = true; }
  20531. if (this._depthStencilBufferAlreadyCleaned) {
  20532. return;
  20533. }
  20534. this._scene.getEngine().clear(null, false, depth, stencil);
  20535. this._depthStencilBufferAlreadyCleaned = true;
  20536. };
  20537. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20538. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20539. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20540. var info = null;
  20541. if (observable) {
  20542. if (!this._renderinGroupInfo) {
  20543. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20544. }
  20545. info = this._renderinGroupInfo;
  20546. info.scene = this._scene;
  20547. info.camera = this._scene.activeCamera;
  20548. }
  20549. // Dispatch sprites
  20550. if (renderSprites) {
  20551. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20552. var manager = this._scene.spriteManagers[index];
  20553. this.dispatchSprites(manager);
  20554. }
  20555. }
  20556. // Render
  20557. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20558. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20559. var renderingGroup = this._renderingGroups[index];
  20560. if (!renderingGroup && !observable)
  20561. continue;
  20562. var renderingGroupMask = 0;
  20563. // Fire PRECLEAR stage
  20564. if (observable && info) {
  20565. renderingGroupMask = Math.pow(2, index);
  20566. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20567. info.renderingGroupId = index;
  20568. observable.notifyObservers(info, renderingGroupMask);
  20569. }
  20570. // Clear depth/stencil if needed
  20571. if (RenderingManager.AUTOCLEAR) {
  20572. var autoClear = this._autoClearDepthStencil[index];
  20573. if (autoClear && autoClear.autoClear) {
  20574. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20575. }
  20576. }
  20577. if (observable && info) {
  20578. // Fire PREOPAQUE stage
  20579. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20580. observable.notifyObservers(info, renderingGroupMask);
  20581. // Fire PRETRANSPARENT stage
  20582. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20583. observable.notifyObservers(info, renderingGroupMask);
  20584. }
  20585. if (renderingGroup)
  20586. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20587. // Fire POSTTRANSPARENT stage
  20588. if (observable && info) {
  20589. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20590. observable.notifyObservers(info, renderingGroupMask);
  20591. }
  20592. }
  20593. };
  20594. RenderingManager.prototype.reset = function () {
  20595. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20596. var renderingGroup = this._renderingGroups[index];
  20597. if (renderingGroup) {
  20598. renderingGroup.prepare();
  20599. }
  20600. }
  20601. };
  20602. RenderingManager.prototype.dispose = function () {
  20603. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20604. var renderingGroup = this._renderingGroups[index];
  20605. if (renderingGroup) {
  20606. renderingGroup.dispose();
  20607. }
  20608. }
  20609. this._renderingGroups.length = 0;
  20610. };
  20611. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20612. if (this._renderingGroups[renderingGroupId] === undefined) {
  20613. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20614. }
  20615. };
  20616. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20617. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20618. this._prepareRenderingGroup(renderingGroupId);
  20619. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20620. };
  20621. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20622. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20623. this._prepareRenderingGroup(renderingGroupId);
  20624. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20625. };
  20626. /**
  20627. * @param subMesh The submesh to dispatch
  20628. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20629. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20630. */
  20631. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20632. if (mesh === undefined) {
  20633. mesh = subMesh.getMesh();
  20634. }
  20635. var renderingGroupId = mesh.renderingGroupId || 0;
  20636. this._prepareRenderingGroup(renderingGroupId);
  20637. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20638. };
  20639. /**
  20640. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20641. * This allowed control for front to back rendering or reversly depending of the special needs.
  20642. *
  20643. * @param renderingGroupId The rendering group id corresponding to its index
  20644. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20645. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20646. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20647. */
  20648. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20649. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20650. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20651. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20652. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20653. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20654. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20655. if (this._renderingGroups[renderingGroupId]) {
  20656. var group = this._renderingGroups[renderingGroupId];
  20657. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20658. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20659. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20660. }
  20661. };
  20662. /**
  20663. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20664. *
  20665. * @param renderingGroupId The rendering group id corresponding to its index
  20666. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20667. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20668. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20669. */
  20670. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20671. if (depth === void 0) { depth = true; }
  20672. if (stencil === void 0) { stencil = true; }
  20673. this._autoClearDepthStencil[renderingGroupId] = {
  20674. autoClear: autoClearDepthStencil,
  20675. depth: depth,
  20676. stencil: stencil
  20677. };
  20678. };
  20679. /**
  20680. * The max id used for rendering groups (not included)
  20681. */
  20682. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20683. /**
  20684. * The min id used for rendering groups (included)
  20685. */
  20686. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20687. /**
  20688. * Used to globally prevent autoclearing scenes.
  20689. */
  20690. RenderingManager.AUTOCLEAR = true;
  20691. return RenderingManager;
  20692. }());
  20693. BABYLON.RenderingManager = RenderingManager;
  20694. })(BABYLON || (BABYLON = {}));
  20695. //# sourceMappingURL=babylon.renderingManager.js.map
  20696. var BABYLON;
  20697. (function (BABYLON) {
  20698. var RenderingGroup = /** @class */ (function () {
  20699. /**
  20700. * Creates a new rendering group.
  20701. * @param index The rendering group index
  20702. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20703. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20704. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20705. */
  20706. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20707. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20708. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20709. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20710. this.index = index;
  20711. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20712. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20713. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20714. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20715. this._particleSystems = new BABYLON.SmartArray(256);
  20716. this._spriteManagers = new BABYLON.SmartArray(256);
  20717. this._edgesRenderers = new BABYLON.SmartArray(16);
  20718. this._scene = scene;
  20719. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20720. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20721. this.transparentSortCompareFn = transparentSortCompareFn;
  20722. }
  20723. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20724. /**
  20725. * Set the opaque sort comparison function.
  20726. * If null the sub meshes will be render in the order they were created
  20727. */
  20728. set: function (value) {
  20729. this._opaqueSortCompareFn = value;
  20730. if (value) {
  20731. this._renderOpaque = this.renderOpaqueSorted;
  20732. }
  20733. else {
  20734. this._renderOpaque = RenderingGroup.renderUnsorted;
  20735. }
  20736. },
  20737. enumerable: true,
  20738. configurable: true
  20739. });
  20740. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20741. /**
  20742. * Set the alpha test sort comparison function.
  20743. * If null the sub meshes will be render in the order they were created
  20744. */
  20745. set: function (value) {
  20746. this._alphaTestSortCompareFn = value;
  20747. if (value) {
  20748. this._renderAlphaTest = this.renderAlphaTestSorted;
  20749. }
  20750. else {
  20751. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20752. }
  20753. },
  20754. enumerable: true,
  20755. configurable: true
  20756. });
  20757. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20758. /**
  20759. * Set the transparent sort comparison function.
  20760. * If null the sub meshes will be render in the order they were created
  20761. */
  20762. set: function (value) {
  20763. if (value) {
  20764. this._transparentSortCompareFn = value;
  20765. }
  20766. else {
  20767. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20768. }
  20769. this._renderTransparent = this.renderTransparentSorted;
  20770. },
  20771. enumerable: true,
  20772. configurable: true
  20773. });
  20774. /**
  20775. * Render all the sub meshes contained in the group.
  20776. * @param customRenderFunction Used to override the default render behaviour of the group.
  20777. * @returns true if rendered some submeshes.
  20778. */
  20779. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20780. if (customRenderFunction) {
  20781. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20782. return;
  20783. }
  20784. var engine = this._scene.getEngine();
  20785. // Depth only
  20786. if (this._depthOnlySubMeshes.length !== 0) {
  20787. engine.setColorWrite(false);
  20788. this._renderAlphaTest(this._depthOnlySubMeshes);
  20789. engine.setColorWrite(true);
  20790. }
  20791. // Opaque
  20792. if (this._opaqueSubMeshes.length !== 0) {
  20793. this._renderOpaque(this._opaqueSubMeshes);
  20794. }
  20795. // Alpha test
  20796. if (this._alphaTestSubMeshes.length !== 0) {
  20797. this._renderAlphaTest(this._alphaTestSubMeshes);
  20798. }
  20799. var stencilState = engine.getStencilBuffer();
  20800. engine.setStencilBuffer(false);
  20801. // Sprites
  20802. if (renderSprites) {
  20803. this._renderSprites();
  20804. }
  20805. // Particles
  20806. if (renderParticles) {
  20807. this._renderParticles(activeMeshes);
  20808. }
  20809. if (this.onBeforeTransparentRendering) {
  20810. this.onBeforeTransparentRendering();
  20811. }
  20812. // Transparent
  20813. if (this._transparentSubMeshes.length !== 0) {
  20814. this._renderTransparent(this._transparentSubMeshes);
  20815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20816. }
  20817. // Set back stencil to false in case it changes before the edge renderer.
  20818. engine.setStencilBuffer(false);
  20819. // Edges
  20820. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20821. this._edgesRenderers.data[edgesRendererIndex].render();
  20822. }
  20823. // Restore Stencil state.
  20824. engine.setStencilBuffer(stencilState);
  20825. };
  20826. /**
  20827. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20828. * @param subMeshes The submeshes to render
  20829. */
  20830. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20831. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20832. };
  20833. /**
  20834. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20835. * @param subMeshes The submeshes to render
  20836. */
  20837. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20838. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20839. };
  20840. /**
  20841. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20842. * @param subMeshes The submeshes to render
  20843. */
  20844. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20845. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20846. };
  20847. /**
  20848. * Renders the submeshes in a specified order.
  20849. * @param subMeshes The submeshes to sort before render
  20850. * @param sortCompareFn The comparison function use to sort
  20851. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20852. * @param transparent Specifies to activate blending if true
  20853. */
  20854. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20855. var subIndex = 0;
  20856. var subMesh;
  20857. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20858. for (; subIndex < subMeshes.length; subIndex++) {
  20859. subMesh = subMeshes.data[subIndex];
  20860. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20861. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20862. }
  20863. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20864. if (sortCompareFn) {
  20865. sortedArray.sort(sortCompareFn);
  20866. }
  20867. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20868. subMesh = sortedArray[subIndex];
  20869. if (transparent) {
  20870. var material = subMesh.getMaterial();
  20871. if (material && material.needDepthPrePass) {
  20872. var engine = material.getScene().getEngine();
  20873. engine.setColorWrite(false);
  20874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20875. subMesh.render(false);
  20876. engine.setColorWrite(true);
  20877. }
  20878. }
  20879. subMesh.render(transparent);
  20880. }
  20881. };
  20882. /**
  20883. * Renders the submeshes in the order they were dispatched (no sort applied).
  20884. * @param subMeshes The submeshes to render
  20885. */
  20886. RenderingGroup.renderUnsorted = function (subMeshes) {
  20887. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20888. var submesh = subMeshes.data[subIndex];
  20889. submesh.render(false);
  20890. }
  20891. };
  20892. /**
  20893. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20894. * are rendered back to front if in the same alpha index.
  20895. *
  20896. * @param a The first submesh
  20897. * @param b The second submesh
  20898. * @returns The result of the comparison
  20899. */
  20900. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20901. // Alpha index first
  20902. if (a._alphaIndex > b._alphaIndex) {
  20903. return 1;
  20904. }
  20905. if (a._alphaIndex < b._alphaIndex) {
  20906. return -1;
  20907. }
  20908. // Then distance to camera
  20909. return RenderingGroup.backToFrontSortCompare(a, b);
  20910. };
  20911. /**
  20912. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20913. * are rendered back to front.
  20914. *
  20915. * @param a The first submesh
  20916. * @param b The second submesh
  20917. * @returns The result of the comparison
  20918. */
  20919. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20920. // Then distance to camera
  20921. if (a._distanceToCamera < b._distanceToCamera) {
  20922. return 1;
  20923. }
  20924. if (a._distanceToCamera > b._distanceToCamera) {
  20925. return -1;
  20926. }
  20927. return 0;
  20928. };
  20929. /**
  20930. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20931. * are rendered front to back (prevent overdraw).
  20932. *
  20933. * @param a The first submesh
  20934. * @param b The second submesh
  20935. * @returns The result of the comparison
  20936. */
  20937. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20938. // Then distance to camera
  20939. if (a._distanceToCamera < b._distanceToCamera) {
  20940. return -1;
  20941. }
  20942. if (a._distanceToCamera > b._distanceToCamera) {
  20943. return 1;
  20944. }
  20945. return 0;
  20946. };
  20947. /**
  20948. * Resets the different lists of submeshes to prepare a new frame.
  20949. */
  20950. RenderingGroup.prototype.prepare = function () {
  20951. this._opaqueSubMeshes.reset();
  20952. this._transparentSubMeshes.reset();
  20953. this._alphaTestSubMeshes.reset();
  20954. this._depthOnlySubMeshes.reset();
  20955. this._particleSystems.reset();
  20956. this._spriteManagers.reset();
  20957. this._edgesRenderers.reset();
  20958. };
  20959. RenderingGroup.prototype.dispose = function () {
  20960. this._opaqueSubMeshes.dispose();
  20961. this._transparentSubMeshes.dispose();
  20962. this._alphaTestSubMeshes.dispose();
  20963. this._depthOnlySubMeshes.dispose();
  20964. this._particleSystems.dispose();
  20965. this._spriteManagers.dispose();
  20966. this._edgesRenderers.dispose();
  20967. };
  20968. /**
  20969. * Inserts the submesh in its correct queue depending on its material.
  20970. * @param subMesh The submesh to dispatch
  20971. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20972. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20973. */
  20974. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20975. // Get mesh and materials if not provided
  20976. if (mesh === undefined) {
  20977. mesh = subMesh.getMesh();
  20978. }
  20979. if (material === undefined) {
  20980. material = subMesh.getMaterial();
  20981. }
  20982. if (material === null || material === undefined) {
  20983. return;
  20984. }
  20985. if (material.needAlphaBlendingForMesh(mesh)) {
  20986. this._transparentSubMeshes.push(subMesh);
  20987. }
  20988. else if (material.needAlphaTesting()) {
  20989. if (material.needDepthPrePass) {
  20990. this._depthOnlySubMeshes.push(subMesh);
  20991. }
  20992. this._alphaTestSubMeshes.push(subMesh);
  20993. }
  20994. else {
  20995. if (material.needDepthPrePass) {
  20996. this._depthOnlySubMeshes.push(subMesh);
  20997. }
  20998. this._opaqueSubMeshes.push(subMesh); // Opaque
  20999. }
  21000. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21001. this._edgesRenderers.push(mesh._edgesRenderer);
  21002. }
  21003. };
  21004. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21005. this._spriteManagers.push(spriteManager);
  21006. };
  21007. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21008. this._particleSystems.push(particleSystem);
  21009. };
  21010. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21011. if (this._particleSystems.length === 0) {
  21012. return;
  21013. }
  21014. // Particles
  21015. var activeCamera = this._scene.activeCamera;
  21016. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21017. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21018. var particleSystem = this._particleSystems.data[particleIndex];
  21019. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21020. continue;
  21021. }
  21022. var emitter = particleSystem.emitter;
  21023. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21024. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21025. }
  21026. }
  21027. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21028. };
  21029. RenderingGroup.prototype._renderSprites = function () {
  21030. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21031. return;
  21032. }
  21033. // Sprites
  21034. var activeCamera = this._scene.activeCamera;
  21035. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21036. for (var id = 0; id < this._spriteManagers.length; id++) {
  21037. var spriteManager = this._spriteManagers.data[id];
  21038. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21039. spriteManager.render();
  21040. }
  21041. }
  21042. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21043. };
  21044. return RenderingGroup;
  21045. }());
  21046. BABYLON.RenderingGroup = RenderingGroup;
  21047. })(BABYLON || (BABYLON = {}));
  21048. //# sourceMappingURL=babylon.renderingGroup.js.map
  21049. var BABYLON;
  21050. (function (BABYLON) {
  21051. var ClickInfo = /** @class */ (function () {
  21052. function ClickInfo() {
  21053. this._singleClick = false;
  21054. this._doubleClick = false;
  21055. this._hasSwiped = false;
  21056. this._ignore = false;
  21057. }
  21058. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21059. get: function () {
  21060. return this._singleClick;
  21061. },
  21062. set: function (b) {
  21063. this._singleClick = b;
  21064. },
  21065. enumerable: true,
  21066. configurable: true
  21067. });
  21068. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21069. get: function () {
  21070. return this._doubleClick;
  21071. },
  21072. set: function (b) {
  21073. this._doubleClick = b;
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21079. get: function () {
  21080. return this._hasSwiped;
  21081. },
  21082. set: function (b) {
  21083. this._hasSwiped = b;
  21084. },
  21085. enumerable: true,
  21086. configurable: true
  21087. });
  21088. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21089. get: function () {
  21090. return this._ignore;
  21091. },
  21092. set: function (b) {
  21093. this._ignore = b;
  21094. },
  21095. enumerable: true,
  21096. configurable: true
  21097. });
  21098. return ClickInfo;
  21099. }());
  21100. /**
  21101. * This class is used by the onRenderingGroupObservable
  21102. */
  21103. var RenderingGroupInfo = /** @class */ (function () {
  21104. function RenderingGroupInfo() {
  21105. }
  21106. /**
  21107. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21108. * This stage will be fired no matter what
  21109. */
  21110. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21111. /**
  21112. * Called before opaque object are rendered.
  21113. * This stage will be fired only if there's 3D Opaque content to render
  21114. */
  21115. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21116. /**
  21117. * Called after the opaque objects are rendered and before the transparent ones
  21118. * This stage will be fired only if there's 3D transparent content to render
  21119. */
  21120. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21121. /**
  21122. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21123. * This stage will be fired no matter what
  21124. */
  21125. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21126. return RenderingGroupInfo;
  21127. }());
  21128. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21129. /**
  21130. * Represents a scene to be rendered by the engine.
  21131. * @see http://doc.babylonjs.com/page.php?p=21911
  21132. */
  21133. var Scene = /** @class */ (function () {
  21134. /**
  21135. * @constructor
  21136. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21137. */
  21138. function Scene(engine) {
  21139. // Members
  21140. this.autoClear = true;
  21141. this.autoClearDepthAndStencil = true;
  21142. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21143. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21144. this.forceWireframe = false;
  21145. this._forcePointsCloud = false;
  21146. this.forceShowBoundingBoxes = false;
  21147. this.animationsEnabled = true;
  21148. this.useConstantAnimationDeltaTime = false;
  21149. this.constantlyUpdateMeshUnderPointer = false;
  21150. this.hoverCursor = "pointer";
  21151. this.defaultCursor = "";
  21152. /**
  21153. * This is used to call preventDefault() on pointer down
  21154. * in order to block unwanted artifacts like system double clicks
  21155. */
  21156. this.preventDefaultOnPointerDown = true;
  21157. // Metadata
  21158. this.metadata = null;
  21159. /**
  21160. * An event triggered when the scene is disposed.
  21161. * @type {BABYLON.Observable}
  21162. */
  21163. this.onDisposeObservable = new BABYLON.Observable();
  21164. /**
  21165. * An event triggered before rendering the scene (right after animations and physics)
  21166. * @type {BABYLON.Observable}
  21167. */
  21168. this.onBeforeRenderObservable = new BABYLON.Observable();
  21169. /**
  21170. * An event triggered after rendering the scene
  21171. * @type {BABYLON.Observable}
  21172. */
  21173. this.onAfterRenderObservable = new BABYLON.Observable();
  21174. /**
  21175. * An event triggered before animating the scene
  21176. * @type {BABYLON.Observable}
  21177. */
  21178. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21179. /**
  21180. * An event triggered after animations processing
  21181. * @type {BABYLON.Observable}
  21182. */
  21183. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21184. /**
  21185. * An event triggered before draw calls are ready to be sent
  21186. * @type {BABYLON.Observable}
  21187. */
  21188. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21189. /**
  21190. * An event triggered after draw calls have been sent
  21191. * @type {BABYLON.Observable}
  21192. */
  21193. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21194. /**
  21195. * An event triggered when physic simulation is about to be run
  21196. * @type {BABYLON.Observable}
  21197. */
  21198. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21199. /**
  21200. * An event triggered when physic simulation has been done
  21201. * @type {BABYLON.Observable}
  21202. */
  21203. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21204. /**
  21205. * An event triggered when the scene is ready
  21206. * @type {BABYLON.Observable}
  21207. */
  21208. this.onReadyObservable = new BABYLON.Observable();
  21209. /**
  21210. * An event triggered before rendering a camera
  21211. * @type {BABYLON.Observable}
  21212. */
  21213. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21214. /**
  21215. * An event triggered after rendering a camera
  21216. * @type {BABYLON.Observable}
  21217. */
  21218. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21219. /**
  21220. * An event triggered when active meshes evaluation is about to start
  21221. * @type {BABYLON.Observable}
  21222. */
  21223. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21224. /**
  21225. * An event triggered when active meshes evaluation is done
  21226. * @type {BABYLON.Observable}
  21227. */
  21228. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21229. /**
  21230. * An event triggered when particles rendering is about to start
  21231. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21232. * @type {BABYLON.Observable}
  21233. */
  21234. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21235. /**
  21236. * An event triggered when particles rendering is done
  21237. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21238. * @type {BABYLON.Observable}
  21239. */
  21240. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21241. /**
  21242. * An event triggered when sprites rendering is about to start
  21243. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21244. * @type {BABYLON.Observable}
  21245. */
  21246. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21247. /**
  21248. * An event triggered when sprites rendering is done
  21249. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21250. * @type {BABYLON.Observable}
  21251. */
  21252. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21253. /**
  21254. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21255. * @type {BABYLON.Observable}
  21256. */
  21257. this.onDataLoadedObservable = new BABYLON.Observable();
  21258. /**
  21259. * An event triggered when a camera is created
  21260. * @type {BABYLON.Observable}
  21261. */
  21262. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21263. /**
  21264. * An event triggered when a camera is removed
  21265. * @type {BABYLON.Observable}
  21266. */
  21267. this.onCameraRemovedObservable = new BABYLON.Observable();
  21268. /**
  21269. * An event triggered when a light is created
  21270. * @type {BABYLON.Observable}
  21271. */
  21272. this.onNewLightAddedObservable = new BABYLON.Observable();
  21273. /**
  21274. * An event triggered when a light is removed
  21275. * @type {BABYLON.Observable}
  21276. */
  21277. this.onLightRemovedObservable = new BABYLON.Observable();
  21278. /**
  21279. * An event triggered when a geometry is created
  21280. * @type {BABYLON.Observable}
  21281. */
  21282. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21283. /**
  21284. * An event triggered when a geometry is removed
  21285. * @type {BABYLON.Observable}
  21286. */
  21287. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21288. /**
  21289. * An event triggered when a transform node is created
  21290. * @type {BABYLON.Observable}
  21291. */
  21292. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21293. /**
  21294. * An event triggered when a transform node is removed
  21295. * @type {BABYLON.Observable}
  21296. */
  21297. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21298. /**
  21299. * An event triggered when a mesh is created
  21300. * @type {BABYLON.Observable}
  21301. */
  21302. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21303. /**
  21304. * An event triggered when a mesh is removed
  21305. * @type {BABYLON.Observable}
  21306. */
  21307. this.onMeshRemovedObservable = new BABYLON.Observable();
  21308. /**
  21309. * An event triggered when render targets are about to be rendered
  21310. * Can happen multiple times per frame.
  21311. * @type {BABYLON.Observable}
  21312. */
  21313. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21314. /**
  21315. * An event triggered when render targets were rendered.
  21316. * Can happen multiple times per frame.
  21317. * @type {BABYLON.Observable}
  21318. */
  21319. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21320. /**
  21321. * An event triggered before calculating deterministic simulation step
  21322. * @type {BABYLON.Observable}
  21323. */
  21324. this.onBeforeStepObservable = new BABYLON.Observable();
  21325. /**
  21326. * An event triggered after calculating deterministic simulation step
  21327. * @type {BABYLON.Observable}
  21328. */
  21329. this.onAfterStepObservable = new BABYLON.Observable();
  21330. /**
  21331. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21332. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21333. * 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)
  21334. */
  21335. this.onRenderingGroupObservable = new BABYLON.Observable();
  21336. // Animations
  21337. this.animations = [];
  21338. /**
  21339. * 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).
  21340. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21341. */
  21342. this.onPrePointerObservable = new BABYLON.Observable();
  21343. /**
  21344. * Observable event triggered each time an input event is received from the rendering canvas
  21345. */
  21346. this.onPointerObservable = new BABYLON.Observable();
  21347. this._meshPickProceed = false;
  21348. this._currentPickResult = null;
  21349. this._previousPickResult = null;
  21350. this._totalPointersPressed = 0;
  21351. this._doubleClickOccured = false;
  21352. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21353. this.cameraToUseForPointers = null;
  21354. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21355. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21356. this._startingPointerTime = 0;
  21357. this._previousStartingPointerTime = 0;
  21358. // Deterministic lockstep
  21359. this._timeAccumulator = 0;
  21360. this._currentStepId = 0;
  21361. this._currentInternalStep = 0;
  21362. // Keyboard
  21363. /**
  21364. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21365. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21366. */
  21367. this.onPreKeyboardObservable = new BABYLON.Observable();
  21368. /**
  21369. * Observable event triggered each time an keyboard event is received from the hosting window
  21370. */
  21371. this.onKeyboardObservable = new BABYLON.Observable();
  21372. // Coordinate system
  21373. /**
  21374. * use right-handed coordinate system on this scene.
  21375. * @type {boolean}
  21376. */
  21377. this._useRightHandedSystem = false;
  21378. // Fog
  21379. this._fogEnabled = true;
  21380. this._fogMode = Scene.FOGMODE_NONE;
  21381. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21382. this.fogDensity = 0.1;
  21383. this.fogStart = 0;
  21384. this.fogEnd = 1000.0;
  21385. // Lights
  21386. /**
  21387. * is shadow enabled on this scene.
  21388. * @type {boolean}
  21389. */
  21390. this._shadowsEnabled = true;
  21391. /**
  21392. * is light enabled on this scene.
  21393. * @type {boolean}
  21394. */
  21395. this._lightsEnabled = true;
  21396. /**
  21397. * All of the lights added to this scene.
  21398. * @see BABYLON.Light
  21399. * @type {BABYLON.Light[]}
  21400. */
  21401. this.lights = new Array();
  21402. // Cameras
  21403. /** All of the cameras added to this scene. */
  21404. this.cameras = new Array();
  21405. /** All of the active cameras added to this scene. */
  21406. this.activeCameras = new Array();
  21407. // Meshes
  21408. /**
  21409. * All of the tranform nodes added to this scene.
  21410. * @see BABYLON.TransformNode
  21411. * @type {BABYLON.TransformNode[]}
  21412. */
  21413. this.transformNodes = new Array();
  21414. /**
  21415. * All of the (abstract) meshes added to this scene.
  21416. * @see BABYLON.AbstractMesh
  21417. * @type {BABYLON.AbstractMesh[]}
  21418. */
  21419. this.meshes = new Array();
  21420. /**
  21421. * All of the animation groups added to this scene.
  21422. * @see BABYLON.AnimationGroup
  21423. * @type {BABYLON.AnimationGroup[]}
  21424. */
  21425. this.animationGroups = new Array();
  21426. // Geometries
  21427. this._geometries = new Array();
  21428. this.materials = new Array();
  21429. this.multiMaterials = new Array();
  21430. // Textures
  21431. this._texturesEnabled = true;
  21432. this.textures = new Array();
  21433. // Particles
  21434. this.particlesEnabled = true;
  21435. this.particleSystems = new Array();
  21436. // Sprites
  21437. this.spritesEnabled = true;
  21438. this.spriteManagers = new Array();
  21439. /**
  21440. * The list of layers (background and foreground) of the scene.
  21441. */
  21442. this.layers = new Array();
  21443. /**
  21444. * The list of effect layers (highlights/glow) contained in the scene.
  21445. */
  21446. this.effectLayers = new Array();
  21447. // Skeletons
  21448. this._skeletonsEnabled = true;
  21449. this.skeletons = new Array();
  21450. // Morph targets
  21451. this.morphTargetManagers = new Array();
  21452. // Lens flares
  21453. this.lensFlaresEnabled = true;
  21454. this.lensFlareSystems = new Array();
  21455. // Collisions
  21456. this.collisionsEnabled = true;
  21457. /** Defines the gravity applied to this scene */
  21458. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21459. // Postprocesses
  21460. this.postProcesses = new Array();
  21461. this.postProcessesEnabled = true;
  21462. // Customs render targets
  21463. this.renderTargetsEnabled = true;
  21464. this.dumpNextRenderTargets = false;
  21465. this.customRenderTargets = new Array();
  21466. // Imported meshes
  21467. this.importedMeshesFiles = new Array();
  21468. // Probes
  21469. this.probesEnabled = true;
  21470. this.reflectionProbes = new Array();
  21471. this._actionManagers = new Array();
  21472. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21473. // Procedural textures
  21474. this.proceduralTexturesEnabled = true;
  21475. this._proceduralTextures = new Array();
  21476. this.soundTracks = new Array();
  21477. this._audioEnabled = true;
  21478. this._headphone = false;
  21479. // Performance counters
  21480. this._totalVertices = new BABYLON.PerfCounter();
  21481. this._activeIndices = new BABYLON.PerfCounter();
  21482. this._activeParticles = new BABYLON.PerfCounter();
  21483. this._activeBones = new BABYLON.PerfCounter();
  21484. this._animationTime = 0;
  21485. this.animationTimeScale = 1;
  21486. this._renderId = 0;
  21487. this._executeWhenReadyTimeoutId = -1;
  21488. this._intermediateRendering = false;
  21489. this._viewUpdateFlag = -1;
  21490. this._projectionUpdateFlag = -1;
  21491. this._alternateViewUpdateFlag = -1;
  21492. this._alternateProjectionUpdateFlag = -1;
  21493. this._toBeDisposed = new BABYLON.SmartArray(256);
  21494. this._activeRequests = new Array();
  21495. this._pendingData = new Array();
  21496. this._isDisposed = false;
  21497. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21498. this._activeMeshes = new BABYLON.SmartArray(256);
  21499. this._processedMaterials = new BABYLON.SmartArray(256);
  21500. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21501. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21502. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21503. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21504. this._activeAnimatables = new Array();
  21505. this._transformMatrix = BABYLON.Matrix.Zero();
  21506. this._useAlternateCameraConfiguration = false;
  21507. this._alternateRendering = false;
  21508. this.requireLightSorting = false;
  21509. this._depthRenderer = {};
  21510. this._activeMeshesFrozen = false;
  21511. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21512. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21513. this._engine.scenes.push(this);
  21514. this._uid = null;
  21515. this._renderingManager = new BABYLON.RenderingManager(this);
  21516. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21517. if (BABYLON.OutlineRenderer) {
  21518. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21519. }
  21520. if (BABYLON.Tools.IsWindowObjectExist()) {
  21521. this.attachControl();
  21522. }
  21523. //simplification queue
  21524. if (BABYLON.SimplificationQueue) {
  21525. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21526. }
  21527. //collision coordinator initialization. For now legacy per default.
  21528. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21529. // Uniform Buffer
  21530. this._createUbo();
  21531. // Default Image processing definition.
  21532. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21533. }
  21534. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21535. /** The fog is deactivated */
  21536. get: function () {
  21537. return Scene._FOGMODE_NONE;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21543. /** The fog density is following an exponential function */
  21544. get: function () {
  21545. return Scene._FOGMODE_EXP;
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21551. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21552. get: function () {
  21553. return Scene._FOGMODE_EXP2;
  21554. },
  21555. enumerable: true,
  21556. configurable: true
  21557. });
  21558. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21559. /** The fog density is following a linear function. */
  21560. get: function () {
  21561. return Scene._FOGMODE_LINEAR;
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21567. /**
  21568. * Texture used in all pbr material as the reflection texture.
  21569. * As in the majority of the scene they are the same (exception for multi room and so on),
  21570. * this is easier to reference from here than from all the materials.
  21571. */
  21572. get: function () {
  21573. return this._environmentTexture;
  21574. },
  21575. /**
  21576. * Texture used in all pbr material as the reflection texture.
  21577. * As in the majority of the scene they are the same (exception for multi room and so on),
  21578. * this is easier to set here than in all the materials.
  21579. */
  21580. set: function (value) {
  21581. if (this._environmentTexture === value) {
  21582. return;
  21583. }
  21584. this._environmentTexture = value;
  21585. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21586. },
  21587. enumerable: true,
  21588. configurable: true
  21589. });
  21590. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21591. /**
  21592. * Default image processing configuration used either in the rendering
  21593. * Forward main pass or through the imageProcessingPostProcess if present.
  21594. * As in the majority of the scene they are the same (exception for multi camera),
  21595. * this is easier to reference from here than from all the materials and post process.
  21596. *
  21597. * No setter as we it is a shared configuration, you can set the values instead.
  21598. */
  21599. get: function () {
  21600. return this._imageProcessingConfiguration;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21606. get: function () {
  21607. return this._forcePointsCloud;
  21608. },
  21609. set: function (value) {
  21610. if (this._forcePointsCloud === value) {
  21611. return;
  21612. }
  21613. this._forcePointsCloud = value;
  21614. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Scene.prototype, "onDispose", {
  21620. /** A function to be executed when this scene is disposed. */
  21621. set: function (callback) {
  21622. if (this._onDisposeObserver) {
  21623. this.onDisposeObservable.remove(this._onDisposeObserver);
  21624. }
  21625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21626. },
  21627. enumerable: true,
  21628. configurable: true
  21629. });
  21630. Object.defineProperty(Scene.prototype, "beforeRender", {
  21631. /** A function to be executed before rendering this scene */
  21632. set: function (callback) {
  21633. if (this._onBeforeRenderObserver) {
  21634. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21635. }
  21636. if (callback) {
  21637. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21638. }
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. Object.defineProperty(Scene.prototype, "afterRender", {
  21644. /** A function to be executed after rendering this scene */
  21645. set: function (callback) {
  21646. if (this._onAfterRenderObserver) {
  21647. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21648. }
  21649. if (callback) {
  21650. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21651. }
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21657. set: function (callback) {
  21658. if (this._onBeforeCameraRenderObserver) {
  21659. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21660. }
  21661. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21667. set: function (callback) {
  21668. if (this._onAfterCameraRenderObserver) {
  21669. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21670. }
  21671. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21677. get: function () {
  21678. if (!this._gamepadManager) {
  21679. this._gamepadManager = new BABYLON.GamepadManager(this);
  21680. }
  21681. return this._gamepadManager;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21687. get: function () {
  21688. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21689. },
  21690. enumerable: true,
  21691. configurable: true
  21692. });
  21693. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21694. get: function () {
  21695. return this._useRightHandedSystem;
  21696. },
  21697. set: function (value) {
  21698. if (this._useRightHandedSystem === value) {
  21699. return;
  21700. }
  21701. this._useRightHandedSystem = value;
  21702. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Scene.prototype.setStepId = function (newStepId) {
  21708. this._currentStepId = newStepId;
  21709. };
  21710. ;
  21711. Scene.prototype.getStepId = function () {
  21712. return this._currentStepId;
  21713. };
  21714. ;
  21715. Scene.prototype.getInternalStep = function () {
  21716. return this._currentInternalStep;
  21717. };
  21718. ;
  21719. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21720. get: function () {
  21721. return this._fogEnabled;
  21722. },
  21723. /**
  21724. * is fog enabled on this scene.
  21725. */
  21726. set: function (value) {
  21727. if (this._fogEnabled === value) {
  21728. return;
  21729. }
  21730. this._fogEnabled = value;
  21731. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21732. },
  21733. enumerable: true,
  21734. configurable: true
  21735. });
  21736. Object.defineProperty(Scene.prototype, "fogMode", {
  21737. get: function () {
  21738. return this._fogMode;
  21739. },
  21740. set: function (value) {
  21741. if (this._fogMode === value) {
  21742. return;
  21743. }
  21744. this._fogMode = value;
  21745. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21746. },
  21747. enumerable: true,
  21748. configurable: true
  21749. });
  21750. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21751. get: function () {
  21752. return this._shadowsEnabled;
  21753. },
  21754. set: function (value) {
  21755. if (this._shadowsEnabled === value) {
  21756. return;
  21757. }
  21758. this._shadowsEnabled = value;
  21759. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21765. get: function () {
  21766. return this._lightsEnabled;
  21767. },
  21768. set: function (value) {
  21769. if (this._lightsEnabled === value) {
  21770. return;
  21771. }
  21772. this._lightsEnabled = value;
  21773. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21779. /** The default material used on meshes when no material is affected */
  21780. get: function () {
  21781. if (!this._defaultMaterial) {
  21782. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21783. }
  21784. return this._defaultMaterial;
  21785. },
  21786. /** The default material used on meshes when no material is affected */
  21787. set: function (value) {
  21788. this._defaultMaterial = value;
  21789. },
  21790. enumerable: true,
  21791. configurable: true
  21792. });
  21793. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21794. get: function () {
  21795. return this._texturesEnabled;
  21796. },
  21797. set: function (value) {
  21798. if (this._texturesEnabled === value) {
  21799. return;
  21800. }
  21801. this._texturesEnabled = value;
  21802. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21803. },
  21804. enumerable: true,
  21805. configurable: true
  21806. });
  21807. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21808. get: function () {
  21809. return this._skeletonsEnabled;
  21810. },
  21811. set: function (value) {
  21812. if (this._skeletonsEnabled === value) {
  21813. return;
  21814. }
  21815. this._skeletonsEnabled = value;
  21816. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21817. },
  21818. enumerable: true,
  21819. configurable: true
  21820. });
  21821. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21822. get: function () {
  21823. if (!this._postProcessRenderPipelineManager) {
  21824. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21825. }
  21826. return this._postProcessRenderPipelineManager;
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21832. get: function () {
  21833. if (!this._mainSoundTrack) {
  21834. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21835. }
  21836. return this._mainSoundTrack;
  21837. },
  21838. enumerable: true,
  21839. configurable: true
  21840. });
  21841. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21842. get: function () {
  21843. return this._alternateRendering;
  21844. },
  21845. enumerable: true,
  21846. configurable: true
  21847. });
  21848. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21849. get: function () {
  21850. return this._frustumPlanes;
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21856. /**
  21857. * Gets the current geometry buffer associated to the scene.
  21858. */
  21859. get: function () {
  21860. return this._geometryBufferRenderer;
  21861. },
  21862. /**
  21863. * Sets the current geometry buffer for the scene.
  21864. */
  21865. set: function (geometryBufferRenderer) {
  21866. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21867. this._geometryBufferRenderer = geometryBufferRenderer;
  21868. }
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(Scene.prototype, "debugLayer", {
  21874. // Properties
  21875. get: function () {
  21876. if (!this._debugLayer) {
  21877. this._debugLayer = new BABYLON.DebugLayer(this);
  21878. }
  21879. return this._debugLayer;
  21880. },
  21881. enumerable: true,
  21882. configurable: true
  21883. });
  21884. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21885. get: function () {
  21886. return this._workerCollisions;
  21887. },
  21888. set: function (enabled) {
  21889. if (!BABYLON.CollisionCoordinatorLegacy) {
  21890. return;
  21891. }
  21892. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  21893. this._workerCollisions = enabled;
  21894. if (this.collisionCoordinator) {
  21895. this.collisionCoordinator.destroy();
  21896. }
  21897. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21898. this.collisionCoordinator.init(this);
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21904. get: function () {
  21905. return this._selectionOctree;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21911. /**
  21912. * The mesh that is currently under the pointer.
  21913. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21914. */
  21915. get: function () {
  21916. return this._pointerOverMesh;
  21917. },
  21918. enumerable: true,
  21919. configurable: true
  21920. });
  21921. Object.defineProperty(Scene.prototype, "pointerX", {
  21922. /**
  21923. * Current on-screen X position of the pointer
  21924. * @return {number} X position of the pointer
  21925. */
  21926. get: function () {
  21927. return this._pointerX;
  21928. },
  21929. enumerable: true,
  21930. configurable: true
  21931. });
  21932. Object.defineProperty(Scene.prototype, "pointerY", {
  21933. /**
  21934. * Current on-screen Y position of the pointer
  21935. * @return {number} Y position of the pointer
  21936. */
  21937. get: function () {
  21938. return this._pointerY;
  21939. },
  21940. enumerable: true,
  21941. configurable: true
  21942. });
  21943. Scene.prototype.getCachedMaterial = function () {
  21944. return this._cachedMaterial;
  21945. };
  21946. Scene.prototype.getCachedEffect = function () {
  21947. return this._cachedEffect;
  21948. };
  21949. Scene.prototype.getCachedVisibility = function () {
  21950. return this._cachedVisibility;
  21951. };
  21952. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21953. if (visibility === void 0) { visibility = 1; }
  21954. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21955. };
  21956. Scene.prototype.getBoundingBoxRenderer = function () {
  21957. if (!this._boundingBoxRenderer) {
  21958. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21959. }
  21960. return this._boundingBoxRenderer;
  21961. };
  21962. Scene.prototype.getOutlineRenderer = function () {
  21963. return this._outlineRenderer;
  21964. };
  21965. Scene.prototype.getEngine = function () {
  21966. return this._engine;
  21967. };
  21968. Scene.prototype.getTotalVertices = function () {
  21969. return this._totalVertices.current;
  21970. };
  21971. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21972. get: function () {
  21973. return this._totalVertices;
  21974. },
  21975. enumerable: true,
  21976. configurable: true
  21977. });
  21978. Scene.prototype.getActiveIndices = function () {
  21979. return this._activeIndices.current;
  21980. };
  21981. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21982. get: function () {
  21983. return this._activeIndices;
  21984. },
  21985. enumerable: true,
  21986. configurable: true
  21987. });
  21988. Scene.prototype.getActiveParticles = function () {
  21989. return this._activeParticles.current;
  21990. };
  21991. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21992. get: function () {
  21993. return this._activeParticles;
  21994. },
  21995. enumerable: true,
  21996. configurable: true
  21997. });
  21998. Scene.prototype.getActiveBones = function () {
  21999. return this._activeBones.current;
  22000. };
  22001. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22002. get: function () {
  22003. return this._activeBones;
  22004. },
  22005. enumerable: true,
  22006. configurable: true
  22007. });
  22008. // Stats
  22009. Scene.prototype.getInterFramePerfCounter = function () {
  22010. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22011. return 0;
  22012. };
  22013. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22014. get: function () {
  22015. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22016. return null;
  22017. },
  22018. enumerable: true,
  22019. configurable: true
  22020. });
  22021. Scene.prototype.getLastFrameDuration = function () {
  22022. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22023. return 0;
  22024. };
  22025. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22026. get: function () {
  22027. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22028. return null;
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22034. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22035. return 0;
  22036. };
  22037. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22038. get: function () {
  22039. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22040. return null;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Scene.prototype.getActiveMeshes = function () {
  22046. return this._activeMeshes;
  22047. };
  22048. Scene.prototype.getRenderTargetsDuration = function () {
  22049. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22050. return 0;
  22051. };
  22052. Scene.prototype.getRenderDuration = function () {
  22053. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22054. return 0;
  22055. };
  22056. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22057. get: function () {
  22058. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22059. return null;
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Scene.prototype.getParticlesDuration = function () {
  22065. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22066. return 0;
  22067. };
  22068. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22069. get: function () {
  22070. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22071. return null;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Scene.prototype.getSpritesDuration = function () {
  22077. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22078. return 0;
  22079. };
  22080. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22081. get: function () {
  22082. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22083. return null;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Scene.prototype.getAnimationRatio = function () {
  22089. return this._animationRatio;
  22090. };
  22091. Scene.prototype.getRenderId = function () {
  22092. return this._renderId;
  22093. };
  22094. Scene.prototype.incrementRenderId = function () {
  22095. this._renderId++;
  22096. };
  22097. Scene.prototype._updatePointerPosition = function (evt) {
  22098. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22099. if (!canvasRect) {
  22100. return;
  22101. }
  22102. this._pointerX = evt.clientX - canvasRect.left;
  22103. this._pointerY = evt.clientY - canvasRect.top;
  22104. this._unTranslatedPointerX = this._pointerX;
  22105. this._unTranslatedPointerY = this._pointerY;
  22106. };
  22107. Scene.prototype._createUbo = function () {
  22108. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22109. this._sceneUbo.addUniform("viewProjection", 16);
  22110. this._sceneUbo.addUniform("view", 16);
  22111. };
  22112. Scene.prototype._createAlternateUbo = function () {
  22113. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22114. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22115. this._alternateSceneUbo.addUniform("view", 16);
  22116. };
  22117. // Pointers handling
  22118. /**
  22119. * Use this method to simulate a pointer move on a mesh
  22120. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22121. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22122. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22123. */
  22124. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22125. var evt = new PointerEvent("pointermove", pointerEventInit);
  22126. return this._processPointerMove(pickResult, evt);
  22127. };
  22128. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22129. var canvas = this._engine.getRenderingCanvas();
  22130. if (!canvas) {
  22131. return this;
  22132. }
  22133. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22134. this.setPointerOverSprite(null);
  22135. this.setPointerOverMesh(pickResult.pickedMesh);
  22136. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22137. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22138. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22139. }
  22140. else {
  22141. canvas.style.cursor = this.hoverCursor;
  22142. }
  22143. }
  22144. else {
  22145. canvas.style.cursor = this.defaultCursor;
  22146. }
  22147. }
  22148. else {
  22149. this.setPointerOverMesh(null);
  22150. // Sprites
  22151. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22152. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22153. this.setPointerOverSprite(pickResult.pickedSprite);
  22154. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22155. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22156. }
  22157. else {
  22158. canvas.style.cursor = this.hoverCursor;
  22159. }
  22160. }
  22161. else {
  22162. this.setPointerOverSprite(null);
  22163. // Restore pointer
  22164. canvas.style.cursor = this.defaultCursor;
  22165. }
  22166. }
  22167. if (pickResult) {
  22168. if (this.onPointerMove) {
  22169. this.onPointerMove(evt, pickResult);
  22170. }
  22171. if (this.onPointerObservable.hasObservers()) {
  22172. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22173. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22174. this.onPointerObservable.notifyObservers(pi, type);
  22175. }
  22176. }
  22177. return this;
  22178. };
  22179. /**
  22180. * Use this method to simulate a pointer down on a mesh
  22181. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22182. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22183. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22184. */
  22185. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22186. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22187. return this._processPointerDown(pickResult, evt);
  22188. };
  22189. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22190. var _this = this;
  22191. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22192. this._pickedDownMesh = pickResult.pickedMesh;
  22193. var actionManager = pickResult.pickedMesh.actionManager;
  22194. if (actionManager) {
  22195. if (actionManager.hasPickTriggers) {
  22196. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22197. switch (evt.button) {
  22198. case 0:
  22199. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22200. break;
  22201. case 1:
  22202. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22203. break;
  22204. case 2:
  22205. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22206. break;
  22207. }
  22208. }
  22209. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22210. window.setTimeout(function () {
  22211. 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);
  22212. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22213. if (_this._totalPointersPressed !== 0 &&
  22214. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22215. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22216. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22217. _this._startingPointerTime = 0;
  22218. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22219. }
  22220. }
  22221. }, Scene.LongPressDelay);
  22222. }
  22223. }
  22224. }
  22225. if (pickResult) {
  22226. if (this.onPointerDown) {
  22227. this.onPointerDown(evt, pickResult);
  22228. }
  22229. if (this.onPointerObservable.hasObservers()) {
  22230. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22231. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22232. this.onPointerObservable.notifyObservers(pi, type);
  22233. }
  22234. }
  22235. return this;
  22236. };
  22237. /**
  22238. * Use this method to simulate a pointer up on a mesh
  22239. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22240. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22241. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22242. */
  22243. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22244. var evt = new PointerEvent("pointerup", pointerEventInit);
  22245. var clickInfo = new ClickInfo();
  22246. clickInfo.singleClick = true;
  22247. clickInfo.ignore = true;
  22248. return this._processPointerUp(pickResult, evt, clickInfo);
  22249. };
  22250. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22251. if (pickResult && pickResult && pickResult.pickedMesh) {
  22252. this._pickedUpMesh = pickResult.pickedMesh;
  22253. if (this._pickedDownMesh === this._pickedUpMesh) {
  22254. if (this.onPointerPick) {
  22255. this.onPointerPick(evt, pickResult);
  22256. }
  22257. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22258. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22259. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22260. this.onPointerObservable.notifyObservers(pi, type);
  22261. }
  22262. }
  22263. if (pickResult.pickedMesh.actionManager) {
  22264. if (clickInfo.ignore) {
  22265. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22266. }
  22267. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22268. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22269. }
  22270. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22271. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22272. }
  22273. }
  22274. }
  22275. if (this._pickedDownMesh &&
  22276. this._pickedDownMesh.actionManager &&
  22277. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22278. this._pickedDownMesh !== this._pickedUpMesh) {
  22279. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22280. }
  22281. if (this.onPointerUp) {
  22282. this.onPointerUp(evt, pickResult);
  22283. }
  22284. if (this.onPointerObservable.hasObservers()) {
  22285. if (!clickInfo.ignore) {
  22286. if (!clickInfo.hasSwiped) {
  22287. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22288. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22289. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22290. this.onPointerObservable.notifyObservers(pi, type);
  22291. }
  22292. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22293. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22294. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22295. this.onPointerObservable.notifyObservers(pi, type);
  22296. }
  22297. }
  22298. }
  22299. else {
  22300. var type = BABYLON.PointerEventTypes.POINTERUP;
  22301. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22302. this.onPointerObservable.notifyObservers(pi, type);
  22303. }
  22304. }
  22305. return this;
  22306. };
  22307. /**
  22308. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22309. * @param attachUp defines if you want to attach events to pointerup
  22310. * @param attachDown defines if you want to attach events to pointerdown
  22311. * @param attachMove defines if you want to attach events to pointermove
  22312. */
  22313. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22314. var _this = this;
  22315. if (attachUp === void 0) { attachUp = true; }
  22316. if (attachDown === void 0) { attachDown = true; }
  22317. if (attachMove === void 0) { attachMove = true; }
  22318. this._initActionManager = function (act, clickInfo) {
  22319. if (!_this._meshPickProceed) {
  22320. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22321. _this._currentPickResult = pickResult;
  22322. if (pickResult) {
  22323. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22324. }
  22325. _this._meshPickProceed = true;
  22326. }
  22327. return act;
  22328. };
  22329. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22330. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22331. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22332. btn !== _this._previousButtonPressed) {
  22333. _this._doubleClickOccured = false;
  22334. clickInfo.singleClick = true;
  22335. clickInfo.ignore = false;
  22336. cb(clickInfo, _this._currentPickResult);
  22337. }
  22338. };
  22339. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22340. var clickInfo = new ClickInfo();
  22341. _this._currentPickResult = null;
  22342. var act = null;
  22343. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22344. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22345. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22346. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22347. act = _this._initActionManager(act, clickInfo);
  22348. if (act)
  22349. checkPicking = act.hasPickTriggers;
  22350. }
  22351. if (checkPicking) {
  22352. var btn = evt.button;
  22353. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22354. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22355. if (!clickInfo.hasSwiped) {
  22356. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22357. if (!checkSingleClickImmediately) {
  22358. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22359. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22360. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22361. act = _this._initActionManager(act, clickInfo);
  22362. if (act)
  22363. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22364. }
  22365. }
  22366. if (checkSingleClickImmediately) {
  22367. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22368. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22369. btn !== _this._previousButtonPressed) {
  22370. clickInfo.singleClick = true;
  22371. cb(clickInfo, _this._currentPickResult);
  22372. }
  22373. }
  22374. else {
  22375. // wait that no double click has been raised during the double click delay
  22376. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22377. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22378. }
  22379. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22380. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22381. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22382. act = _this._initActionManager(act, clickInfo);
  22383. if (act)
  22384. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22385. }
  22386. if (checkDoubleClick) {
  22387. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22388. if (btn === _this._previousButtonPressed &&
  22389. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22390. !_this._doubleClickOccured) {
  22391. // pointer has not moved for 2 clicks, it's a double click
  22392. if (!clickInfo.hasSwiped &&
  22393. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22394. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22395. _this._previousStartingPointerTime = 0;
  22396. _this._doubleClickOccured = true;
  22397. clickInfo.doubleClick = true;
  22398. clickInfo.ignore = false;
  22399. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22400. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22401. }
  22402. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22403. cb(clickInfo, _this._currentPickResult);
  22404. }
  22405. else {
  22406. _this._doubleClickOccured = false;
  22407. _this._previousStartingPointerTime = _this._startingPointerTime;
  22408. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22409. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22410. _this._previousButtonPressed = btn;
  22411. if (Scene.ExclusiveDoubleClickMode) {
  22412. if (_this._previousDelayedSimpleClickTimeout) {
  22413. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22414. }
  22415. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22416. cb(clickInfo, _this._previousPickResult);
  22417. }
  22418. else {
  22419. cb(clickInfo, _this._currentPickResult);
  22420. }
  22421. }
  22422. }
  22423. else {
  22424. _this._doubleClickOccured = false;
  22425. _this._previousStartingPointerTime = _this._startingPointerTime;
  22426. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22427. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22428. _this._previousButtonPressed = btn;
  22429. }
  22430. }
  22431. }
  22432. }
  22433. clickInfo.ignore = true;
  22434. cb(clickInfo, _this._currentPickResult);
  22435. };
  22436. this._spritePredicate = function (sprite) {
  22437. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22438. };
  22439. this._onPointerMove = function (evt) {
  22440. _this._updatePointerPosition(evt);
  22441. // PreObservable support
  22442. if (_this.onPrePointerObservable.hasObservers()) {
  22443. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22444. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22445. _this.onPrePointerObservable.notifyObservers(pi, type);
  22446. if (pi.skipOnPointerObservable) {
  22447. return;
  22448. }
  22449. }
  22450. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22451. return;
  22452. }
  22453. if (!_this.pointerMovePredicate) {
  22454. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22455. }
  22456. // Meshes
  22457. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22458. _this._processPointerMove(pickResult, evt);
  22459. };
  22460. this._onPointerDown = function (evt) {
  22461. _this._totalPointersPressed++;
  22462. _this._pickedDownMesh = null;
  22463. _this._meshPickProceed = false;
  22464. _this._updatePointerPosition(evt);
  22465. if (_this.preventDefaultOnPointerDown && canvas) {
  22466. evt.preventDefault();
  22467. canvas.focus();
  22468. }
  22469. // PreObservable support
  22470. if (_this.onPrePointerObservable.hasObservers()) {
  22471. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22472. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22473. _this.onPrePointerObservable.notifyObservers(pi, type);
  22474. if (pi.skipOnPointerObservable) {
  22475. return;
  22476. }
  22477. }
  22478. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22479. return;
  22480. }
  22481. _this._startingPointerPosition.x = _this._pointerX;
  22482. _this._startingPointerPosition.y = _this._pointerY;
  22483. _this._startingPointerTime = new Date().getTime();
  22484. if (!_this.pointerDownPredicate) {
  22485. _this.pointerDownPredicate = function (mesh) {
  22486. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22487. };
  22488. }
  22489. // Meshes
  22490. _this._pickedDownMesh = null;
  22491. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22492. _this._processPointerDown(pickResult, evt);
  22493. // Sprites
  22494. _this._pickedDownSprite = null;
  22495. if (_this.spriteManagers.length > 0) {
  22496. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22497. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22498. if (pickResult.pickedSprite.actionManager) {
  22499. _this._pickedDownSprite = pickResult.pickedSprite;
  22500. switch (evt.button) {
  22501. case 0:
  22502. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22503. break;
  22504. case 1:
  22505. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22506. break;
  22507. case 2:
  22508. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22509. break;
  22510. }
  22511. if (pickResult.pickedSprite.actionManager) {
  22512. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22513. }
  22514. }
  22515. }
  22516. }
  22517. };
  22518. this._onPointerUp = function (evt) {
  22519. if (_this._totalPointersPressed === 0) {
  22520. return; // So we need to test it the pointer down was pressed before.
  22521. }
  22522. _this._totalPointersPressed--;
  22523. _this._pickedUpMesh = null;
  22524. _this._meshPickProceed = false;
  22525. _this._updatePointerPosition(evt);
  22526. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22527. // PreObservable support
  22528. if (_this.onPrePointerObservable.hasObservers()) {
  22529. if (!clickInfo.ignore) {
  22530. if (!clickInfo.hasSwiped) {
  22531. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22532. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22533. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22534. _this.onPrePointerObservable.notifyObservers(pi, type);
  22535. if (pi.skipOnPointerObservable) {
  22536. return;
  22537. }
  22538. }
  22539. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22540. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22541. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22542. _this.onPrePointerObservable.notifyObservers(pi, type);
  22543. if (pi.skipOnPointerObservable) {
  22544. return;
  22545. }
  22546. }
  22547. }
  22548. }
  22549. else {
  22550. var type = BABYLON.PointerEventTypes.POINTERUP;
  22551. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22552. _this.onPrePointerObservable.notifyObservers(pi, type);
  22553. if (pi.skipOnPointerObservable) {
  22554. return;
  22555. }
  22556. }
  22557. }
  22558. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22559. return;
  22560. }
  22561. if (!_this.pointerUpPredicate) {
  22562. _this.pointerUpPredicate = function (mesh) {
  22563. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22564. };
  22565. }
  22566. // Meshes
  22567. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22568. _this._initActionManager(null, clickInfo);
  22569. }
  22570. if (!pickResult) {
  22571. pickResult = _this._currentPickResult;
  22572. }
  22573. _this._processPointerUp(pickResult, evt, clickInfo);
  22574. // Sprites
  22575. if (_this.spriteManagers.length > 0) {
  22576. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22577. if (spritePickResult) {
  22578. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22579. if (spritePickResult.pickedSprite.actionManager) {
  22580. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22581. if (spritePickResult.pickedSprite.actionManager) {
  22582. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22583. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22584. }
  22585. }
  22586. }
  22587. }
  22588. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22589. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22590. }
  22591. }
  22592. }
  22593. _this._previousPickResult = _this._currentPickResult;
  22594. });
  22595. };
  22596. this._onKeyDown = function (evt) {
  22597. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22598. if (_this.onPreKeyboardObservable.hasObservers()) {
  22599. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22600. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22601. if (pi.skipOnPointerObservable) {
  22602. return;
  22603. }
  22604. }
  22605. if (_this.onKeyboardObservable.hasObservers()) {
  22606. var pi = new BABYLON.KeyboardInfo(type, evt);
  22607. _this.onKeyboardObservable.notifyObservers(pi, type);
  22608. }
  22609. if (_this.actionManager) {
  22610. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22611. }
  22612. };
  22613. this._onKeyUp = function (evt) {
  22614. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22615. if (_this.onPreKeyboardObservable.hasObservers()) {
  22616. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22617. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22618. if (pi.skipOnPointerObservable) {
  22619. return;
  22620. }
  22621. }
  22622. if (_this.onKeyboardObservable.hasObservers()) {
  22623. var pi = new BABYLON.KeyboardInfo(type, evt);
  22624. _this.onKeyboardObservable.notifyObservers(pi, type);
  22625. }
  22626. if (_this.actionManager) {
  22627. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22628. }
  22629. };
  22630. var engine = this.getEngine();
  22631. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22632. if (!canvas) {
  22633. return;
  22634. }
  22635. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22636. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22637. });
  22638. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22639. if (!canvas) {
  22640. return;
  22641. }
  22642. canvas.removeEventListener("keydown", _this._onKeyDown);
  22643. canvas.removeEventListener("keyup", _this._onKeyUp);
  22644. });
  22645. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22646. var canvas = this._engine.getRenderingCanvas();
  22647. if (!canvas) {
  22648. return;
  22649. }
  22650. if (attachMove) {
  22651. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22652. // Wheel
  22653. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22654. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22655. }
  22656. if (attachDown) {
  22657. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22658. }
  22659. if (attachUp) {
  22660. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22661. }
  22662. canvas.tabIndex = 1;
  22663. };
  22664. Scene.prototype.detachControl = function () {
  22665. var engine = this.getEngine();
  22666. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22667. var canvas = engine.getRenderingCanvas();
  22668. if (!canvas) {
  22669. return;
  22670. }
  22671. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22672. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22673. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22674. if (this._onCanvasBlurObserver) {
  22675. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22676. }
  22677. if (this._onCanvasFocusObserver) {
  22678. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22679. }
  22680. // Wheel
  22681. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22682. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22683. // Keyboard
  22684. canvas.removeEventListener("keydown", this._onKeyDown);
  22685. canvas.removeEventListener("keyup", this._onKeyUp);
  22686. // Observables
  22687. this.onKeyboardObservable.clear();
  22688. this.onPreKeyboardObservable.clear();
  22689. this.onPointerObservable.clear();
  22690. this.onPrePointerObservable.clear();
  22691. };
  22692. /**
  22693. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22694. * Delay loaded resources are not taking in account
  22695. * @return true if all required resources are ready
  22696. */
  22697. Scene.prototype.isReady = function () {
  22698. if (this._isDisposed) {
  22699. return false;
  22700. }
  22701. if (this._pendingData.length > 0) {
  22702. return false;
  22703. }
  22704. var index;
  22705. var engine = this.getEngine();
  22706. // Geometries
  22707. for (index = 0; index < this._geometries.length; index++) {
  22708. var geometry = this._geometries[index];
  22709. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22710. return false;
  22711. }
  22712. }
  22713. // Meshes
  22714. for (index = 0; index < this.meshes.length; index++) {
  22715. var mesh = this.meshes[index];
  22716. if (!mesh.isEnabled()) {
  22717. continue;
  22718. }
  22719. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22720. continue;
  22721. }
  22722. if (!mesh.isReady(true)) {
  22723. return false;
  22724. }
  22725. // Effect layers
  22726. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22727. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22728. var layer = _a[_i];
  22729. if (!layer.hasMesh(mesh)) {
  22730. continue;
  22731. }
  22732. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22733. var subMesh = _c[_b];
  22734. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22735. return false;
  22736. }
  22737. }
  22738. }
  22739. }
  22740. return true;
  22741. };
  22742. Scene.prototype.resetCachedMaterial = function () {
  22743. this._cachedMaterial = null;
  22744. this._cachedEffect = null;
  22745. this._cachedVisibility = null;
  22746. };
  22747. Scene.prototype.registerBeforeRender = function (func) {
  22748. this.onBeforeRenderObservable.add(func);
  22749. };
  22750. Scene.prototype.unregisterBeforeRender = function (func) {
  22751. this.onBeforeRenderObservable.removeCallback(func);
  22752. };
  22753. Scene.prototype.registerAfterRender = function (func) {
  22754. this.onAfterRenderObservable.add(func);
  22755. };
  22756. Scene.prototype.unregisterAfterRender = function (func) {
  22757. this.onAfterRenderObservable.removeCallback(func);
  22758. };
  22759. Scene.prototype._executeOnceBeforeRender = function (func) {
  22760. var _this = this;
  22761. var execFunc = function () {
  22762. func();
  22763. setTimeout(function () {
  22764. _this.unregisterBeforeRender(execFunc);
  22765. });
  22766. };
  22767. this.registerBeforeRender(execFunc);
  22768. };
  22769. /**
  22770. * The provided function will run before render once and will be disposed afterwards.
  22771. * A timeout delay can be provided so that the function will be executed in N ms.
  22772. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22773. * @param func The function to be executed.
  22774. * @param timeout optional delay in ms
  22775. */
  22776. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22777. var _this = this;
  22778. if (timeout !== undefined) {
  22779. setTimeout(function () {
  22780. _this._executeOnceBeforeRender(func);
  22781. }, timeout);
  22782. }
  22783. else {
  22784. this._executeOnceBeforeRender(func);
  22785. }
  22786. };
  22787. Scene.prototype._addPendingData = function (data) {
  22788. this._pendingData.push(data);
  22789. };
  22790. Scene.prototype._removePendingData = function (data) {
  22791. var wasLoading = this.isLoading;
  22792. var index = this._pendingData.indexOf(data);
  22793. if (index !== -1) {
  22794. this._pendingData.splice(index, 1);
  22795. }
  22796. if (wasLoading && !this.isLoading) {
  22797. this.onDataLoadedObservable.notifyObservers(this);
  22798. }
  22799. };
  22800. Scene.prototype.getWaitingItemsCount = function () {
  22801. return this._pendingData.length;
  22802. };
  22803. Object.defineProperty(Scene.prototype, "isLoading", {
  22804. get: function () {
  22805. return this._pendingData.length > 0;
  22806. },
  22807. enumerable: true,
  22808. configurable: true
  22809. });
  22810. /**
  22811. * Registers a function to be executed when the scene is ready.
  22812. * @param {Function} func - the function to be executed.
  22813. */
  22814. Scene.prototype.executeWhenReady = function (func) {
  22815. var _this = this;
  22816. this.onReadyObservable.add(func);
  22817. if (this._executeWhenReadyTimeoutId !== -1) {
  22818. return;
  22819. }
  22820. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22821. _this._checkIsReady();
  22822. }, 150);
  22823. };
  22824. /**
  22825. * Returns a promise that resolves when the scene is ready.
  22826. * @returns A promise that resolves when the scene is ready.
  22827. */
  22828. Scene.prototype.whenReadyAsync = function () {
  22829. var _this = this;
  22830. return new Promise(function (resolve) {
  22831. _this.executeWhenReady(function () {
  22832. resolve();
  22833. });
  22834. });
  22835. };
  22836. Scene.prototype._checkIsReady = function () {
  22837. var _this = this;
  22838. if (this.isReady()) {
  22839. this.onReadyObservable.notifyObservers(this);
  22840. this.onReadyObservable.clear();
  22841. this._executeWhenReadyTimeoutId = -1;
  22842. return;
  22843. }
  22844. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22845. _this._checkIsReady();
  22846. }, 150);
  22847. };
  22848. // Animations
  22849. /**
  22850. * Will start the animation sequence of a given target
  22851. * @param target - the target
  22852. * @param {number} from - from which frame should animation start
  22853. * @param {number} to - till which frame should animation run.
  22854. * @param {boolean} [loop] - should the animation loop
  22855. * @param {number} [speedRatio] - the speed in which to run the animation
  22856. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22857. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22858. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22859. * See BABYLON.Animatable
  22860. */
  22861. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22862. if (speedRatio === void 0) { speedRatio = 1.0; }
  22863. if (from > to && speedRatio > 0) {
  22864. speedRatio *= -1;
  22865. }
  22866. this.stopAnimation(target);
  22867. if (!animatable) {
  22868. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22869. }
  22870. // Local animations
  22871. if (target.animations) {
  22872. animatable.appendAnimations(target, target.animations);
  22873. }
  22874. // Children animations
  22875. if (target.getAnimatables) {
  22876. var animatables = target.getAnimatables();
  22877. for (var index = 0; index < animatables.length; index++) {
  22878. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22879. }
  22880. }
  22881. animatable.reset();
  22882. return animatable;
  22883. };
  22884. /**
  22885. * Begin a new animation on a given node
  22886. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22887. * @param {BABYLON.Animation[]} defines the list of animations to start
  22888. * @param {number} from defines the initial value
  22889. * @param {number} to defines the final value
  22890. * @param {boolean} loop defines if you want animation to loop (off by default)
  22891. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22892. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22893. * @returns the list of created animatables
  22894. */
  22895. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22896. if (speedRatio === undefined) {
  22897. speedRatio = 1.0;
  22898. }
  22899. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22900. return animatable;
  22901. };
  22902. /**
  22903. * Begin a new animation on a given node and its hierarchy
  22904. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22905. * @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.
  22906. * @param {BABYLON.Animation[]} defines the list of animations to start
  22907. * @param {number} from defines the initial value
  22908. * @param {number} to defines the final value
  22909. * @param {boolean} loop defines if you want animation to loop (off by default)
  22910. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22911. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22912. * @returns the list of animatables created for all nodes
  22913. */
  22914. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22915. var children = target.getDescendants(directDescendantsOnly);
  22916. var result = [];
  22917. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22918. var child = children_1[_i];
  22919. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22920. }
  22921. return result;
  22922. };
  22923. Scene.prototype.getAnimatableByTarget = function (target) {
  22924. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22925. if (this._activeAnimatables[index].target === target) {
  22926. return this._activeAnimatables[index];
  22927. }
  22928. }
  22929. return null;
  22930. };
  22931. Object.defineProperty(Scene.prototype, "animatables", {
  22932. get: function () {
  22933. return this._activeAnimatables;
  22934. },
  22935. enumerable: true,
  22936. configurable: true
  22937. });
  22938. /**
  22939. * Will stop the animation of the given target
  22940. * @param target - the target
  22941. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22942. * @see beginAnimation
  22943. */
  22944. Scene.prototype.stopAnimation = function (target, animationName) {
  22945. var animatable = this.getAnimatableByTarget(target);
  22946. if (animatable) {
  22947. animatable.stop(animationName);
  22948. }
  22949. };
  22950. /**
  22951. * Stops and removes all animations that have been applied to the scene
  22952. */
  22953. Scene.prototype.stopAllAnimations = function () {
  22954. if (this._activeAnimatables) {
  22955. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22956. this._activeAnimatables[i].stop();
  22957. }
  22958. this._activeAnimatables = [];
  22959. }
  22960. };
  22961. Scene.prototype._animate = function () {
  22962. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22963. return;
  22964. }
  22965. // Getting time
  22966. var now = BABYLON.Tools.Now;
  22967. if (!this._animationTimeLast) {
  22968. if (this._pendingData.length > 0) {
  22969. return;
  22970. }
  22971. this._animationTimeLast = now;
  22972. }
  22973. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22974. this._animationTime += deltaTime;
  22975. this._animationTimeLast = now;
  22976. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22977. this._activeAnimatables[index]._animate(this._animationTime);
  22978. }
  22979. };
  22980. // Matrix
  22981. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22982. this._useAlternateCameraConfiguration = active;
  22983. };
  22984. Scene.prototype.getViewMatrix = function () {
  22985. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22986. };
  22987. Scene.prototype.getProjectionMatrix = function () {
  22988. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22989. };
  22990. Scene.prototype.getTransformMatrix = function () {
  22991. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22992. };
  22993. Scene.prototype.setTransformMatrix = function (view, projection) {
  22994. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22995. return;
  22996. }
  22997. this._viewUpdateFlag = view.updateFlag;
  22998. this._projectionUpdateFlag = projection.updateFlag;
  22999. this._viewMatrix = view;
  23000. this._projectionMatrix = projection;
  23001. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23002. // Update frustum
  23003. if (!this._frustumPlanes) {
  23004. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23005. }
  23006. else {
  23007. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23008. }
  23009. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23010. var otherCamera = this.activeCamera._alternateCamera;
  23011. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23012. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23013. }
  23014. if (this._sceneUbo.useUbo) {
  23015. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23016. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23017. this._sceneUbo.update();
  23018. }
  23019. };
  23020. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23021. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23022. return;
  23023. }
  23024. this._alternateViewUpdateFlag = view.updateFlag;
  23025. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23026. this._alternateViewMatrix = view;
  23027. this._alternateProjectionMatrix = projection;
  23028. if (!this._alternateTransformMatrix) {
  23029. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23030. }
  23031. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23032. if (!this._alternateSceneUbo) {
  23033. this._createAlternateUbo();
  23034. }
  23035. if (this._alternateSceneUbo.useUbo) {
  23036. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23037. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23038. this._alternateSceneUbo.update();
  23039. }
  23040. };
  23041. Scene.prototype.getSceneUniformBuffer = function () {
  23042. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23043. };
  23044. // Methods
  23045. Scene.prototype.getUniqueId = function () {
  23046. var result = Scene._uniqueIdCounter;
  23047. Scene._uniqueIdCounter++;
  23048. return result;
  23049. };
  23050. Scene.prototype.addMesh = function (newMesh) {
  23051. this.meshes.push(newMesh);
  23052. //notify the collision coordinator
  23053. if (this.collisionCoordinator) {
  23054. this.collisionCoordinator.onMeshAdded(newMesh);
  23055. }
  23056. newMesh._resyncLightSources();
  23057. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23058. };
  23059. Scene.prototype.removeMesh = function (toRemove) {
  23060. var index = this.meshes.indexOf(toRemove);
  23061. if (index !== -1) {
  23062. // Remove from the scene if mesh found
  23063. this.meshes.splice(index, 1);
  23064. }
  23065. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23066. return index;
  23067. };
  23068. Scene.prototype.addTransformNode = function (newTransformNode) {
  23069. this.transformNodes.push(newTransformNode);
  23070. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23071. };
  23072. Scene.prototype.removeTransformNode = function (toRemove) {
  23073. var index = this.transformNodes.indexOf(toRemove);
  23074. if (index !== -1) {
  23075. // Remove from the scene if found
  23076. this.transformNodes.splice(index, 1);
  23077. }
  23078. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23079. return index;
  23080. };
  23081. Scene.prototype.removeSkeleton = function (toRemove) {
  23082. var index = this.skeletons.indexOf(toRemove);
  23083. if (index !== -1) {
  23084. // Remove from the scene if found
  23085. this.skeletons.splice(index, 1);
  23086. }
  23087. return index;
  23088. };
  23089. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23090. var index = this.morphTargetManagers.indexOf(toRemove);
  23091. if (index !== -1) {
  23092. // Remove from the scene if found
  23093. this.morphTargetManagers.splice(index, 1);
  23094. }
  23095. return index;
  23096. };
  23097. Scene.prototype.removeLight = function (toRemove) {
  23098. var index = this.lights.indexOf(toRemove);
  23099. if (index !== -1) {
  23100. // Remove from meshes
  23101. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23102. var mesh = _a[_i];
  23103. mesh._removeLightSource(toRemove);
  23104. }
  23105. // Remove from the scene if mesh found
  23106. this.lights.splice(index, 1);
  23107. this.sortLightsByPriority();
  23108. }
  23109. this.onLightRemovedObservable.notifyObservers(toRemove);
  23110. return index;
  23111. };
  23112. Scene.prototype.removeCamera = function (toRemove) {
  23113. var index = this.cameras.indexOf(toRemove);
  23114. if (index !== -1) {
  23115. // Remove from the scene if mesh found
  23116. this.cameras.splice(index, 1);
  23117. }
  23118. // Remove from activeCameras
  23119. var index2 = this.activeCameras.indexOf(toRemove);
  23120. if (index2 !== -1) {
  23121. // Remove from the scene if mesh found
  23122. this.activeCameras.splice(index2, 1);
  23123. }
  23124. // Reset the activeCamera
  23125. if (this.activeCamera === toRemove) {
  23126. if (this.cameras.length > 0) {
  23127. this.activeCamera = this.cameras[0];
  23128. }
  23129. else {
  23130. this.activeCamera = null;
  23131. }
  23132. }
  23133. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23134. return index;
  23135. };
  23136. Scene.prototype.removeParticleSystem = function (toRemove) {
  23137. var index = this.particleSystems.indexOf(toRemove);
  23138. if (index !== -1) {
  23139. this.particleSystems.splice(index, 1);
  23140. }
  23141. return index;
  23142. };
  23143. ;
  23144. Scene.prototype.removeAnimation = function (toRemove) {
  23145. var index = this.animations.indexOf(toRemove);
  23146. if (index !== -1) {
  23147. this.animations.splice(index, 1);
  23148. }
  23149. return index;
  23150. };
  23151. ;
  23152. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23153. var index = this.multiMaterials.indexOf(toRemove);
  23154. if (index !== -1) {
  23155. this.multiMaterials.splice(index, 1);
  23156. }
  23157. return index;
  23158. };
  23159. ;
  23160. Scene.prototype.removeMaterial = function (toRemove) {
  23161. var index = this.materials.indexOf(toRemove);
  23162. if (index !== -1) {
  23163. this.materials.splice(index, 1);
  23164. }
  23165. return index;
  23166. };
  23167. ;
  23168. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23169. var index = this.lensFlareSystems.indexOf(toRemove);
  23170. if (index !== -1) {
  23171. this.lensFlareSystems.splice(index, 1);
  23172. }
  23173. return index;
  23174. };
  23175. ;
  23176. Scene.prototype.removeActionManager = function (toRemove) {
  23177. var index = this._actionManagers.indexOf(toRemove);
  23178. if (index !== -1) {
  23179. this._actionManagers.splice(index, 1);
  23180. }
  23181. return index;
  23182. };
  23183. ;
  23184. Scene.prototype.addLight = function (newLight) {
  23185. this.lights.push(newLight);
  23186. this.sortLightsByPriority();
  23187. // Add light to all meshes (To support if the light is removed and then readded)
  23188. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23189. var mesh = _a[_i];
  23190. if (mesh._lightSources.indexOf(newLight) === -1) {
  23191. mesh._lightSources.push(newLight);
  23192. mesh._resyncLightSources();
  23193. }
  23194. }
  23195. this.onNewLightAddedObservable.notifyObservers(newLight);
  23196. };
  23197. Scene.prototype.sortLightsByPriority = function () {
  23198. if (this.requireLightSorting) {
  23199. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23200. }
  23201. };
  23202. Scene.prototype.addCamera = function (newCamera) {
  23203. this.cameras.push(newCamera);
  23204. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23205. };
  23206. Scene.prototype.addSkeleton = function (newSkeleton) {
  23207. this.skeletons.push(newSkeleton);
  23208. };
  23209. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23210. this.particleSystems.push(newParticleSystem);
  23211. };
  23212. Scene.prototype.addAnimation = function (newAnimation) {
  23213. this.animations.push(newAnimation);
  23214. };
  23215. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23216. this.multiMaterials.push(newMultiMaterial);
  23217. };
  23218. Scene.prototype.addMaterial = function (newMaterial) {
  23219. this.materials.push(newMaterial);
  23220. };
  23221. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23222. this.morphTargetManagers.push(newMorphTargetManager);
  23223. };
  23224. Scene.prototype.addGeometry = function (newGeometrie) {
  23225. this._geometries.push(newGeometrie);
  23226. };
  23227. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23228. this.lensFlareSystems.push(newLensFlareSystem);
  23229. };
  23230. Scene.prototype.addActionManager = function (newActionManager) {
  23231. this._actionManagers.push(newActionManager);
  23232. };
  23233. /**
  23234. * Switch active camera
  23235. * @param {Camera} newCamera - new active camera
  23236. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23237. */
  23238. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23239. if (attachControl === void 0) { attachControl = true; }
  23240. var canvas = this._engine.getRenderingCanvas();
  23241. if (!canvas) {
  23242. return;
  23243. }
  23244. if (this.activeCamera) {
  23245. this.activeCamera.detachControl(canvas);
  23246. }
  23247. this.activeCamera = newCamera;
  23248. if (attachControl) {
  23249. newCamera.attachControl(canvas);
  23250. }
  23251. };
  23252. /**
  23253. * sets the active camera of the scene using its ID
  23254. * @param {string} id - the camera's ID
  23255. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23256. * @see activeCamera
  23257. */
  23258. Scene.prototype.setActiveCameraByID = function (id) {
  23259. var camera = this.getCameraByID(id);
  23260. if (camera) {
  23261. this.activeCamera = camera;
  23262. return camera;
  23263. }
  23264. return null;
  23265. };
  23266. /**
  23267. * sets the active camera of the scene using its name
  23268. * @param {string} name - the camera's name
  23269. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23270. * @see activeCamera
  23271. */
  23272. Scene.prototype.setActiveCameraByName = function (name) {
  23273. var camera = this.getCameraByName(name);
  23274. if (camera) {
  23275. this.activeCamera = camera;
  23276. return camera;
  23277. }
  23278. return null;
  23279. };
  23280. /**
  23281. * get an animation group using its name
  23282. * @param {string} the material's name
  23283. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23284. */
  23285. Scene.prototype.getAnimationGroupByName = function (name) {
  23286. for (var index = 0; index < this.animationGroups.length; index++) {
  23287. if (this.animationGroups[index].name === name) {
  23288. return this.animationGroups[index];
  23289. }
  23290. }
  23291. return null;
  23292. };
  23293. /**
  23294. * get a material using its id
  23295. * @param {string} the material's ID
  23296. * @return {BABYLON.Material|null} the material or null if none found.
  23297. */
  23298. Scene.prototype.getMaterialByID = function (id) {
  23299. for (var index = 0; index < this.materials.length; index++) {
  23300. if (this.materials[index].id === id) {
  23301. return this.materials[index];
  23302. }
  23303. }
  23304. return null;
  23305. };
  23306. /**
  23307. * get a material using its name
  23308. * @param {string} the material's name
  23309. * @return {BABYLON.Material|null} the material or null if none found.
  23310. */
  23311. Scene.prototype.getMaterialByName = function (name) {
  23312. for (var index = 0; index < this.materials.length; index++) {
  23313. if (this.materials[index].name === name) {
  23314. return this.materials[index];
  23315. }
  23316. }
  23317. return null;
  23318. };
  23319. Scene.prototype.getLensFlareSystemByName = function (name) {
  23320. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23321. if (this.lensFlareSystems[index].name === name) {
  23322. return this.lensFlareSystems[index];
  23323. }
  23324. }
  23325. return null;
  23326. };
  23327. Scene.prototype.getLensFlareSystemByID = function (id) {
  23328. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23329. if (this.lensFlareSystems[index].id === id) {
  23330. return this.lensFlareSystems[index];
  23331. }
  23332. }
  23333. return null;
  23334. };
  23335. Scene.prototype.getCameraByID = function (id) {
  23336. for (var index = 0; index < this.cameras.length; index++) {
  23337. if (this.cameras[index].id === id) {
  23338. return this.cameras[index];
  23339. }
  23340. }
  23341. return null;
  23342. };
  23343. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23344. for (var index = 0; index < this.cameras.length; index++) {
  23345. if (this.cameras[index].uniqueId === uniqueId) {
  23346. return this.cameras[index];
  23347. }
  23348. }
  23349. return null;
  23350. };
  23351. /**
  23352. * get a camera using its name
  23353. * @param {string} the camera's name
  23354. * @return {BABYLON.Camera|null} the camera or null if none found.
  23355. */
  23356. Scene.prototype.getCameraByName = function (name) {
  23357. for (var index = 0; index < this.cameras.length; index++) {
  23358. if (this.cameras[index].name === name) {
  23359. return this.cameras[index];
  23360. }
  23361. }
  23362. return null;
  23363. };
  23364. /**
  23365. * get a bone using its id
  23366. * @param {string} the bone's id
  23367. * @return {BABYLON.Bone|null} the bone or null if not found
  23368. */
  23369. Scene.prototype.getBoneByID = function (id) {
  23370. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23371. var skeleton = this.skeletons[skeletonIndex];
  23372. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23373. if (skeleton.bones[boneIndex].id === id) {
  23374. return skeleton.bones[boneIndex];
  23375. }
  23376. }
  23377. }
  23378. return null;
  23379. };
  23380. /**
  23381. * get a bone using its id
  23382. * @param {string} the bone's name
  23383. * @return {BABYLON.Bone|null} the bone or null if not found
  23384. */
  23385. Scene.prototype.getBoneByName = function (name) {
  23386. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23387. var skeleton = this.skeletons[skeletonIndex];
  23388. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23389. if (skeleton.bones[boneIndex].name === name) {
  23390. return skeleton.bones[boneIndex];
  23391. }
  23392. }
  23393. }
  23394. return null;
  23395. };
  23396. /**
  23397. * get a light node using its name
  23398. * @param {string} the light's name
  23399. * @return {BABYLON.Light|null} the light or null if none found.
  23400. */
  23401. Scene.prototype.getLightByName = function (name) {
  23402. for (var index = 0; index < this.lights.length; index++) {
  23403. if (this.lights[index].name === name) {
  23404. return this.lights[index];
  23405. }
  23406. }
  23407. return null;
  23408. };
  23409. /**
  23410. * get a light node using its ID
  23411. * @param {string} the light's id
  23412. * @return {BABYLON.Light|null} the light or null if none found.
  23413. */
  23414. Scene.prototype.getLightByID = function (id) {
  23415. for (var index = 0; index < this.lights.length; index++) {
  23416. if (this.lights[index].id === id) {
  23417. return this.lights[index];
  23418. }
  23419. }
  23420. return null;
  23421. };
  23422. /**
  23423. * get a light node using its scene-generated unique ID
  23424. * @param {number} the light's unique id
  23425. * @return {BABYLON.Light|null} the light or null if none found.
  23426. */
  23427. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23428. for (var index = 0; index < this.lights.length; index++) {
  23429. if (this.lights[index].uniqueId === uniqueId) {
  23430. return this.lights[index];
  23431. }
  23432. }
  23433. return null;
  23434. };
  23435. /**
  23436. * get a particle system by id
  23437. * @param id {number} the particle system id
  23438. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23439. */
  23440. Scene.prototype.getParticleSystemByID = function (id) {
  23441. for (var index = 0; index < this.particleSystems.length; index++) {
  23442. if (this.particleSystems[index].id === id) {
  23443. return this.particleSystems[index];
  23444. }
  23445. }
  23446. return null;
  23447. };
  23448. /**
  23449. * get a geometry using its ID
  23450. * @param {string} the geometry's id
  23451. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23452. */
  23453. Scene.prototype.getGeometryByID = function (id) {
  23454. for (var index = 0; index < this._geometries.length; index++) {
  23455. if (this._geometries[index].id === id) {
  23456. return this._geometries[index];
  23457. }
  23458. }
  23459. return null;
  23460. };
  23461. /**
  23462. * add a new geometry to this scene.
  23463. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23464. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23465. * @return {boolean} was the geometry added or not
  23466. */
  23467. Scene.prototype.pushGeometry = function (geometry, force) {
  23468. if (!force && this.getGeometryByID(geometry.id)) {
  23469. return false;
  23470. }
  23471. this._geometries.push(geometry);
  23472. //notify the collision coordinator
  23473. if (this.collisionCoordinator) {
  23474. this.collisionCoordinator.onGeometryAdded(geometry);
  23475. }
  23476. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23477. return true;
  23478. };
  23479. /**
  23480. * Removes an existing geometry
  23481. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23482. * @return {boolean} was the geometry removed or not
  23483. */
  23484. Scene.prototype.removeGeometry = function (geometry) {
  23485. var index = this._geometries.indexOf(geometry);
  23486. if (index > -1) {
  23487. this._geometries.splice(index, 1);
  23488. //notify the collision coordinator
  23489. if (this.collisionCoordinator) {
  23490. this.collisionCoordinator.onGeometryDeleted(geometry);
  23491. }
  23492. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23493. return true;
  23494. }
  23495. return false;
  23496. };
  23497. Scene.prototype.getGeometries = function () {
  23498. return this._geometries;
  23499. };
  23500. /**
  23501. * Get the first added mesh found of a given ID
  23502. * @param {string} id - the id to search for
  23503. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23504. */
  23505. Scene.prototype.getMeshByID = function (id) {
  23506. for (var index = 0; index < this.meshes.length; index++) {
  23507. if (this.meshes[index].id === id) {
  23508. return this.meshes[index];
  23509. }
  23510. }
  23511. return null;
  23512. };
  23513. Scene.prototype.getMeshesByID = function (id) {
  23514. return this.meshes.filter(function (m) {
  23515. return m.id === id;
  23516. });
  23517. };
  23518. /**
  23519. * Get the first added transform node found of a given ID
  23520. * @param {string} id - the id to search for
  23521. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23522. */
  23523. Scene.prototype.getTransformNodeByID = function (id) {
  23524. for (var index = 0; index < this.transformNodes.length; index++) {
  23525. if (this.transformNodes[index].id === id) {
  23526. return this.transformNodes[index];
  23527. }
  23528. }
  23529. return null;
  23530. };
  23531. Scene.prototype.getTransformNodesByID = function (id) {
  23532. return this.transformNodes.filter(function (m) {
  23533. return m.id === id;
  23534. });
  23535. };
  23536. /**
  23537. * Get a mesh with its auto-generated unique id
  23538. * @param {number} uniqueId - the unique id to search for
  23539. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23540. */
  23541. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23542. for (var index = 0; index < this.meshes.length; index++) {
  23543. if (this.meshes[index].uniqueId === uniqueId) {
  23544. return this.meshes[index];
  23545. }
  23546. }
  23547. return null;
  23548. };
  23549. /**
  23550. * Get a the last added mesh found of a given ID
  23551. * @param {string} id - the id to search for
  23552. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23553. */
  23554. Scene.prototype.getLastMeshByID = function (id) {
  23555. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23556. if (this.meshes[index].id === id) {
  23557. return this.meshes[index];
  23558. }
  23559. }
  23560. return null;
  23561. };
  23562. /**
  23563. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23564. * @param {string} id - the id to search for
  23565. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23566. */
  23567. Scene.prototype.getLastEntryByID = function (id) {
  23568. var index;
  23569. for (index = this.meshes.length - 1; index >= 0; index--) {
  23570. if (this.meshes[index].id === id) {
  23571. return this.meshes[index];
  23572. }
  23573. }
  23574. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23575. if (this.transformNodes[index].id === id) {
  23576. return this.transformNodes[index];
  23577. }
  23578. }
  23579. for (index = this.cameras.length - 1; index >= 0; index--) {
  23580. if (this.cameras[index].id === id) {
  23581. return this.cameras[index];
  23582. }
  23583. }
  23584. for (index = this.lights.length - 1; index >= 0; index--) {
  23585. if (this.lights[index].id === id) {
  23586. return this.lights[index];
  23587. }
  23588. }
  23589. return null;
  23590. };
  23591. Scene.prototype.getNodeByID = function (id) {
  23592. var mesh = this.getMeshByID(id);
  23593. if (mesh) {
  23594. return mesh;
  23595. }
  23596. var light = this.getLightByID(id);
  23597. if (light) {
  23598. return light;
  23599. }
  23600. var camera = this.getCameraByID(id);
  23601. if (camera) {
  23602. return camera;
  23603. }
  23604. var bone = this.getBoneByID(id);
  23605. return bone;
  23606. };
  23607. Scene.prototype.getNodeByName = function (name) {
  23608. var mesh = this.getMeshByName(name);
  23609. if (mesh) {
  23610. return mesh;
  23611. }
  23612. var light = this.getLightByName(name);
  23613. if (light) {
  23614. return light;
  23615. }
  23616. var camera = this.getCameraByName(name);
  23617. if (camera) {
  23618. return camera;
  23619. }
  23620. var bone = this.getBoneByName(name);
  23621. return bone;
  23622. };
  23623. Scene.prototype.getMeshByName = function (name) {
  23624. for (var index = 0; index < this.meshes.length; index++) {
  23625. if (this.meshes[index].name === name) {
  23626. return this.meshes[index];
  23627. }
  23628. }
  23629. return null;
  23630. };
  23631. Scene.prototype.getTransformNodeByName = function (name) {
  23632. for (var index = 0; index < this.transformNodes.length; index++) {
  23633. if (this.transformNodes[index].name === name) {
  23634. return this.transformNodes[index];
  23635. }
  23636. }
  23637. return null;
  23638. };
  23639. Scene.prototype.getSoundByName = function (name) {
  23640. var index;
  23641. if (BABYLON.AudioEngine) {
  23642. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23643. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23644. return this.mainSoundTrack.soundCollection[index];
  23645. }
  23646. }
  23647. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23648. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23649. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23650. return this.soundTracks[sdIndex].soundCollection[index];
  23651. }
  23652. }
  23653. }
  23654. }
  23655. return null;
  23656. };
  23657. Scene.prototype.getLastSkeletonByID = function (id) {
  23658. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23659. if (this.skeletons[index].id === id) {
  23660. return this.skeletons[index];
  23661. }
  23662. }
  23663. return null;
  23664. };
  23665. Scene.prototype.getSkeletonById = function (id) {
  23666. for (var index = 0; index < this.skeletons.length; index++) {
  23667. if (this.skeletons[index].id === id) {
  23668. return this.skeletons[index];
  23669. }
  23670. }
  23671. return null;
  23672. };
  23673. Scene.prototype.getSkeletonByName = function (name) {
  23674. for (var index = 0; index < this.skeletons.length; index++) {
  23675. if (this.skeletons[index].name === name) {
  23676. return this.skeletons[index];
  23677. }
  23678. }
  23679. return null;
  23680. };
  23681. Scene.prototype.getMorphTargetManagerById = function (id) {
  23682. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23683. if (this.morphTargetManagers[index].uniqueId === id) {
  23684. return this.morphTargetManagers[index];
  23685. }
  23686. }
  23687. return null;
  23688. };
  23689. Scene.prototype.isActiveMesh = function (mesh) {
  23690. return (this._activeMeshes.indexOf(mesh) !== -1);
  23691. };
  23692. /**
  23693. * Return a the first highlight layer of the scene with a given name.
  23694. * @param name The name of the highlight layer to look for.
  23695. * @return The highlight layer if found otherwise null.
  23696. */
  23697. Scene.prototype.getHighlightLayerByName = function (name) {
  23698. for (var index = 0; index < this.effectLayers.length; index++) {
  23699. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23700. return this.effectLayers[index];
  23701. }
  23702. }
  23703. return null;
  23704. };
  23705. /**
  23706. * Return a the first highlight layer of the scene with a given name.
  23707. * @param name The name of the highlight layer to look for.
  23708. * @return The highlight layer if found otherwise null.
  23709. */
  23710. Scene.prototype.getGlowLayerByName = function (name) {
  23711. for (var index = 0; index < this.effectLayers.length; index++) {
  23712. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23713. return this.effectLayers[index];
  23714. }
  23715. }
  23716. return null;
  23717. };
  23718. Object.defineProperty(Scene.prototype, "uid", {
  23719. /**
  23720. * Return a unique id as a string which can serve as an identifier for the scene
  23721. */
  23722. get: function () {
  23723. if (!this._uid) {
  23724. this._uid = BABYLON.Tools.RandomId();
  23725. }
  23726. return this._uid;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. /**
  23732. * Add an externaly attached data from its key.
  23733. * This method call will fail and return false, if such key already exists.
  23734. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23735. * @param key the unique key that identifies the data
  23736. * @param data the data object to associate to the key for this Engine instance
  23737. * @return true if no such key were already present and the data was added successfully, false otherwise
  23738. */
  23739. Scene.prototype.addExternalData = function (key, data) {
  23740. if (!this._externalData) {
  23741. this._externalData = new BABYLON.StringDictionary();
  23742. }
  23743. return this._externalData.add(key, data);
  23744. };
  23745. /**
  23746. * Get an externaly attached data from its key
  23747. * @param key the unique key that identifies the data
  23748. * @return the associated data, if present (can be null), or undefined if not present
  23749. */
  23750. Scene.prototype.getExternalData = function (key) {
  23751. if (!this._externalData) {
  23752. return null;
  23753. }
  23754. return this._externalData.get(key);
  23755. };
  23756. /**
  23757. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23758. * @param key the unique key that identifies the data
  23759. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23760. * @return the associated data, can be null if the factory returned null.
  23761. */
  23762. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23763. if (!this._externalData) {
  23764. this._externalData = new BABYLON.StringDictionary();
  23765. }
  23766. return this._externalData.getOrAddWithFactory(key, factory);
  23767. };
  23768. /**
  23769. * Remove an externaly attached data from the Engine instance
  23770. * @param key the unique key that identifies the data
  23771. * @return true if the data was successfully removed, false if it doesn't exist
  23772. */
  23773. Scene.prototype.removeExternalData = function (key) {
  23774. return this._externalData.remove(key);
  23775. };
  23776. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23777. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23778. if (mesh.showSubMeshesBoundingBox) {
  23779. var boundingInfo = subMesh.getBoundingInfo();
  23780. if (boundingInfo !== null && boundingInfo !== undefined) {
  23781. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23782. }
  23783. }
  23784. var material = subMesh.getMaterial();
  23785. if (material !== null && material !== undefined) {
  23786. // Render targets
  23787. if (material.getRenderTargetTextures !== undefined) {
  23788. if (this._processedMaterials.indexOf(material) === -1) {
  23789. this._processedMaterials.push(material);
  23790. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23791. }
  23792. }
  23793. // Dispatch
  23794. this._activeIndices.addCount(subMesh.indexCount, false);
  23795. this._renderingManager.dispatch(subMesh, mesh, material);
  23796. }
  23797. }
  23798. };
  23799. Scene.prototype._isInIntermediateRendering = function () {
  23800. return this._intermediateRendering;
  23801. };
  23802. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23803. this._activeMeshCandidateProvider = provider;
  23804. };
  23805. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23806. return this._activeMeshCandidateProvider;
  23807. };
  23808. /**
  23809. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23810. */
  23811. Scene.prototype.freezeActiveMeshes = function () {
  23812. this._evaluateActiveMeshes();
  23813. this._activeMeshesFrozen = true;
  23814. return this;
  23815. };
  23816. /**
  23817. * Use this function to restart evaluating active meshes on every frame
  23818. */
  23819. Scene.prototype.unfreezeActiveMeshes = function () {
  23820. this._activeMeshesFrozen = false;
  23821. return this;
  23822. };
  23823. Scene.prototype._evaluateActiveMeshes = function () {
  23824. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23825. return;
  23826. }
  23827. if (!this.activeCamera) {
  23828. return;
  23829. }
  23830. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23831. this.activeCamera._activeMeshes.reset();
  23832. this._activeMeshes.reset();
  23833. this._renderingManager.reset();
  23834. this._processedMaterials.reset();
  23835. this._activeParticleSystems.reset();
  23836. this._activeSkeletons.reset();
  23837. this._softwareSkinnedMeshes.reset();
  23838. if (this._boundingBoxRenderer) {
  23839. this._boundingBoxRenderer.reset();
  23840. }
  23841. // Meshes
  23842. var meshes;
  23843. var len;
  23844. var checkIsEnabled = true;
  23845. // Determine mesh candidates
  23846. if (this._activeMeshCandidateProvider !== undefined) {
  23847. // Use _activeMeshCandidateProvider
  23848. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23849. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23850. if (meshes !== undefined) {
  23851. len = meshes.length;
  23852. }
  23853. else {
  23854. len = 0;
  23855. }
  23856. }
  23857. else if (this._selectionOctree !== undefined) {
  23858. // Octree
  23859. var selection = this._selectionOctree.select(this._frustumPlanes);
  23860. meshes = selection.data;
  23861. len = selection.length;
  23862. }
  23863. else {
  23864. // Full scene traversal
  23865. len = this.meshes.length;
  23866. meshes = this.meshes;
  23867. }
  23868. // Check each mesh
  23869. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23870. mesh = meshes[meshIndex];
  23871. if (mesh.isBlocked) {
  23872. continue;
  23873. }
  23874. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23875. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23876. continue;
  23877. }
  23878. mesh.computeWorldMatrix();
  23879. // Intersections
  23880. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23881. this._meshesForIntersections.pushNoDuplicate(mesh);
  23882. }
  23883. // Switch to current LOD
  23884. meshLOD = mesh.getLOD(this.activeCamera);
  23885. if (meshLOD === undefined || meshLOD === null) {
  23886. continue;
  23887. }
  23888. mesh._preActivate();
  23889. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23890. this._activeMeshes.push(mesh);
  23891. this.activeCamera._activeMeshes.push(mesh);
  23892. mesh._activate(this._renderId);
  23893. if (meshLOD !== mesh) {
  23894. meshLOD._activate(this._renderId);
  23895. }
  23896. this._activeMesh(mesh, meshLOD);
  23897. }
  23898. }
  23899. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23900. // Particle systems
  23901. if (this.particlesEnabled) {
  23902. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23903. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23904. var particleSystem = this.particleSystems[particleIndex];
  23905. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23906. continue;
  23907. }
  23908. var emitter = particleSystem.emitter;
  23909. if (!emitter.position || emitter.isEnabled()) {
  23910. this._activeParticleSystems.push(particleSystem);
  23911. particleSystem.animate();
  23912. this._renderingManager.dispatchParticles(particleSystem);
  23913. }
  23914. }
  23915. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23916. }
  23917. };
  23918. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23919. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23920. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23921. mesh.skeleton.prepare();
  23922. }
  23923. if (!mesh.computeBonesUsingShaders) {
  23924. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23925. }
  23926. }
  23927. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23928. var boundingInfo = sourceMesh.getBoundingInfo();
  23929. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23930. }
  23931. if (mesh !== undefined && mesh !== null
  23932. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23933. // Submeshes Octrees
  23934. var len;
  23935. var subMeshes;
  23936. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23937. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23938. len = intersections.length;
  23939. subMeshes = intersections.data;
  23940. }
  23941. else {
  23942. subMeshes = mesh.subMeshes;
  23943. len = subMeshes.length;
  23944. }
  23945. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23946. subMesh = subMeshes[subIndex];
  23947. this._evaluateSubMesh(subMesh, mesh);
  23948. }
  23949. }
  23950. };
  23951. Scene.prototype.updateTransformMatrix = function (force) {
  23952. if (!this.activeCamera) {
  23953. return;
  23954. }
  23955. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23956. };
  23957. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23958. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23959. };
  23960. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23961. if (camera && camera._skipRendering) {
  23962. return;
  23963. }
  23964. var engine = this._engine;
  23965. this.activeCamera = camera;
  23966. if (!this.activeCamera)
  23967. throw new Error("Active camera not set");
  23968. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23969. // Viewport
  23970. engine.setViewport(this.activeCamera.viewport);
  23971. // Camera
  23972. this.resetCachedMaterial();
  23973. this._renderId++;
  23974. this.updateTransformMatrix();
  23975. if (camera._alternateCamera) {
  23976. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23977. this._alternateRendering = true;
  23978. }
  23979. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23980. // Meshes
  23981. this._evaluateActiveMeshes();
  23982. // Software skinning
  23983. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23984. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23985. mesh.applySkeleton(mesh.skeleton);
  23986. }
  23987. // Render targets
  23988. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23989. var needsRestoreFrameBuffer = false;
  23990. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23991. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23992. }
  23993. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23994. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23995. }
  23996. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23997. this._intermediateRendering = true;
  23998. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23999. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24000. var renderTarget = this._renderTargets.data[renderIndex];
  24001. if (renderTarget._shouldRender()) {
  24002. this._renderId++;
  24003. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24004. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24005. }
  24006. }
  24007. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24008. this._intermediateRendering = false;
  24009. this._renderId++;
  24010. needsRestoreFrameBuffer = true; // Restore back buffer
  24011. }
  24012. // Render EffecttLayer Texture
  24013. var stencilState = this._engine.getStencilBuffer();
  24014. var renderEffects = false;
  24015. var needStencil = false;
  24016. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24017. this._intermediateRendering = true;
  24018. for (var i = 0; i < this.effectLayers.length; i++) {
  24019. var effectLayer = this.effectLayers[i];
  24020. if (effectLayer.shouldRender() &&
  24021. (!effectLayer.camera ||
  24022. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24023. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24024. renderEffects = true;
  24025. needStencil = needStencil || effectLayer.needStencil();
  24026. var renderTarget = effectLayer._mainTexture;
  24027. if (renderTarget._shouldRender()) {
  24028. this._renderId++;
  24029. renderTarget.render(false, false);
  24030. needsRestoreFrameBuffer = true;
  24031. }
  24032. }
  24033. }
  24034. this._intermediateRendering = false;
  24035. this._renderId++;
  24036. }
  24037. if (needsRestoreFrameBuffer) {
  24038. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24039. }
  24040. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24041. // Prepare Frame
  24042. this.postProcessManager._prepareFrame();
  24043. // Backgrounds
  24044. var layerIndex;
  24045. var layer;
  24046. if (this.layers.length) {
  24047. engine.setDepthBuffer(false);
  24048. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24049. layer = this.layers[layerIndex];
  24050. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24051. layer.render();
  24052. }
  24053. }
  24054. engine.setDepthBuffer(true);
  24055. }
  24056. // Activate effect Layer stencil
  24057. if (needStencil) {
  24058. this._engine.setStencilBuffer(true);
  24059. }
  24060. // Render
  24061. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24062. this._renderingManager.render(null, null, true, true);
  24063. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24064. // Restore effect Layer stencil
  24065. if (needStencil) {
  24066. this._engine.setStencilBuffer(stencilState);
  24067. }
  24068. // Bounding boxes
  24069. if (this._boundingBoxRenderer) {
  24070. this._boundingBoxRenderer.render();
  24071. }
  24072. // Lens flares
  24073. if (this.lensFlaresEnabled) {
  24074. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24075. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24076. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24077. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24078. lensFlareSystem.render();
  24079. }
  24080. }
  24081. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24082. }
  24083. // Foregrounds
  24084. if (this.layers.length) {
  24085. engine.setDepthBuffer(false);
  24086. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24087. layer = this.layers[layerIndex];
  24088. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24089. layer.render();
  24090. }
  24091. }
  24092. engine.setDepthBuffer(true);
  24093. }
  24094. // Effect Layer
  24095. if (renderEffects) {
  24096. engine.setDepthBuffer(false);
  24097. for (var i = 0; i < this.effectLayers.length; i++) {
  24098. if (this.effectLayers[i].shouldRender()) {
  24099. this.effectLayers[i].render();
  24100. }
  24101. }
  24102. engine.setDepthBuffer(true);
  24103. }
  24104. // Finalize frame
  24105. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24106. // Reset some special arrays
  24107. this._renderTargets.reset();
  24108. this._alternateRendering = false;
  24109. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24110. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24111. };
  24112. Scene.prototype._processSubCameras = function (camera) {
  24113. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24114. this._renderForCamera(camera);
  24115. return;
  24116. }
  24117. // rig cameras
  24118. for (var index = 0; index < camera._rigCameras.length; index++) {
  24119. this._renderForCamera(camera._rigCameras[index], camera);
  24120. }
  24121. this.activeCamera = camera;
  24122. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24123. };
  24124. Scene.prototype._checkIntersections = function () {
  24125. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24126. var sourceMesh = this._meshesForIntersections.data[index];
  24127. if (!sourceMesh.actionManager) {
  24128. continue;
  24129. }
  24130. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24131. var action = sourceMesh.actionManager.actions[actionIndex];
  24132. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24133. var parameters = action.getTriggerParameter();
  24134. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24135. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24136. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24137. if (areIntersecting && currentIntersectionInProgress === -1) {
  24138. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24139. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24140. sourceMesh._intersectionsInProgress.push(otherMesh);
  24141. }
  24142. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24143. sourceMesh._intersectionsInProgress.push(otherMesh);
  24144. }
  24145. }
  24146. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24147. //They intersected, and now they don't.
  24148. //is this trigger an exit trigger? execute an event.
  24149. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24150. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24151. }
  24152. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24153. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24154. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24155. }
  24156. }
  24157. }
  24158. }
  24159. }
  24160. };
  24161. Scene.prototype.render = function () {
  24162. if (this.isDisposed) {
  24163. return;
  24164. }
  24165. this._activeParticles.fetchNewFrame();
  24166. this._totalVertices.fetchNewFrame();
  24167. this._activeIndices.fetchNewFrame();
  24168. this._activeBones.fetchNewFrame();
  24169. this._meshesForIntersections.reset();
  24170. this.resetCachedMaterial();
  24171. this.onBeforeAnimationsObservable.notifyObservers(this);
  24172. // Actions
  24173. if (this.actionManager) {
  24174. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24175. }
  24176. //Simplification Queue
  24177. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24178. this.simplificationQueue.executeNext();
  24179. }
  24180. if (this._engine.isDeterministicLockStep()) {
  24181. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24182. var defaultFPS = (60.0 / 1000.0);
  24183. var defaultFrameTime = 1000 / 60; // frame time in MS
  24184. if (this._physicsEngine) {
  24185. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24186. }
  24187. var stepsTaken = 0;
  24188. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24189. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24190. internalSteps = Math.min(internalSteps, maxSubSteps);
  24191. do {
  24192. this.onBeforeStepObservable.notifyObservers(this);
  24193. // Animations
  24194. this._animationRatio = defaultFrameTime * defaultFPS;
  24195. this._animate();
  24196. this.onAfterAnimationsObservable.notifyObservers(this);
  24197. // Physics
  24198. if (this._physicsEngine) {
  24199. this.onBeforePhysicsObservable.notifyObservers(this);
  24200. this._physicsEngine._step(defaultFrameTime / 1000);
  24201. this.onAfterPhysicsObservable.notifyObservers(this);
  24202. }
  24203. this.onAfterStepObservable.notifyObservers(this);
  24204. this._currentStepId++;
  24205. stepsTaken++;
  24206. deltaTime -= defaultFrameTime;
  24207. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24208. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24209. }
  24210. else {
  24211. // Animations
  24212. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24213. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24214. this._animate();
  24215. this.onAfterAnimationsObservable.notifyObservers(this);
  24216. // Physics
  24217. if (this._physicsEngine) {
  24218. this.onBeforePhysicsObservable.notifyObservers(this);
  24219. this._physicsEngine._step(deltaTime / 1000.0);
  24220. this.onAfterPhysicsObservable.notifyObservers(this);
  24221. }
  24222. }
  24223. // update gamepad manager
  24224. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24225. this._gamepadManager._checkGamepadsStatus();
  24226. }
  24227. // Before render
  24228. this.onBeforeRenderObservable.notifyObservers(this);
  24229. // Update Cameras
  24230. if (this.activeCameras.length > 0) {
  24231. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24232. var camera = this.activeCameras[cameraIndex];
  24233. camera.update();
  24234. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24235. // rig cameras
  24236. for (var index = 0; index < camera._rigCameras.length; index++) {
  24237. camera._rigCameras[index].update();
  24238. }
  24239. }
  24240. }
  24241. }
  24242. else if (this.activeCamera) {
  24243. this.activeCamera.update();
  24244. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24245. // rig cameras
  24246. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24247. this.activeCamera._rigCameras[index].update();
  24248. }
  24249. }
  24250. }
  24251. // Customs render targets
  24252. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24253. var engine = this.getEngine();
  24254. var currentActiveCamera = this.activeCamera;
  24255. if (this.renderTargetsEnabled) {
  24256. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24257. this._intermediateRendering = true;
  24258. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24259. var renderTarget = this.customRenderTargets[customIndex];
  24260. if (renderTarget._shouldRender()) {
  24261. this._renderId++;
  24262. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24263. if (!this.activeCamera)
  24264. throw new Error("Active camera not set");
  24265. // Viewport
  24266. engine.setViewport(this.activeCamera.viewport);
  24267. // Camera
  24268. this.updateTransformMatrix();
  24269. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24270. }
  24271. }
  24272. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24273. this._intermediateRendering = false;
  24274. this._renderId++;
  24275. }
  24276. // Restore back buffer
  24277. if (this.customRenderTargets.length > 0) {
  24278. engine.restoreDefaultFramebuffer();
  24279. }
  24280. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24281. this.activeCamera = currentActiveCamera;
  24282. // Procedural textures
  24283. if (this.proceduralTexturesEnabled) {
  24284. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24285. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24286. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24287. if (proceduralTexture._shouldRender()) {
  24288. proceduralTexture.render();
  24289. }
  24290. }
  24291. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24292. }
  24293. // Clear
  24294. if (this.autoClearDepthAndStencil || this.autoClear) {
  24295. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24296. }
  24297. // Shadows
  24298. if (this.shadowsEnabled) {
  24299. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24300. var light = this.lights[lightIndex];
  24301. var shadowGenerator = light.getShadowGenerator();
  24302. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24303. var shadowMap = (shadowGenerator.getShadowMap());
  24304. if (this.textures.indexOf(shadowMap) !== -1) {
  24305. this._renderTargets.push(shadowMap);
  24306. }
  24307. }
  24308. }
  24309. }
  24310. // Depth renderer
  24311. for (var key in this._depthRenderer) {
  24312. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24313. }
  24314. // Geometry renderer
  24315. if (this._geometryBufferRenderer) {
  24316. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24317. }
  24318. // RenderPipeline
  24319. if (this._postProcessRenderPipelineManager) {
  24320. this._postProcessRenderPipelineManager.update();
  24321. }
  24322. // Multi-cameras?
  24323. if (this.activeCameras.length > 0) {
  24324. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24325. if (cameraIndex > 0) {
  24326. this._engine.clear(null, false, true, true);
  24327. }
  24328. this._processSubCameras(this.activeCameras[cameraIndex]);
  24329. }
  24330. }
  24331. else {
  24332. if (!this.activeCamera) {
  24333. throw new Error("No camera defined");
  24334. }
  24335. this._processSubCameras(this.activeCamera);
  24336. }
  24337. // Intersection checks
  24338. this._checkIntersections();
  24339. // Update the audio listener attached to the camera
  24340. if (BABYLON.AudioEngine) {
  24341. this._updateAudioParameters();
  24342. }
  24343. // After render
  24344. if (this.afterRender) {
  24345. this.afterRender();
  24346. }
  24347. this.onAfterRenderObservable.notifyObservers(this);
  24348. // Cleaning
  24349. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24350. var data = this._toBeDisposed.data[index];
  24351. if (data) {
  24352. data.dispose();
  24353. }
  24354. this._toBeDisposed[index] = null;
  24355. }
  24356. this._toBeDisposed.reset();
  24357. if (this.dumpNextRenderTargets) {
  24358. this.dumpNextRenderTargets = false;
  24359. }
  24360. this._activeBones.addCount(0, true);
  24361. this._activeIndices.addCount(0, true);
  24362. this._activeParticles.addCount(0, true);
  24363. };
  24364. Scene.prototype._updateAudioParameters = function () {
  24365. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24366. return;
  24367. }
  24368. var listeningCamera;
  24369. var audioEngine = BABYLON.Engine.audioEngine;
  24370. if (this.activeCameras.length > 0) {
  24371. listeningCamera = this.activeCameras[0];
  24372. }
  24373. else {
  24374. listeningCamera = this.activeCamera;
  24375. }
  24376. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24377. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24378. // for VR cameras
  24379. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24380. listeningCamera = listeningCamera.rigCameras[0];
  24381. }
  24382. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24383. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24384. cameraDirection.normalize();
  24385. // To avoid some errors on GearVR
  24386. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24387. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24388. }
  24389. var i;
  24390. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24391. var sound = this.mainSoundTrack.soundCollection[i];
  24392. if (sound.useCustomAttenuation) {
  24393. sound.updateDistanceFromListener();
  24394. }
  24395. }
  24396. for (i = 0; i < this.soundTracks.length; i++) {
  24397. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24398. sound = this.soundTracks[i].soundCollection[j];
  24399. if (sound.useCustomAttenuation) {
  24400. sound.updateDistanceFromListener();
  24401. }
  24402. }
  24403. }
  24404. }
  24405. };
  24406. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24407. // Audio
  24408. get: function () {
  24409. return this._audioEnabled;
  24410. },
  24411. set: function (value) {
  24412. this._audioEnabled = value;
  24413. if (BABYLON.AudioEngine) {
  24414. if (this._audioEnabled) {
  24415. this._enableAudio();
  24416. }
  24417. else {
  24418. this._disableAudio();
  24419. }
  24420. }
  24421. },
  24422. enumerable: true,
  24423. configurable: true
  24424. });
  24425. Scene.prototype._disableAudio = function () {
  24426. var i;
  24427. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24428. this.mainSoundTrack.soundCollection[i].pause();
  24429. }
  24430. for (i = 0; i < this.soundTracks.length; i++) {
  24431. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24432. this.soundTracks[i].soundCollection[j].pause();
  24433. }
  24434. }
  24435. };
  24436. Scene.prototype._enableAudio = function () {
  24437. var i;
  24438. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24439. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24440. this.mainSoundTrack.soundCollection[i].play();
  24441. }
  24442. }
  24443. for (i = 0; i < this.soundTracks.length; i++) {
  24444. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24445. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24446. this.soundTracks[i].soundCollection[j].play();
  24447. }
  24448. }
  24449. }
  24450. };
  24451. Object.defineProperty(Scene.prototype, "headphone", {
  24452. get: function () {
  24453. return this._headphone;
  24454. },
  24455. set: function (value) {
  24456. this._headphone = value;
  24457. if (BABYLON.AudioEngine) {
  24458. if (this._headphone) {
  24459. this._switchAudioModeForHeadphones();
  24460. }
  24461. else {
  24462. this._switchAudioModeForNormalSpeakers();
  24463. }
  24464. }
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Scene.prototype._switchAudioModeForHeadphones = function () {
  24470. this.mainSoundTrack.switchPanningModelToHRTF();
  24471. for (var i = 0; i < this.soundTracks.length; i++) {
  24472. this.soundTracks[i].switchPanningModelToHRTF();
  24473. }
  24474. };
  24475. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24476. this.mainSoundTrack.switchPanningModelToEqualPower();
  24477. for (var i = 0; i < this.soundTracks.length; i++) {
  24478. this.soundTracks[i].switchPanningModelToEqualPower();
  24479. }
  24480. };
  24481. /**
  24482. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24483. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24484. * @returns the created depth renderer
  24485. */
  24486. Scene.prototype.enableDepthRenderer = function (camera) {
  24487. camera = camera || this.activeCamera;
  24488. if (!camera) {
  24489. throw "No camera available to enable depth renderer";
  24490. }
  24491. if (!this._depthRenderer[camera.id]) {
  24492. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24493. }
  24494. return this._depthRenderer[camera.id];
  24495. };
  24496. /**
  24497. * Disables a depth renderer for a given camera
  24498. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24499. */
  24500. Scene.prototype.disableDepthRenderer = function (camera) {
  24501. camera = camera || this.activeCamera;
  24502. if (!camera || !this._depthRenderer[camera.id]) {
  24503. return;
  24504. }
  24505. this._depthRenderer[camera.id].dispose();
  24506. delete this._depthRenderer[camera.id];
  24507. };
  24508. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24509. if (ratio === void 0) { ratio = 1; }
  24510. if (this._geometryBufferRenderer) {
  24511. return this._geometryBufferRenderer;
  24512. }
  24513. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24514. if (!this._geometryBufferRenderer.isSupported) {
  24515. this._geometryBufferRenderer = null;
  24516. }
  24517. return this._geometryBufferRenderer;
  24518. };
  24519. Scene.prototype.disableGeometryBufferRenderer = function () {
  24520. if (!this._geometryBufferRenderer) {
  24521. return;
  24522. }
  24523. this._geometryBufferRenderer.dispose();
  24524. this._geometryBufferRenderer = null;
  24525. };
  24526. Scene.prototype.freezeMaterials = function () {
  24527. for (var i = 0; i < this.materials.length; i++) {
  24528. this.materials[i].freeze();
  24529. }
  24530. };
  24531. Scene.prototype.unfreezeMaterials = function () {
  24532. for (var i = 0; i < this.materials.length; i++) {
  24533. this.materials[i].unfreeze();
  24534. }
  24535. };
  24536. Scene.prototype.dispose = function () {
  24537. this.beforeRender = null;
  24538. this.afterRender = null;
  24539. this.skeletons = [];
  24540. this.morphTargetManagers = [];
  24541. this.importedMeshesFiles = new Array();
  24542. this.stopAllAnimations();
  24543. this.resetCachedMaterial();
  24544. for (var key in this._depthRenderer) {
  24545. this._depthRenderer[key].dispose();
  24546. }
  24547. if (this._gamepadManager) {
  24548. this._gamepadManager.dispose();
  24549. this._gamepadManager = null;
  24550. }
  24551. // Smart arrays
  24552. if (this.activeCamera) {
  24553. this.activeCamera._activeMeshes.dispose();
  24554. this.activeCamera = null;
  24555. }
  24556. this._activeMeshes.dispose();
  24557. this._renderingManager.dispose();
  24558. this._processedMaterials.dispose();
  24559. this._activeParticleSystems.dispose();
  24560. this._activeSkeletons.dispose();
  24561. this._softwareSkinnedMeshes.dispose();
  24562. this._renderTargets.dispose();
  24563. if (this._boundingBoxRenderer) {
  24564. this._boundingBoxRenderer.dispose();
  24565. }
  24566. this._meshesForIntersections.dispose();
  24567. this._toBeDisposed.dispose();
  24568. // Abort active requests
  24569. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24570. var request = _a[_i];
  24571. request.abort();
  24572. }
  24573. // Debug layer
  24574. if (this._debugLayer) {
  24575. this._debugLayer.hide();
  24576. }
  24577. // Events
  24578. this.onDisposeObservable.notifyObservers(this);
  24579. this.onDisposeObservable.clear();
  24580. this.onBeforeRenderObservable.clear();
  24581. this.onAfterRenderObservable.clear();
  24582. this.OnBeforeRenderTargetsRenderObservable.clear();
  24583. this.OnAfterRenderTargetsRenderObservable.clear();
  24584. this.onAfterStepObservable.clear();
  24585. this.onBeforeStepObservable.clear();
  24586. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24587. this.onAfterActiveMeshesEvaluationObservable.clear();
  24588. this.onBeforeParticlesRenderingObservable.clear();
  24589. this.onAfterParticlesRenderingObservable.clear();
  24590. this.onBeforeSpritesRenderingObservable.clear();
  24591. this.onAfterSpritesRenderingObservable.clear();
  24592. this.onBeforeDrawPhaseObservable.clear();
  24593. this.onAfterDrawPhaseObservable.clear();
  24594. this.onBeforePhysicsObservable.clear();
  24595. this.onAfterPhysicsObservable.clear();
  24596. this.onBeforeAnimationsObservable.clear();
  24597. this.onAfterAnimationsObservable.clear();
  24598. this.onDataLoadedObservable.clear();
  24599. this.detachControl();
  24600. // Release sounds & sounds tracks
  24601. if (BABYLON.AudioEngine) {
  24602. this.disposeSounds();
  24603. }
  24604. // VR Helper
  24605. if (this.VRHelper) {
  24606. this.VRHelper.dispose();
  24607. }
  24608. // Detach cameras
  24609. var canvas = this._engine.getRenderingCanvas();
  24610. if (canvas) {
  24611. var index;
  24612. for (index = 0; index < this.cameras.length; index++) {
  24613. this.cameras[index].detachControl(canvas);
  24614. }
  24615. }
  24616. // Release animation groups
  24617. while (this.animationGroups.length) {
  24618. this.animationGroups[0].dispose();
  24619. }
  24620. // Release lights
  24621. while (this.lights.length) {
  24622. this.lights[0].dispose();
  24623. }
  24624. // Release meshes
  24625. while (this.meshes.length) {
  24626. this.meshes[0].dispose(true);
  24627. }
  24628. while (this.transformNodes.length) {
  24629. this.removeTransformNode(this.transformNodes[0]);
  24630. }
  24631. // Release cameras
  24632. while (this.cameras.length) {
  24633. this.cameras[0].dispose();
  24634. }
  24635. // Release materials
  24636. if (this.defaultMaterial) {
  24637. this.defaultMaterial.dispose();
  24638. }
  24639. while (this.multiMaterials.length) {
  24640. this.multiMaterials[0].dispose();
  24641. }
  24642. while (this.materials.length) {
  24643. this.materials[0].dispose();
  24644. }
  24645. // Release particles
  24646. while (this.particleSystems.length) {
  24647. this.particleSystems[0].dispose();
  24648. }
  24649. // Release sprites
  24650. while (this.spriteManagers.length) {
  24651. this.spriteManagers[0].dispose();
  24652. }
  24653. // Release postProcesses
  24654. while (this.postProcesses.length) {
  24655. this.postProcesses[0].dispose();
  24656. }
  24657. // Release layers
  24658. while (this.layers.length) {
  24659. this.layers[0].dispose();
  24660. }
  24661. while (this.effectLayers.length) {
  24662. this.effectLayers[0].dispose();
  24663. }
  24664. // Release textures
  24665. while (this.textures.length) {
  24666. this.textures[0].dispose();
  24667. }
  24668. // Release UBO
  24669. this._sceneUbo.dispose();
  24670. if (this._alternateSceneUbo) {
  24671. this._alternateSceneUbo.dispose();
  24672. }
  24673. // Post-processes
  24674. this.postProcessManager.dispose();
  24675. if (this._postProcessRenderPipelineManager) {
  24676. this._postProcessRenderPipelineManager.dispose();
  24677. }
  24678. // Physics
  24679. if (this._physicsEngine) {
  24680. this.disablePhysicsEngine();
  24681. }
  24682. // Remove from engine
  24683. index = this._engine.scenes.indexOf(this);
  24684. if (index > -1) {
  24685. this._engine.scenes.splice(index, 1);
  24686. }
  24687. this._engine.wipeCaches(true);
  24688. this._isDisposed = true;
  24689. };
  24690. Object.defineProperty(Scene.prototype, "isDisposed", {
  24691. get: function () {
  24692. return this._isDisposed;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. // Release sounds & sounds tracks
  24698. Scene.prototype.disposeSounds = function () {
  24699. if (!this._mainSoundTrack) {
  24700. return;
  24701. }
  24702. this.mainSoundTrack.dispose();
  24703. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24704. this.soundTracks[scIndex].dispose();
  24705. }
  24706. };
  24707. // Octrees
  24708. /**
  24709. * Get the world extend vectors with an optional filter
  24710. *
  24711. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  24712. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24713. */
  24714. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24715. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24716. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24717. filterPredicate = filterPredicate || (function () { return true; });
  24718. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24719. mesh.computeWorldMatrix(true);
  24720. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24721. return;
  24722. }
  24723. var boundingInfo = mesh.getBoundingInfo();
  24724. var minBox = boundingInfo.boundingBox.minimumWorld;
  24725. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24726. BABYLON.Tools.CheckExtends(minBox, min, max);
  24727. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24728. });
  24729. return {
  24730. min: min,
  24731. max: max
  24732. };
  24733. };
  24734. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24735. if (maxCapacity === void 0) { maxCapacity = 64; }
  24736. if (maxDepth === void 0) { maxDepth = 2; }
  24737. if (!this._selectionOctree) {
  24738. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24739. }
  24740. var worldExtends = this.getWorldExtends();
  24741. // Update octree
  24742. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24743. return this._selectionOctree;
  24744. };
  24745. // Picking
  24746. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24747. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24748. var result = BABYLON.Ray.Zero();
  24749. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24750. return result;
  24751. };
  24752. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24753. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24754. var engine = this._engine;
  24755. if (!camera) {
  24756. if (!this.activeCamera)
  24757. throw new Error("Active camera not set");
  24758. camera = this.activeCamera;
  24759. }
  24760. var cameraViewport = camera.viewport;
  24761. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24762. // Moving coordinates to local viewport world
  24763. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24764. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24765. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24766. return this;
  24767. };
  24768. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24769. var result = BABYLON.Ray.Zero();
  24770. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24771. return result;
  24772. };
  24773. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24774. if (!BABYLON.PickingInfo) {
  24775. return this;
  24776. }
  24777. var engine = this._engine;
  24778. if (!camera) {
  24779. if (!this.activeCamera)
  24780. throw new Error("Active camera not set");
  24781. camera = this.activeCamera;
  24782. }
  24783. var cameraViewport = camera.viewport;
  24784. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24785. var identity = BABYLON.Matrix.Identity();
  24786. // Moving coordinates to local viewport world
  24787. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24788. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24789. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24790. return this;
  24791. };
  24792. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24793. if (!BABYLON.PickingInfo) {
  24794. return null;
  24795. }
  24796. var pickingInfo = null;
  24797. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24798. var mesh = this.meshes[meshIndex];
  24799. if (predicate) {
  24800. if (!predicate(mesh)) {
  24801. continue;
  24802. }
  24803. }
  24804. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24805. continue;
  24806. }
  24807. var world = mesh.getWorldMatrix();
  24808. var ray = rayFunction(world);
  24809. var result = mesh.intersects(ray, fastCheck);
  24810. if (!result || !result.hit)
  24811. continue;
  24812. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24813. continue;
  24814. pickingInfo = result;
  24815. if (fastCheck) {
  24816. break;
  24817. }
  24818. }
  24819. return pickingInfo || new BABYLON.PickingInfo();
  24820. };
  24821. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24822. if (!BABYLON.PickingInfo) {
  24823. return null;
  24824. }
  24825. var pickingInfos = new Array();
  24826. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24827. var mesh = this.meshes[meshIndex];
  24828. if (predicate) {
  24829. if (!predicate(mesh)) {
  24830. continue;
  24831. }
  24832. }
  24833. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24834. continue;
  24835. }
  24836. var world = mesh.getWorldMatrix();
  24837. var ray = rayFunction(world);
  24838. var result = mesh.intersects(ray, false);
  24839. if (!result || !result.hit)
  24840. continue;
  24841. pickingInfos.push(result);
  24842. }
  24843. return pickingInfos;
  24844. };
  24845. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24846. if (!BABYLON.PickingInfo) {
  24847. return null;
  24848. }
  24849. var pickingInfo = null;
  24850. if (!camera) {
  24851. if (!this.activeCamera) {
  24852. return null;
  24853. }
  24854. camera = this.activeCamera;
  24855. }
  24856. if (this.spriteManagers.length > 0) {
  24857. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24858. var spriteManager = this.spriteManagers[spriteIndex];
  24859. if (!spriteManager.isPickable) {
  24860. continue;
  24861. }
  24862. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24863. if (!result || !result.hit)
  24864. continue;
  24865. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24866. continue;
  24867. pickingInfo = result;
  24868. if (fastCheck) {
  24869. break;
  24870. }
  24871. }
  24872. }
  24873. return pickingInfo || new BABYLON.PickingInfo();
  24874. };
  24875. /** Launch a ray to try to pick a mesh in the scene
  24876. * @param x position on screen
  24877. * @param y position on screen
  24878. * @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
  24879. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24880. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24881. */
  24882. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24883. var _this = this;
  24884. if (!BABYLON.PickingInfo) {
  24885. return null;
  24886. }
  24887. return this._internalPick(function (world) {
  24888. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24889. return _this._tempPickingRay;
  24890. }, predicate, fastCheck);
  24891. };
  24892. /** Launch a ray to try to pick a sprite in the scene
  24893. * @param x position on screen
  24894. * @param y position on screen
  24895. * @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
  24896. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24897. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24898. */
  24899. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24900. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24901. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24902. };
  24903. /** Use the given ray to pick a mesh in the scene
  24904. * @param ray The ray to use to pick meshes
  24905. * @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
  24906. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24907. */
  24908. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24909. var _this = this;
  24910. return this._internalPick(function (world) {
  24911. if (!_this._pickWithRayInverseMatrix) {
  24912. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24913. }
  24914. world.invertToRef(_this._pickWithRayInverseMatrix);
  24915. if (!_this._cachedRayForTransform) {
  24916. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24917. }
  24918. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24919. return _this._cachedRayForTransform;
  24920. }, predicate, fastCheck);
  24921. };
  24922. /**
  24923. * Launch a ray to try to pick a mesh in the scene
  24924. * @param x X position on screen
  24925. * @param y Y position on screen
  24926. * @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
  24927. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24928. */
  24929. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24930. var _this = this;
  24931. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24932. };
  24933. /**
  24934. * Launch a ray to try to pick a mesh in the scene
  24935. * @param ray Ray to use
  24936. * @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
  24937. */
  24938. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24939. var _this = this;
  24940. return this._internalMultiPick(function (world) {
  24941. if (!_this._pickWithRayInverseMatrix) {
  24942. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24943. }
  24944. world.invertToRef(_this._pickWithRayInverseMatrix);
  24945. if (!_this._cachedRayForTransform) {
  24946. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24947. }
  24948. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24949. return _this._cachedRayForTransform;
  24950. }, predicate);
  24951. };
  24952. Scene.prototype.setPointerOverMesh = function (mesh) {
  24953. if (this._pointerOverMesh === mesh) {
  24954. return;
  24955. }
  24956. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24957. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24958. }
  24959. this._pointerOverMesh = mesh;
  24960. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24961. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24962. }
  24963. };
  24964. Scene.prototype.getPointerOverMesh = function () {
  24965. return this._pointerOverMesh;
  24966. };
  24967. Scene.prototype.setPointerOverSprite = function (sprite) {
  24968. if (this._pointerOverSprite === sprite) {
  24969. return;
  24970. }
  24971. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24972. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24973. }
  24974. this._pointerOverSprite = sprite;
  24975. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24976. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24977. }
  24978. };
  24979. Scene.prototype.getPointerOverSprite = function () {
  24980. return this._pointerOverSprite;
  24981. };
  24982. // Physics
  24983. Scene.prototype.getPhysicsEngine = function () {
  24984. return this._physicsEngine;
  24985. };
  24986. /**
  24987. * Enables physics to the current scene
  24988. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24989. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24990. * @return {boolean} was the physics engine initialized
  24991. */
  24992. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24993. if (gravity === void 0) { gravity = null; }
  24994. if (this._physicsEngine) {
  24995. return true;
  24996. }
  24997. try {
  24998. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24999. return true;
  25000. }
  25001. catch (e) {
  25002. BABYLON.Tools.Error(e.message);
  25003. return false;
  25004. }
  25005. };
  25006. Scene.prototype.disablePhysicsEngine = function () {
  25007. if (!this._physicsEngine) {
  25008. return;
  25009. }
  25010. this._physicsEngine.dispose();
  25011. this._physicsEngine = null;
  25012. };
  25013. Scene.prototype.isPhysicsEnabled = function () {
  25014. return this._physicsEngine !== undefined;
  25015. };
  25016. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25017. var mesh = compound.parts[0].mesh;
  25018. if (mesh.physicsImpostor) {
  25019. mesh.physicsImpostor.dispose();
  25020. mesh.physicsImpostor = null;
  25021. }
  25022. };
  25023. // Misc.
  25024. Scene.prototype._rebuildGeometries = function () {
  25025. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25026. var geometry = _a[_i];
  25027. geometry._rebuild();
  25028. }
  25029. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25030. var mesh = _c[_b];
  25031. mesh._rebuild();
  25032. }
  25033. if (this.postProcessManager) {
  25034. this.postProcessManager._rebuild();
  25035. }
  25036. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25037. var layer = _e[_d];
  25038. layer._rebuild();
  25039. }
  25040. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25041. var effectLayer = _g[_f];
  25042. effectLayer._rebuild();
  25043. }
  25044. if (this._boundingBoxRenderer) {
  25045. this._boundingBoxRenderer._rebuild();
  25046. }
  25047. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25048. var system = _j[_h];
  25049. system.rebuild();
  25050. }
  25051. if (this._postProcessRenderPipelineManager) {
  25052. this._postProcessRenderPipelineManager._rebuild();
  25053. }
  25054. };
  25055. Scene.prototype._rebuildTextures = function () {
  25056. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25057. var texture = _a[_i];
  25058. texture._rebuild();
  25059. }
  25060. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25061. };
  25062. /**
  25063. * Creates a default light for the scene.
  25064. * @param replace Whether to replace the existing lights in the scene.
  25065. */
  25066. Scene.prototype.createDefaultLight = function (replace) {
  25067. if (replace === void 0) { replace = false; }
  25068. // Dispose existing light in replace mode.
  25069. if (replace) {
  25070. if (this.lights) {
  25071. for (var i = 0; i < this.lights.length; i++) {
  25072. this.lights[i].dispose();
  25073. }
  25074. }
  25075. }
  25076. // Light
  25077. if (this.lights.length === 0) {
  25078. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25079. }
  25080. };
  25081. /**
  25082. * Creates a default camera for the scene.
  25083. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25084. * @param replace Whether to replace the existing active camera in the scene.
  25085. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25086. */
  25087. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25088. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25089. if (replace === void 0) { replace = false; }
  25090. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25091. // Dispose existing camera in replace mode.
  25092. if (replace) {
  25093. if (this.activeCamera) {
  25094. this.activeCamera.dispose();
  25095. this.activeCamera = null;
  25096. }
  25097. }
  25098. // Camera
  25099. if (!this.activeCamera) {
  25100. var worldExtends = this.getWorldExtends();
  25101. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25102. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25103. var camera;
  25104. var radius = worldSize.length() * 1.5;
  25105. // empty scene scenario!
  25106. if (!isFinite(radius)) {
  25107. radius = 1;
  25108. worldCenter.copyFromFloats(0, 0, 0);
  25109. }
  25110. if (createArcRotateCamera) {
  25111. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25112. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25113. arcRotateCamera.wheelPrecision = 100 / radius;
  25114. camera = arcRotateCamera;
  25115. }
  25116. else {
  25117. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25118. freeCamera.setTarget(worldCenter);
  25119. camera = freeCamera;
  25120. }
  25121. camera.minZ = radius * 0.01;
  25122. camera.maxZ = radius * 1000;
  25123. camera.speed = radius * 0.2;
  25124. this.activeCamera = camera;
  25125. var canvas = this.getEngine().getRenderingCanvas();
  25126. if (attachCameraControls && canvas) {
  25127. camera.attachControl(canvas);
  25128. }
  25129. }
  25130. };
  25131. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25132. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25133. if (replace === void 0) { replace = false; }
  25134. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25135. this.createDefaultLight(replace);
  25136. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25137. };
  25138. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25139. if (pbr === void 0) { pbr = false; }
  25140. if (scale === void 0) { scale = 1000; }
  25141. if (blur === void 0) { blur = 0; }
  25142. if (environmentTexture) {
  25143. this.environmentTexture = environmentTexture;
  25144. }
  25145. if (!this.environmentTexture) {
  25146. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25147. return null;
  25148. }
  25149. // Skybox
  25150. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25151. if (pbr) {
  25152. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25153. hdrSkyboxMaterial.backFaceCulling = false;
  25154. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25155. if (hdrSkyboxMaterial.reflectionTexture) {
  25156. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25157. }
  25158. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25159. hdrSkyboxMaterial.disableLighting = true;
  25160. hdrSkyboxMaterial.twoSidedLighting = true;
  25161. hdrSkybox.infiniteDistance = true;
  25162. hdrSkybox.material = hdrSkyboxMaterial;
  25163. }
  25164. else {
  25165. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25166. skyboxMaterial.backFaceCulling = false;
  25167. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25168. if (skyboxMaterial.reflectionTexture) {
  25169. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25170. }
  25171. skyboxMaterial.disableLighting = true;
  25172. hdrSkybox.infiniteDistance = true;
  25173. hdrSkybox.material = skyboxMaterial;
  25174. }
  25175. return hdrSkybox;
  25176. };
  25177. Scene.prototype.createDefaultEnvironment = function (options) {
  25178. if (BABYLON.EnvironmentHelper) {
  25179. return new BABYLON.EnvironmentHelper(options, this);
  25180. }
  25181. return null;
  25182. };
  25183. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25184. if (webVROptions === void 0) { webVROptions = {}; }
  25185. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25186. };
  25187. // Tags
  25188. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25189. if (tagsQuery === undefined) {
  25190. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25191. return list;
  25192. }
  25193. var listByTags = [];
  25194. forEach = forEach || (function (item) { return; });
  25195. for (var i in list) {
  25196. var item = list[i];
  25197. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25198. listByTags.push(item);
  25199. forEach(item);
  25200. }
  25201. }
  25202. return listByTags;
  25203. };
  25204. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25205. return this._getByTags(this.meshes, tagsQuery, forEach);
  25206. };
  25207. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25208. return this._getByTags(this.cameras, tagsQuery, forEach);
  25209. };
  25210. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25211. return this._getByTags(this.lights, tagsQuery, forEach);
  25212. };
  25213. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25214. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25215. };
  25216. /**
  25217. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25218. * This allowed control for front to back rendering or reversly depending of the special needs.
  25219. *
  25220. * @param renderingGroupId The rendering group id corresponding to its index
  25221. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25222. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25223. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25224. */
  25225. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25226. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25227. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25228. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25229. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25230. };
  25231. /**
  25232. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25233. *
  25234. * @param renderingGroupId The rendering group id corresponding to its index
  25235. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25236. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25237. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25238. */
  25239. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25240. if (depth === void 0) { depth = true; }
  25241. if (stencil === void 0) { stencil = true; }
  25242. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25243. };
  25244. /**
  25245. * Will flag all materials as dirty to trigger new shader compilation
  25246. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25247. */
  25248. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25249. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25250. var material = _a[_i];
  25251. if (predicate && !predicate(material)) {
  25252. continue;
  25253. }
  25254. material.markAsDirty(flag);
  25255. }
  25256. };
  25257. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25258. var _this = this;
  25259. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25260. this._activeRequests.push(request);
  25261. request.onCompleteObservable.add(function (request) {
  25262. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25263. });
  25264. return request;
  25265. };
  25266. /** @ignore */
  25267. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25268. var _this = this;
  25269. return new Promise(function (resolve, reject) {
  25270. _this._loadFile(url, function (data) {
  25271. resolve(data);
  25272. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25273. reject(exception);
  25274. });
  25275. });
  25276. };
  25277. // Statics
  25278. Scene._FOGMODE_NONE = 0;
  25279. Scene._FOGMODE_EXP = 1;
  25280. Scene._FOGMODE_EXP2 = 2;
  25281. Scene._FOGMODE_LINEAR = 3;
  25282. Scene._uniqueIdCounter = 0;
  25283. Scene.MinDeltaTime = 1.0;
  25284. Scene.MaxDeltaTime = 1000.0;
  25285. /** The distance in pixel that you have to move to prevent some events */
  25286. Scene.DragMovementThreshold = 10; // in pixels
  25287. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25288. Scene.LongPressDelay = 500; // in milliseconds
  25289. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25290. Scene.DoubleClickDelay = 300; // in milliseconds
  25291. /** If you need to check double click without raising a single click at first click, enable this flag */
  25292. Scene.ExclusiveDoubleClickMode = false;
  25293. return Scene;
  25294. }());
  25295. BABYLON.Scene = Scene;
  25296. })(BABYLON || (BABYLON = {}));
  25297. //# sourceMappingURL=babylon.scene.js.map
  25298. var BABYLON;
  25299. (function (BABYLON) {
  25300. /**
  25301. * Set of assets to keep when moving a scene into an asset container.
  25302. */
  25303. var KeepAssets = /** @class */ (function () {
  25304. function KeepAssets() {
  25305. /**
  25306. * Cameras to keep.
  25307. */
  25308. this.cameras = new Array();
  25309. /**
  25310. * Lights to keep.
  25311. */
  25312. this.lights = new Array();
  25313. /**
  25314. * Meshes to keep.
  25315. */
  25316. this.meshes = new Array();
  25317. /**
  25318. * Skeletons to keep.
  25319. */
  25320. this.skeletons = new Array();
  25321. /**
  25322. * ParticleSystems to keep.
  25323. */
  25324. this.particleSystems = new Array();
  25325. /**
  25326. * Animations to keep.
  25327. */
  25328. this.animations = new Array();
  25329. /**
  25330. * MultiMaterials to keep.
  25331. */
  25332. this.multiMaterials = new Array();
  25333. /**
  25334. * Materials to keep.
  25335. */
  25336. this.materials = new Array();
  25337. /**
  25338. * MorphTargetManagers to keep.
  25339. */
  25340. this.morphTargetManagers = new Array();
  25341. /**
  25342. * Geometries to keep.
  25343. */
  25344. this.geometries = new Array();
  25345. /**
  25346. * TransformNodes to keep.
  25347. */
  25348. this.transformNodes = new Array();
  25349. /**
  25350. * LensFlareSystems to keep.
  25351. */
  25352. this.lensFlareSystems = new Array();
  25353. /**
  25354. * ShadowGenerators to keep.
  25355. */
  25356. this.shadowGenerators = new Array();
  25357. /**
  25358. * ActionManagers to keep.
  25359. */
  25360. this.actionManagers = new Array();
  25361. /**
  25362. * Sounds to keep.
  25363. */
  25364. this.sounds = new Array();
  25365. }
  25366. return KeepAssets;
  25367. }());
  25368. BABYLON.KeepAssets = KeepAssets;
  25369. /**
  25370. * Container with a set of assets that can be added or removed from a scene.
  25371. */
  25372. var AssetContainer = /** @class */ (function () {
  25373. /**
  25374. * Instantiates an AssetContainer.
  25375. * @param scene The scene the AssetContainer belongs to.
  25376. */
  25377. function AssetContainer(scene) {
  25378. // Objects
  25379. /**
  25380. * Cameras populated in the container.
  25381. */
  25382. this.cameras = new Array();
  25383. /**
  25384. * Lights populated in the container.
  25385. */
  25386. this.lights = new Array();
  25387. /**
  25388. * Meshes populated in the container.
  25389. */
  25390. this.meshes = new Array();
  25391. /**
  25392. * Skeletons populated in the container.
  25393. */
  25394. this.skeletons = new Array();
  25395. /**
  25396. * ParticleSystems populated in the container.
  25397. */
  25398. this.particleSystems = new Array();
  25399. /**
  25400. * Animations populated in the container.
  25401. */
  25402. this.animations = new Array();
  25403. /**
  25404. * MultiMaterials populated in the container.
  25405. */
  25406. this.multiMaterials = new Array();
  25407. /**
  25408. * Materials populated in the container.
  25409. */
  25410. this.materials = new Array();
  25411. /**
  25412. * MorphTargetManagers populated in the container.
  25413. */
  25414. this.morphTargetManagers = new Array();
  25415. /**
  25416. * Geometries populated in the container.
  25417. */
  25418. this.geometries = new Array();
  25419. /**
  25420. * TransformNodes populated in the container.
  25421. */
  25422. this.transformNodes = new Array();
  25423. /**
  25424. * LensFlareSystems populated in the container.
  25425. */
  25426. this.lensFlareSystems = new Array();
  25427. /**
  25428. * ShadowGenerators populated in the container.
  25429. */
  25430. this.shadowGenerators = new Array();
  25431. /**
  25432. * ActionManagers populated in the container.
  25433. */
  25434. this.actionManagers = new Array();
  25435. /**
  25436. * Sounds populated in the container.
  25437. */
  25438. this.sounds = new Array();
  25439. this.scene = scene;
  25440. }
  25441. /**
  25442. * Adds all the assets from the container to the scene.
  25443. */
  25444. AssetContainer.prototype.addAllToScene = function () {
  25445. var _this = this;
  25446. this.cameras.forEach(function (o) {
  25447. _this.scene.addCamera(o);
  25448. });
  25449. this.lights.forEach(function (o) {
  25450. _this.scene.addLight(o);
  25451. });
  25452. this.meshes.forEach(function (o) {
  25453. _this.scene.addMesh(o);
  25454. });
  25455. this.skeletons.forEach(function (o) {
  25456. _this.scene.addSkeleton(o);
  25457. });
  25458. this.particleSystems.forEach(function (o) {
  25459. _this.scene.addParticleSystem(o);
  25460. });
  25461. this.animations.forEach(function (o) {
  25462. _this.scene.addAnimation(o);
  25463. });
  25464. this.multiMaterials.forEach(function (o) {
  25465. _this.scene.addMultiMaterial(o);
  25466. });
  25467. this.materials.forEach(function (o) {
  25468. _this.scene.addMaterial(o);
  25469. });
  25470. this.morphTargetManagers.forEach(function (o) {
  25471. _this.scene.addMorphTargetManager(o);
  25472. });
  25473. this.geometries.forEach(function (o) {
  25474. _this.scene.addGeometry(o);
  25475. });
  25476. this.transformNodes.forEach(function (o) {
  25477. _this.scene.addTransformNode(o);
  25478. });
  25479. this.lensFlareSystems.forEach(function (o) {
  25480. _this.scene.addLensFlareSystem(o);
  25481. });
  25482. this.actionManagers.forEach(function (o) {
  25483. _this.scene.addActionManager(o);
  25484. });
  25485. this.sounds.forEach(function (o) {
  25486. o.play();
  25487. o.autoplay = true;
  25488. _this.scene.mainSoundTrack.AddSound(o);
  25489. });
  25490. };
  25491. /**
  25492. * Removes all the assets in the container from the scene
  25493. */
  25494. AssetContainer.prototype.removeAllFromScene = function () {
  25495. var _this = this;
  25496. this.cameras.forEach(function (o) {
  25497. _this.scene.removeCamera(o);
  25498. });
  25499. this.lights.forEach(function (o) {
  25500. _this.scene.removeLight(o);
  25501. });
  25502. this.meshes.forEach(function (o) {
  25503. _this.scene.removeMesh(o);
  25504. });
  25505. this.skeletons.forEach(function (o) {
  25506. _this.scene.removeSkeleton(o);
  25507. });
  25508. this.particleSystems.forEach(function (o) {
  25509. _this.scene.removeParticleSystem(o);
  25510. });
  25511. this.animations.forEach(function (o) {
  25512. _this.scene.removeAnimation(o);
  25513. });
  25514. this.multiMaterials.forEach(function (o) {
  25515. _this.scene.removeMultiMaterial(o);
  25516. });
  25517. this.materials.forEach(function (o) {
  25518. _this.scene.removeMaterial(o);
  25519. });
  25520. this.morphTargetManagers.forEach(function (o) {
  25521. _this.scene.removeMorphTargetManager(o);
  25522. });
  25523. this.geometries.forEach(function (o) {
  25524. _this.scene.removeGeometry(o);
  25525. });
  25526. this.transformNodes.forEach(function (o) {
  25527. _this.scene.removeTransformNode(o);
  25528. });
  25529. this.lensFlareSystems.forEach(function (o) {
  25530. _this.scene.removeLensFlareSystem(o);
  25531. });
  25532. this.actionManagers.forEach(function (o) {
  25533. _this.scene.removeActionManager(o);
  25534. });
  25535. this.sounds.forEach(function (o) {
  25536. o.stop();
  25537. o.autoplay = false;
  25538. _this.scene.mainSoundTrack.RemoveSound(o);
  25539. });
  25540. };
  25541. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25542. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25543. var asset = sourceAssets_1[_i];
  25544. var move = true;
  25545. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25546. var keepAsset = keepAssets_1[_a];
  25547. if (asset === keepAsset) {
  25548. move = false;
  25549. break;
  25550. }
  25551. }
  25552. if (move) {
  25553. targetAssets.push(asset);
  25554. }
  25555. }
  25556. };
  25557. /**
  25558. * Removes all the assets contained in the scene and adds them to the container.
  25559. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25560. */
  25561. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25562. if (keepAssets === undefined) {
  25563. keepAssets = new KeepAssets();
  25564. }
  25565. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25566. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25567. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25568. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25569. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25570. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25571. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25572. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25573. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25574. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25575. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25576. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25577. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25578. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25579. this.removeAllFromScene();
  25580. };
  25581. return AssetContainer;
  25582. }());
  25583. BABYLON.AssetContainer = AssetContainer;
  25584. })(BABYLON || (BABYLON = {}));
  25585. //# sourceMappingURL=babylon.assetContainer.js.map
  25586. var BABYLON;
  25587. (function (BABYLON) {
  25588. var Buffer = /** @class */ (function () {
  25589. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25590. if (instanced === void 0) { instanced = false; }
  25591. if (engine instanceof BABYLON.Mesh) {
  25592. this._engine = engine.getScene().getEngine();
  25593. }
  25594. else {
  25595. this._engine = engine;
  25596. }
  25597. this._updatable = updatable;
  25598. this._instanced = instanced;
  25599. this._data = data;
  25600. this._strideSize = stride;
  25601. if (!postponeInternalCreation) {
  25602. this.create();
  25603. }
  25604. }
  25605. /**
  25606. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25607. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25608. * @param offset defines offset in the buffer (0 by default)
  25609. * @param size defines the size in floats of attributes (position is 3 for instance)
  25610. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25611. * @param instanced defines if the vertex buffer contains indexed data
  25612. * @returns the new vertex buffer
  25613. */
  25614. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25615. // a lot of these parameters are ignored as they are overriden by the buffer
  25616. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25617. };
  25618. // Properties
  25619. Buffer.prototype.isUpdatable = function () {
  25620. return this._updatable;
  25621. };
  25622. Buffer.prototype.getData = function () {
  25623. return this._data;
  25624. };
  25625. Buffer.prototype.getBuffer = function () {
  25626. return this._buffer;
  25627. };
  25628. Buffer.prototype.getStrideSize = function () {
  25629. return this._strideSize;
  25630. };
  25631. // public getIsInstanced(): boolean {
  25632. // return this._instanced;
  25633. // }
  25634. // public get instanceDivisor(): number {
  25635. // return this._instanceDivisor;
  25636. // }
  25637. // public set instanceDivisor(value: number) {
  25638. // this._instanceDivisor = value;
  25639. // if (value == 0) {
  25640. // this._instanced = false;
  25641. // } else {
  25642. // this._instanced = true;
  25643. // }
  25644. // }
  25645. // Methods
  25646. Buffer.prototype.create = function (data) {
  25647. if (data === void 0) { data = null; }
  25648. if (!data && this._buffer) {
  25649. return; // nothing to do
  25650. }
  25651. data = data || this._data;
  25652. if (!data) {
  25653. return;
  25654. }
  25655. if (!this._buffer) {
  25656. if (this._updatable) {
  25657. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25658. this._data = data;
  25659. }
  25660. else {
  25661. this._buffer = this._engine.createVertexBuffer(data);
  25662. }
  25663. }
  25664. else if (this._updatable) {
  25665. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25666. this._data = data;
  25667. }
  25668. };
  25669. Buffer.prototype._rebuild = function () {
  25670. this._buffer = null;
  25671. this.create(this._data);
  25672. };
  25673. Buffer.prototype.update = function (data) {
  25674. this.create(data);
  25675. };
  25676. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25677. if (!this._buffer) {
  25678. return;
  25679. }
  25680. if (this._updatable) {
  25681. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25682. this._data = null;
  25683. }
  25684. };
  25685. Buffer.prototype.dispose = function () {
  25686. if (!this._buffer) {
  25687. return;
  25688. }
  25689. if (this._engine._releaseBuffer(this._buffer)) {
  25690. this._buffer = null;
  25691. }
  25692. };
  25693. return Buffer;
  25694. }());
  25695. BABYLON.Buffer = Buffer;
  25696. })(BABYLON || (BABYLON = {}));
  25697. //# sourceMappingURL=babylon.buffer.js.map
  25698. var BABYLON;
  25699. (function (BABYLON) {
  25700. var VertexBuffer = /** @class */ (function () {
  25701. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25702. if (data instanceof BABYLON.Buffer) {
  25703. if (!stride) {
  25704. stride = data.getStrideSize();
  25705. }
  25706. this._buffer = data;
  25707. this._ownsBuffer = false;
  25708. }
  25709. else {
  25710. if (!stride) {
  25711. stride = VertexBuffer.DeduceStride(kind);
  25712. }
  25713. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25714. this._ownsBuffer = true;
  25715. }
  25716. this._stride = stride;
  25717. this._instanced = instanced !== undefined ? instanced : false;
  25718. this._instanceDivisor = instanced ? 1 : 0;
  25719. this._offset = offset ? offset : 0;
  25720. this._size = size ? size : stride;
  25721. this._kind = kind;
  25722. }
  25723. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25724. /**
  25725. * Gets or sets the instance divisor when in instanced mode
  25726. */
  25727. get: function () {
  25728. return this._instanceDivisor;
  25729. },
  25730. set: function (value) {
  25731. this._instanceDivisor = value;
  25732. if (value == 0) {
  25733. this._instanced = false;
  25734. }
  25735. else {
  25736. this._instanced = true;
  25737. }
  25738. },
  25739. enumerable: true,
  25740. configurable: true
  25741. });
  25742. VertexBuffer.prototype._rebuild = function () {
  25743. if (!this._buffer) {
  25744. return;
  25745. }
  25746. this._buffer._rebuild();
  25747. };
  25748. /**
  25749. * Returns the kind of the VertexBuffer (string).
  25750. */
  25751. VertexBuffer.prototype.getKind = function () {
  25752. return this._kind;
  25753. };
  25754. // Properties
  25755. /**
  25756. * Boolean : is the VertexBuffer updatable ?
  25757. */
  25758. VertexBuffer.prototype.isUpdatable = function () {
  25759. return this._buffer.isUpdatable();
  25760. };
  25761. /**
  25762. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25763. */
  25764. VertexBuffer.prototype.getData = function () {
  25765. return this._buffer.getData();
  25766. };
  25767. /**
  25768. * Returns the WebGLBuffer associated to the VertexBuffer.
  25769. */
  25770. VertexBuffer.prototype.getBuffer = function () {
  25771. return this._buffer.getBuffer();
  25772. };
  25773. /**
  25774. * Returns the stride of the VertexBuffer (integer).
  25775. */
  25776. VertexBuffer.prototype.getStrideSize = function () {
  25777. return this._stride;
  25778. };
  25779. /**
  25780. * Returns the offset (integer).
  25781. */
  25782. VertexBuffer.prototype.getOffset = function () {
  25783. return this._offset;
  25784. };
  25785. /**
  25786. * Returns the VertexBuffer total size (integer).
  25787. */
  25788. VertexBuffer.prototype.getSize = function () {
  25789. return this._size;
  25790. };
  25791. /**
  25792. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25793. */
  25794. VertexBuffer.prototype.getIsInstanced = function () {
  25795. return this._instanced;
  25796. };
  25797. /**
  25798. * Returns the instancing divisor, zero for non-instanced (integer).
  25799. */
  25800. VertexBuffer.prototype.getInstanceDivisor = function () {
  25801. return this._instanceDivisor;
  25802. };
  25803. // Methods
  25804. /**
  25805. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25806. * Returns the created WebGLBuffer.
  25807. */
  25808. VertexBuffer.prototype.create = function (data) {
  25809. return this._buffer.create(data);
  25810. };
  25811. /**
  25812. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25813. * This function will create a new buffer if the current one is not updatable
  25814. * Returns the updated WebGLBuffer.
  25815. */
  25816. VertexBuffer.prototype.update = function (data) {
  25817. return this._buffer.update(data);
  25818. };
  25819. /**
  25820. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25821. * Returns the directly updated WebGLBuffer.
  25822. */
  25823. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25824. return this._buffer.updateDirectly(data, offset);
  25825. };
  25826. /**
  25827. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25828. */
  25829. VertexBuffer.prototype.dispose = function () {
  25830. if (this._ownsBuffer) {
  25831. this._buffer.dispose();
  25832. }
  25833. };
  25834. Object.defineProperty(VertexBuffer, "PositionKind", {
  25835. get: function () {
  25836. return VertexBuffer._PositionKind;
  25837. },
  25838. enumerable: true,
  25839. configurable: true
  25840. });
  25841. Object.defineProperty(VertexBuffer, "NormalKind", {
  25842. get: function () {
  25843. return VertexBuffer._NormalKind;
  25844. },
  25845. enumerable: true,
  25846. configurable: true
  25847. });
  25848. Object.defineProperty(VertexBuffer, "TangentKind", {
  25849. get: function () {
  25850. return VertexBuffer._TangentKind;
  25851. },
  25852. enumerable: true,
  25853. configurable: true
  25854. });
  25855. Object.defineProperty(VertexBuffer, "UVKind", {
  25856. get: function () {
  25857. return VertexBuffer._UVKind;
  25858. },
  25859. enumerable: true,
  25860. configurable: true
  25861. });
  25862. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25863. get: function () {
  25864. return VertexBuffer._UV2Kind;
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25870. get: function () {
  25871. return VertexBuffer._UV3Kind;
  25872. },
  25873. enumerable: true,
  25874. configurable: true
  25875. });
  25876. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25877. get: function () {
  25878. return VertexBuffer._UV4Kind;
  25879. },
  25880. enumerable: true,
  25881. configurable: true
  25882. });
  25883. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25884. get: function () {
  25885. return VertexBuffer._UV5Kind;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25891. get: function () {
  25892. return VertexBuffer._UV6Kind;
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(VertexBuffer, "ColorKind", {
  25898. get: function () {
  25899. return VertexBuffer._ColorKind;
  25900. },
  25901. enumerable: true,
  25902. configurable: true
  25903. });
  25904. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25905. get: function () {
  25906. return VertexBuffer._MatricesIndicesKind;
  25907. },
  25908. enumerable: true,
  25909. configurable: true
  25910. });
  25911. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25912. get: function () {
  25913. return VertexBuffer._MatricesWeightsKind;
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25919. get: function () {
  25920. return VertexBuffer._MatricesIndicesExtraKind;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25926. get: function () {
  25927. return VertexBuffer._MatricesWeightsExtraKind;
  25928. },
  25929. enumerable: true,
  25930. configurable: true
  25931. });
  25932. /**
  25933. * Deduces the stride given a kind.
  25934. * @param kind The kind string to deduce
  25935. * @returns The deduced stride
  25936. */
  25937. VertexBuffer.DeduceStride = function (kind) {
  25938. switch (kind) {
  25939. case VertexBuffer.UVKind:
  25940. case VertexBuffer.UV2Kind:
  25941. case VertexBuffer.UV3Kind:
  25942. case VertexBuffer.UV4Kind:
  25943. case VertexBuffer.UV5Kind:
  25944. case VertexBuffer.UV6Kind:
  25945. return 2;
  25946. case VertexBuffer.NormalKind:
  25947. case VertexBuffer.PositionKind:
  25948. return 3;
  25949. case VertexBuffer.ColorKind:
  25950. case VertexBuffer.MatricesIndicesKind:
  25951. case VertexBuffer.MatricesIndicesExtraKind:
  25952. case VertexBuffer.MatricesWeightsKind:
  25953. case VertexBuffer.MatricesWeightsExtraKind:
  25954. case VertexBuffer.TangentKind:
  25955. return 4;
  25956. default:
  25957. throw new Error("Invalid kind '" + kind + "'");
  25958. }
  25959. };
  25960. // Enums
  25961. VertexBuffer._PositionKind = "position";
  25962. VertexBuffer._NormalKind = "normal";
  25963. VertexBuffer._TangentKind = "tangent";
  25964. VertexBuffer._UVKind = "uv";
  25965. VertexBuffer._UV2Kind = "uv2";
  25966. VertexBuffer._UV3Kind = "uv3";
  25967. VertexBuffer._UV4Kind = "uv4";
  25968. VertexBuffer._UV5Kind = "uv5";
  25969. VertexBuffer._UV6Kind = "uv6";
  25970. VertexBuffer._ColorKind = "color";
  25971. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25972. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25973. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25974. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25975. return VertexBuffer;
  25976. }());
  25977. BABYLON.VertexBuffer = VertexBuffer;
  25978. })(BABYLON || (BABYLON = {}));
  25979. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25980. var BABYLON;
  25981. (function (BABYLON) {
  25982. /**
  25983. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25984. */
  25985. var DummyInternalTextureTracker = /** @class */ (function () {
  25986. function DummyInternalTextureTracker() {
  25987. /**
  25988. * Gets or set the previous tracker in the list
  25989. */
  25990. this.previous = null;
  25991. /**
  25992. * Gets or set the next tracker in the list
  25993. */
  25994. this.next = null;
  25995. }
  25996. return DummyInternalTextureTracker;
  25997. }());
  25998. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25999. })(BABYLON || (BABYLON = {}));
  26000. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26001. var BABYLON;
  26002. (function (BABYLON) {
  26003. /**
  26004. * Class used to store data associated with WebGL texture data for the engine
  26005. * This class should not be used directly
  26006. */
  26007. var InternalTexture = /** @class */ (function () {
  26008. /**
  26009. * Creates a new InternalTexture
  26010. * @param engine defines the engine to use
  26011. * @param dataSource defines the type of data that will be used
  26012. */
  26013. function InternalTexture(engine, dataSource) {
  26014. /**
  26015. * Observable called when the texture is loaded
  26016. */
  26017. this.onLoadedObservable = new BABYLON.Observable();
  26018. /**
  26019. * Gets or set the previous tracker in the list
  26020. */
  26021. this.previous = null;
  26022. /**
  26023. * Gets or set the next tracker in the list
  26024. */
  26025. this.next = null;
  26026. // Private
  26027. /** @ignore */
  26028. this._initialSlot = -1;
  26029. /** @ignore */
  26030. this._designatedSlot = -1;
  26031. /** @ignore */
  26032. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26033. /** @ignore */
  26034. this._comparisonFunction = 0;
  26035. /** @ignore */
  26036. this._references = 1;
  26037. this._engine = engine;
  26038. this._dataSource = dataSource;
  26039. this._webGLTexture = engine._createTexture();
  26040. }
  26041. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26042. /**
  26043. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26044. */
  26045. get: function () {
  26046. return this._dataSource;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. /**
  26052. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26053. */
  26054. InternalTexture.prototype.incrementReferences = function () {
  26055. this._references++;
  26056. };
  26057. /**
  26058. * Change the size of the texture (not the size of the content)
  26059. * @param width defines the new width
  26060. * @param height defines the new height
  26061. * @param depth defines the new depth (1 by default)
  26062. */
  26063. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26064. if (depth === void 0) { depth = 1; }
  26065. this.width = width;
  26066. this.height = height;
  26067. this.depth = depth;
  26068. this.baseWidth = width;
  26069. this.baseHeight = height;
  26070. this.baseDepth = depth;
  26071. this._size = width * height * depth;
  26072. };
  26073. /** @ignore */
  26074. InternalTexture.prototype._rebuild = function () {
  26075. var _this = this;
  26076. var proxy;
  26077. this.isReady = false;
  26078. this._cachedCoordinatesMode = null;
  26079. this._cachedWrapU = null;
  26080. this._cachedWrapV = null;
  26081. this._cachedAnisotropicFilteringLevel = null;
  26082. switch (this._dataSource) {
  26083. case InternalTexture.DATASOURCE_TEMP:
  26084. return;
  26085. case InternalTexture.DATASOURCE_URL:
  26086. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26087. _this.isReady = true;
  26088. }, null, this._buffer, undefined, this.format);
  26089. proxy._swapAndDie(this);
  26090. return;
  26091. case InternalTexture.DATASOURCE_RAW:
  26092. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26093. proxy._swapAndDie(this);
  26094. this.isReady = true;
  26095. return;
  26096. case InternalTexture.DATASOURCE_RAW3D:
  26097. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26098. proxy._swapAndDie(this);
  26099. this.isReady = true;
  26100. return;
  26101. case InternalTexture.DATASOURCE_DYNAMIC:
  26102. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26103. proxy._swapAndDie(this);
  26104. // The engine will make sure to update content so no need to flag it as isReady = true
  26105. return;
  26106. case InternalTexture.DATASOURCE_RENDERTARGET:
  26107. var options = new BABYLON.RenderTargetCreationOptions();
  26108. options.generateDepthBuffer = this._generateDepthBuffer;
  26109. options.generateMipMaps = this.generateMipMaps;
  26110. options.generateStencilBuffer = this._generateStencilBuffer;
  26111. options.samplingMode = this.samplingMode;
  26112. options.type = this.type;
  26113. if (this.isCube) {
  26114. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26115. }
  26116. else {
  26117. var size = {
  26118. width: this.width,
  26119. height: this.height
  26120. };
  26121. proxy = this._engine.createRenderTargetTexture(size, options);
  26122. }
  26123. proxy._swapAndDie(this);
  26124. this.isReady = true;
  26125. return;
  26126. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26127. var depthTextureOptions = {
  26128. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26129. comparisonFunction: this._comparisonFunction,
  26130. generateStencil: this._generateStencilBuffer,
  26131. };
  26132. if (this.isCube) {
  26133. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26134. }
  26135. else {
  26136. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26137. }
  26138. proxy._swapAndDie(this);
  26139. this.isReady = true;
  26140. return;
  26141. case InternalTexture.DATASOURCE_CUBE:
  26142. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26143. _this.isReady = true;
  26144. }, null, this.format, this._extension);
  26145. proxy._swapAndDie(this);
  26146. return;
  26147. case InternalTexture.DATASOURCE_CUBERAW:
  26148. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26149. proxy._swapAndDie(this);
  26150. this.isReady = true;
  26151. return;
  26152. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26153. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26154. if (proxy) {
  26155. proxy._swapAndDie(_this);
  26156. }
  26157. _this.isReady = true;
  26158. }, null, this.format, this._extension);
  26159. return;
  26160. }
  26161. };
  26162. InternalTexture.prototype._swapAndDie = function (target) {
  26163. target._webGLTexture = this._webGLTexture;
  26164. if (this._framebuffer) {
  26165. target._framebuffer = this._framebuffer;
  26166. }
  26167. if (this._depthStencilBuffer) {
  26168. target._depthStencilBuffer = this._depthStencilBuffer;
  26169. }
  26170. if (this._lodTextureHigh) {
  26171. if (target._lodTextureHigh) {
  26172. target._lodTextureHigh.dispose();
  26173. }
  26174. target._lodTextureHigh = this._lodTextureHigh;
  26175. }
  26176. if (this._lodTextureMid) {
  26177. if (target._lodTextureMid) {
  26178. target._lodTextureMid.dispose();
  26179. }
  26180. target._lodTextureMid = this._lodTextureMid;
  26181. }
  26182. if (this._lodTextureLow) {
  26183. if (target._lodTextureLow) {
  26184. target._lodTextureLow.dispose();
  26185. }
  26186. target._lodTextureLow = this._lodTextureLow;
  26187. }
  26188. var cache = this._engine.getLoadedTexturesCache();
  26189. var index = cache.indexOf(this);
  26190. if (index !== -1) {
  26191. cache.splice(index, 1);
  26192. }
  26193. };
  26194. /**
  26195. * Dispose the current allocated resources
  26196. */
  26197. InternalTexture.prototype.dispose = function () {
  26198. if (!this._webGLTexture) {
  26199. return;
  26200. }
  26201. this._references--;
  26202. if (this._references === 0) {
  26203. this._engine._releaseTexture(this);
  26204. this._webGLTexture = null;
  26205. this.previous = null;
  26206. this.next = null;
  26207. }
  26208. };
  26209. /**
  26210. * The source of the texture data is unknown
  26211. */
  26212. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26213. /**
  26214. * Texture data comes from an URL
  26215. */
  26216. InternalTexture.DATASOURCE_URL = 1;
  26217. /**
  26218. * Texture data is only used for temporary storage
  26219. */
  26220. InternalTexture.DATASOURCE_TEMP = 2;
  26221. /**
  26222. * Texture data comes from raw data (ArrayBuffer)
  26223. */
  26224. InternalTexture.DATASOURCE_RAW = 3;
  26225. /**
  26226. * Texture content is dynamic (video or dynamic texture)
  26227. */
  26228. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26229. /**
  26230. * Texture content is generated by rendering to it
  26231. */
  26232. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26233. /**
  26234. * Texture content is part of a multi render target process
  26235. */
  26236. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26237. /**
  26238. * Texture data comes from a cube data file
  26239. */
  26240. InternalTexture.DATASOURCE_CUBE = 7;
  26241. /**
  26242. * Texture data comes from a raw cube data
  26243. */
  26244. InternalTexture.DATASOURCE_CUBERAW = 8;
  26245. /**
  26246. * Texture data come from a prefiltered cube data file
  26247. */
  26248. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26249. /**
  26250. * Texture content is raw 3D data
  26251. */
  26252. InternalTexture.DATASOURCE_RAW3D = 10;
  26253. /**
  26254. * Texture content is a depth texture
  26255. */
  26256. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26257. return InternalTexture;
  26258. }());
  26259. BABYLON.InternalTexture = InternalTexture;
  26260. })(BABYLON || (BABYLON = {}));
  26261. //# sourceMappingURL=babylon.internalTexture.js.map
  26262. var BABYLON;
  26263. (function (BABYLON) {
  26264. var BaseTexture = /** @class */ (function () {
  26265. function BaseTexture(scene) {
  26266. this._hasAlpha = false;
  26267. this.getAlphaFromRGB = false;
  26268. this.level = 1;
  26269. this.coordinatesIndex = 0;
  26270. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26271. /**
  26272. * | Value | Type | Description |
  26273. * | ----- | ------------------ | ----------- |
  26274. * | 0 | CLAMP_ADDRESSMODE | |
  26275. * | 1 | WRAP_ADDRESSMODE | |
  26276. * | 2 | MIRROR_ADDRESSMODE | |
  26277. */
  26278. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26279. /**
  26280. * | Value | Type | Description |
  26281. * | ----- | ------------------ | ----------- |
  26282. * | 0 | CLAMP_ADDRESSMODE | |
  26283. * | 1 | WRAP_ADDRESSMODE | |
  26284. * | 2 | MIRROR_ADDRESSMODE | |
  26285. */
  26286. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26287. /**
  26288. * | Value | Type | Description |
  26289. * | ----- | ------------------ | ----------- |
  26290. * | 0 | CLAMP_ADDRESSMODE | |
  26291. * | 1 | WRAP_ADDRESSMODE | |
  26292. * | 2 | MIRROR_ADDRESSMODE | |
  26293. */
  26294. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26295. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26296. this.isCube = false;
  26297. this.is3D = false;
  26298. this.gammaSpace = true;
  26299. this.invertZ = false;
  26300. this.lodLevelInAlpha = false;
  26301. this.lodGenerationOffset = 0.0;
  26302. this.lodGenerationScale = 0.8;
  26303. this.isRenderTarget = false;
  26304. this.animations = new Array();
  26305. /**
  26306. * An event triggered when the texture is disposed.
  26307. * @type {BABYLON.Observable}
  26308. */
  26309. this.onDisposeObservable = new BABYLON.Observable();
  26310. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26312. if (this._scene) {
  26313. this._scene.textures.push(this);
  26314. }
  26315. this._uid = null;
  26316. }
  26317. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26318. get: function () {
  26319. return this._hasAlpha;
  26320. },
  26321. set: function (value) {
  26322. if (this._hasAlpha === value) {
  26323. return;
  26324. }
  26325. this._hasAlpha = value;
  26326. if (this._scene) {
  26327. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26328. }
  26329. },
  26330. enumerable: true,
  26331. configurable: true
  26332. });
  26333. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26334. get: function () {
  26335. return this._coordinatesMode;
  26336. },
  26337. /**
  26338. * How a texture is mapped.
  26339. *
  26340. * | Value | Type | Description |
  26341. * | ----- | ----------------------------------- | ----------- |
  26342. * | 0 | EXPLICIT_MODE | |
  26343. * | 1 | SPHERICAL_MODE | |
  26344. * | 2 | PLANAR_MODE | |
  26345. * | 3 | CUBIC_MODE | |
  26346. * | 4 | PROJECTION_MODE | |
  26347. * | 5 | SKYBOX_MODE | |
  26348. * | 6 | INVCUBIC_MODE | |
  26349. * | 7 | EQUIRECTANGULAR_MODE | |
  26350. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26351. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26352. */
  26353. set: function (value) {
  26354. if (this._coordinatesMode === value) {
  26355. return;
  26356. }
  26357. this._coordinatesMode = value;
  26358. if (this._scene) {
  26359. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26360. }
  26361. },
  26362. enumerable: true,
  26363. configurable: true
  26364. });
  26365. Object.defineProperty(BaseTexture.prototype, "uid", {
  26366. get: function () {
  26367. if (!this._uid) {
  26368. this._uid = BABYLON.Tools.RandomId();
  26369. }
  26370. return this._uid;
  26371. },
  26372. enumerable: true,
  26373. configurable: true
  26374. });
  26375. BaseTexture.prototype.toString = function () {
  26376. return this.name;
  26377. };
  26378. BaseTexture.prototype.getClassName = function () {
  26379. return "BaseTexture";
  26380. };
  26381. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26382. set: function (callback) {
  26383. if (this._onDisposeObserver) {
  26384. this.onDisposeObservable.remove(this._onDisposeObserver);
  26385. }
  26386. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26387. },
  26388. enumerable: true,
  26389. configurable: true
  26390. });
  26391. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26392. get: function () {
  26393. return true;
  26394. },
  26395. enumerable: true,
  26396. configurable: true
  26397. });
  26398. BaseTexture.prototype.getScene = function () {
  26399. return this._scene;
  26400. };
  26401. BaseTexture.prototype.getTextureMatrix = function () {
  26402. return BABYLON.Matrix.IdentityReadOnly;
  26403. };
  26404. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26405. return BABYLON.Matrix.IdentityReadOnly;
  26406. };
  26407. BaseTexture.prototype.getInternalTexture = function () {
  26408. return this._texture;
  26409. };
  26410. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26411. return !this.isBlocking || this.isReady();
  26412. };
  26413. BaseTexture.prototype.isReady = function () {
  26414. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26415. this.delayLoad();
  26416. return false;
  26417. }
  26418. if (this._texture) {
  26419. return this._texture.isReady;
  26420. }
  26421. return false;
  26422. };
  26423. BaseTexture.prototype.getSize = function () {
  26424. if (this._texture && this._texture.width) {
  26425. return new BABYLON.Size(this._texture.width, this._texture.height);
  26426. }
  26427. if (this._texture && this._texture._size) {
  26428. return new BABYLON.Size(this._texture._size, this._texture._size);
  26429. }
  26430. return BABYLON.Size.Zero();
  26431. };
  26432. BaseTexture.prototype.getBaseSize = function () {
  26433. if (!this.isReady() || !this._texture)
  26434. return BABYLON.Size.Zero();
  26435. if (this._texture._size) {
  26436. return new BABYLON.Size(this._texture._size, this._texture._size);
  26437. }
  26438. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26439. };
  26440. BaseTexture.prototype.scale = function (ratio) {
  26441. };
  26442. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26443. get: function () {
  26444. return false;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26450. if (!this._scene) {
  26451. return null;
  26452. }
  26453. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26454. for (var index = 0; index < texturesCache.length; index++) {
  26455. var texturesCacheEntry = texturesCache[index];
  26456. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26457. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26458. texturesCacheEntry.incrementReferences();
  26459. return texturesCacheEntry;
  26460. }
  26461. }
  26462. }
  26463. return null;
  26464. };
  26465. BaseTexture.prototype._rebuild = function () {
  26466. };
  26467. BaseTexture.prototype.delayLoad = function () {
  26468. };
  26469. BaseTexture.prototype.clone = function () {
  26470. return null;
  26471. };
  26472. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26473. get: function () {
  26474. if (!this._texture) {
  26475. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26476. }
  26477. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26478. },
  26479. enumerable: true,
  26480. configurable: true
  26481. });
  26482. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26483. get: function () {
  26484. if (!this._texture) {
  26485. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26486. }
  26487. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. BaseTexture.prototype.readPixels = function (faceIndex) {
  26493. if (faceIndex === void 0) { faceIndex = 0; }
  26494. if (!this._texture) {
  26495. return null;
  26496. }
  26497. var size = this.getSize();
  26498. var scene = this.getScene();
  26499. if (!scene) {
  26500. return null;
  26501. }
  26502. var engine = scene.getEngine();
  26503. if (this._texture.isCube) {
  26504. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26505. }
  26506. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26507. };
  26508. BaseTexture.prototype.releaseInternalTexture = function () {
  26509. if (this._texture) {
  26510. this._texture.dispose();
  26511. this._texture = null;
  26512. }
  26513. };
  26514. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26515. get: function () {
  26516. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26517. return null;
  26518. }
  26519. if (!this._texture._sphericalPolynomial) {
  26520. this._texture._sphericalPolynomial =
  26521. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26522. }
  26523. return this._texture._sphericalPolynomial;
  26524. },
  26525. set: function (value) {
  26526. if (this._texture) {
  26527. this._texture._sphericalPolynomial = value;
  26528. }
  26529. },
  26530. enumerable: true,
  26531. configurable: true
  26532. });
  26533. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26534. get: function () {
  26535. if (this._texture) {
  26536. return this._texture._lodTextureHigh;
  26537. }
  26538. return null;
  26539. },
  26540. enumerable: true,
  26541. configurable: true
  26542. });
  26543. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26544. get: function () {
  26545. if (this._texture) {
  26546. return this._texture._lodTextureMid;
  26547. }
  26548. return null;
  26549. },
  26550. enumerable: true,
  26551. configurable: true
  26552. });
  26553. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26554. get: function () {
  26555. if (this._texture) {
  26556. return this._texture._lodTextureLow;
  26557. }
  26558. return null;
  26559. },
  26560. enumerable: true,
  26561. configurable: true
  26562. });
  26563. BaseTexture.prototype.dispose = function () {
  26564. if (!this._scene) {
  26565. return;
  26566. }
  26567. // Animations
  26568. this._scene.stopAnimation(this);
  26569. // Remove from scene
  26570. this._scene._removePendingData(this);
  26571. var index = this._scene.textures.indexOf(this);
  26572. if (index >= 0) {
  26573. this._scene.textures.splice(index, 1);
  26574. }
  26575. if (this._texture === undefined) {
  26576. return;
  26577. }
  26578. // Release
  26579. this.releaseInternalTexture();
  26580. // Callback
  26581. this.onDisposeObservable.notifyObservers(this);
  26582. this.onDisposeObservable.clear();
  26583. };
  26584. BaseTexture.prototype.serialize = function () {
  26585. if (!this.name) {
  26586. return null;
  26587. }
  26588. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26589. // Animations
  26590. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26591. return serializationObject;
  26592. };
  26593. BaseTexture.WhenAllReady = function (textures, callback) {
  26594. var numRemaining = textures.length;
  26595. if (numRemaining === 0) {
  26596. callback();
  26597. return;
  26598. }
  26599. var _loop_1 = function () {
  26600. texture = textures[i];
  26601. if (texture.isReady()) {
  26602. if (--numRemaining === 0) {
  26603. callback();
  26604. }
  26605. }
  26606. else {
  26607. onLoadObservable = texture.onLoadObservable;
  26608. var onLoadCallback_1 = function () {
  26609. onLoadObservable.removeCallback(onLoadCallback_1);
  26610. if (--numRemaining === 0) {
  26611. callback();
  26612. }
  26613. };
  26614. onLoadObservable.add(onLoadCallback_1);
  26615. }
  26616. };
  26617. var texture, onLoadObservable;
  26618. for (var i = 0; i < textures.length; i++) {
  26619. _loop_1();
  26620. }
  26621. };
  26622. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26623. __decorate([
  26624. BABYLON.serialize()
  26625. ], BaseTexture.prototype, "name", void 0);
  26626. __decorate([
  26627. BABYLON.serialize("hasAlpha")
  26628. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26629. __decorate([
  26630. BABYLON.serialize()
  26631. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26632. __decorate([
  26633. BABYLON.serialize()
  26634. ], BaseTexture.prototype, "level", void 0);
  26635. __decorate([
  26636. BABYLON.serialize()
  26637. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26638. __decorate([
  26639. BABYLON.serialize("coordinatesMode")
  26640. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26641. __decorate([
  26642. BABYLON.serialize()
  26643. ], BaseTexture.prototype, "wrapU", void 0);
  26644. __decorate([
  26645. BABYLON.serialize()
  26646. ], BaseTexture.prototype, "wrapV", void 0);
  26647. __decorate([
  26648. BABYLON.serialize()
  26649. ], BaseTexture.prototype, "wrapR", void 0);
  26650. __decorate([
  26651. BABYLON.serialize()
  26652. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26653. __decorate([
  26654. BABYLON.serialize()
  26655. ], BaseTexture.prototype, "isCube", void 0);
  26656. __decorate([
  26657. BABYLON.serialize()
  26658. ], BaseTexture.prototype, "is3D", void 0);
  26659. __decorate([
  26660. BABYLON.serialize()
  26661. ], BaseTexture.prototype, "gammaSpace", void 0);
  26662. __decorate([
  26663. BABYLON.serialize()
  26664. ], BaseTexture.prototype, "invertZ", void 0);
  26665. __decorate([
  26666. BABYLON.serialize()
  26667. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26668. __decorate([
  26669. BABYLON.serialize()
  26670. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26671. __decorate([
  26672. BABYLON.serialize()
  26673. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26674. __decorate([
  26675. BABYLON.serialize()
  26676. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26677. return BaseTexture;
  26678. }());
  26679. BABYLON.BaseTexture = BaseTexture;
  26680. })(BABYLON || (BABYLON = {}));
  26681. //# sourceMappingURL=babylon.baseTexture.js.map
  26682. var BABYLON;
  26683. (function (BABYLON) {
  26684. var Texture = /** @class */ (function (_super) {
  26685. __extends(Texture, _super);
  26686. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26687. if (noMipmap === void 0) { noMipmap = false; }
  26688. if (invertY === void 0) { invertY = true; }
  26689. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26690. if (onLoad === void 0) { onLoad = null; }
  26691. if (onError === void 0) { onError = null; }
  26692. if (buffer === void 0) { buffer = null; }
  26693. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26694. var _this = _super.call(this, scene) || this;
  26695. _this.uOffset = 0;
  26696. _this.vOffset = 0;
  26697. _this.uScale = 1.0;
  26698. _this.vScale = 1.0;
  26699. _this.uAng = 0;
  26700. _this.vAng = 0;
  26701. _this.wAng = 0;
  26702. _this._isBlocking = true;
  26703. _this.name = url || "";
  26704. _this.url = url;
  26705. _this._noMipmap = noMipmap;
  26706. _this._invertY = invertY;
  26707. _this._samplingMode = samplingMode;
  26708. _this._buffer = buffer;
  26709. _this._deleteBuffer = deleteBuffer;
  26710. if (format) {
  26711. _this._format = format;
  26712. }
  26713. scene = _this.getScene();
  26714. if (!scene) {
  26715. return _this;
  26716. }
  26717. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26718. var load = function () {
  26719. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26720. _this.onLoadObservable.notifyObservers(_this);
  26721. }
  26722. if (onLoad) {
  26723. onLoad();
  26724. }
  26725. if (!_this.isBlocking && scene) {
  26726. scene.resetCachedMaterial();
  26727. }
  26728. };
  26729. if (!_this.url) {
  26730. _this._delayedOnLoad = load;
  26731. _this._delayedOnError = onError;
  26732. return _this;
  26733. }
  26734. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26735. if (!_this._texture) {
  26736. if (!scene.useDelayedTextureLoading) {
  26737. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26738. if (deleteBuffer) {
  26739. delete _this._buffer;
  26740. }
  26741. }
  26742. else {
  26743. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26744. _this._delayedOnLoad = load;
  26745. _this._delayedOnError = onError;
  26746. }
  26747. }
  26748. else {
  26749. if (_this._texture.isReady) {
  26750. BABYLON.Tools.SetImmediate(function () { return load(); });
  26751. }
  26752. else {
  26753. _this._texture.onLoadedObservable.add(load);
  26754. }
  26755. }
  26756. return _this;
  26757. }
  26758. Object.defineProperty(Texture.prototype, "noMipmap", {
  26759. get: function () {
  26760. return this._noMipmap;
  26761. },
  26762. enumerable: true,
  26763. configurable: true
  26764. });
  26765. Object.defineProperty(Texture.prototype, "isBlocking", {
  26766. get: function () {
  26767. return this._isBlocking;
  26768. },
  26769. set: function (value) {
  26770. this._isBlocking = value;
  26771. },
  26772. enumerable: true,
  26773. configurable: true
  26774. });
  26775. Object.defineProperty(Texture.prototype, "samplingMode", {
  26776. get: function () {
  26777. return this._samplingMode;
  26778. },
  26779. enumerable: true,
  26780. configurable: true
  26781. });
  26782. Texture.prototype.updateURL = function (url) {
  26783. this.url = url;
  26784. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26785. this.delayLoad();
  26786. };
  26787. Texture.prototype.delayLoad = function () {
  26788. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26789. return;
  26790. }
  26791. var scene = this.getScene();
  26792. if (!scene) {
  26793. return;
  26794. }
  26795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26796. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26797. if (!this._texture) {
  26798. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26799. if (this._deleteBuffer) {
  26800. delete this._buffer;
  26801. }
  26802. }
  26803. else {
  26804. if (this._delayedOnLoad) {
  26805. if (this._texture.isReady) {
  26806. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26807. }
  26808. else {
  26809. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26810. }
  26811. }
  26812. }
  26813. this._delayedOnLoad = null;
  26814. this._delayedOnError = null;
  26815. };
  26816. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26817. if (!this._texture) {
  26818. return;
  26819. }
  26820. var scene = this.getScene();
  26821. if (!scene) {
  26822. return;
  26823. }
  26824. this._samplingMode = samplingMode;
  26825. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26826. };
  26827. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26828. x *= this.uScale;
  26829. y *= this.vScale;
  26830. x -= 0.5 * this.uScale;
  26831. y -= 0.5 * this.vScale;
  26832. z -= 0.5;
  26833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26834. t.x += 0.5 * this.uScale + this.uOffset;
  26835. t.y += 0.5 * this.vScale + this.vOffset;
  26836. t.z += 0.5;
  26837. };
  26838. Texture.prototype.getTextureMatrix = function () {
  26839. var _this = this;
  26840. if (this.uOffset === this._cachedUOffset &&
  26841. this.vOffset === this._cachedVOffset &&
  26842. this.uScale === this._cachedUScale &&
  26843. this.vScale === this._cachedVScale &&
  26844. this.uAng === this._cachedUAng &&
  26845. this.vAng === this._cachedVAng &&
  26846. this.wAng === this._cachedWAng) {
  26847. return this._cachedTextureMatrix;
  26848. }
  26849. this._cachedUOffset = this.uOffset;
  26850. this._cachedVOffset = this.vOffset;
  26851. this._cachedUScale = this.uScale;
  26852. this._cachedVScale = this.vScale;
  26853. this._cachedUAng = this.uAng;
  26854. this._cachedVAng = this.vAng;
  26855. this._cachedWAng = this.wAng;
  26856. if (!this._cachedTextureMatrix) {
  26857. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26858. this._rowGenerationMatrix = new BABYLON.Matrix();
  26859. this._t0 = BABYLON.Vector3.Zero();
  26860. this._t1 = BABYLON.Vector3.Zero();
  26861. this._t2 = BABYLON.Vector3.Zero();
  26862. }
  26863. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26864. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26865. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26866. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26867. this._t1.subtractInPlace(this._t0);
  26868. this._t2.subtractInPlace(this._t0);
  26869. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26870. this._cachedTextureMatrix.m[0] = this._t1.x;
  26871. this._cachedTextureMatrix.m[1] = this._t1.y;
  26872. this._cachedTextureMatrix.m[2] = this._t1.z;
  26873. this._cachedTextureMatrix.m[4] = this._t2.x;
  26874. this._cachedTextureMatrix.m[5] = this._t2.y;
  26875. this._cachedTextureMatrix.m[6] = this._t2.z;
  26876. this._cachedTextureMatrix.m[8] = this._t0.x;
  26877. this._cachedTextureMatrix.m[9] = this._t0.y;
  26878. this._cachedTextureMatrix.m[10] = this._t0.z;
  26879. var scene = this.getScene();
  26880. if (!scene) {
  26881. return this._cachedTextureMatrix;
  26882. }
  26883. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26884. return mat.hasTexture(_this);
  26885. });
  26886. return this._cachedTextureMatrix;
  26887. };
  26888. Texture.prototype.getReflectionTextureMatrix = function () {
  26889. var _this = this;
  26890. var scene = this.getScene();
  26891. if (!scene) {
  26892. return this._cachedTextureMatrix;
  26893. }
  26894. if (this.uOffset === this._cachedUOffset &&
  26895. this.vOffset === this._cachedVOffset &&
  26896. this.uScale === this._cachedUScale &&
  26897. this.vScale === this._cachedVScale &&
  26898. this.coordinatesMode === this._cachedCoordinatesMode) {
  26899. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26900. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26901. return this._cachedTextureMatrix;
  26902. }
  26903. }
  26904. else {
  26905. return this._cachedTextureMatrix;
  26906. }
  26907. }
  26908. if (!this._cachedTextureMatrix) {
  26909. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26910. }
  26911. if (!this._projectionModeMatrix) {
  26912. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26913. }
  26914. this._cachedUOffset = this.uOffset;
  26915. this._cachedVOffset = this.vOffset;
  26916. this._cachedUScale = this.uScale;
  26917. this._cachedVScale = this.vScale;
  26918. this._cachedCoordinatesMode = this.coordinatesMode;
  26919. switch (this.coordinatesMode) {
  26920. case Texture.PLANAR_MODE:
  26921. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26922. this._cachedTextureMatrix[0] = this.uScale;
  26923. this._cachedTextureMatrix[5] = this.vScale;
  26924. this._cachedTextureMatrix[12] = this.uOffset;
  26925. this._cachedTextureMatrix[13] = this.vOffset;
  26926. break;
  26927. case Texture.PROJECTION_MODE:
  26928. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26929. this._projectionModeMatrix.m[0] = 0.5;
  26930. this._projectionModeMatrix.m[5] = -0.5;
  26931. this._projectionModeMatrix.m[10] = 0.0;
  26932. this._projectionModeMatrix.m[12] = 0.5;
  26933. this._projectionModeMatrix.m[13] = 0.5;
  26934. this._projectionModeMatrix.m[14] = 1.0;
  26935. this._projectionModeMatrix.m[15] = 1.0;
  26936. var projectionMatrix = scene.getProjectionMatrix();
  26937. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26938. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26939. break;
  26940. default:
  26941. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26942. break;
  26943. }
  26944. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26945. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26946. });
  26947. return this._cachedTextureMatrix;
  26948. };
  26949. Texture.prototype.clone = function () {
  26950. var _this = this;
  26951. return BABYLON.SerializationHelper.Clone(function () {
  26952. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26953. }, this);
  26954. };
  26955. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26956. get: function () {
  26957. if (!this._onLoadObservable) {
  26958. this._onLoadObservable = new BABYLON.Observable();
  26959. }
  26960. return this._onLoadObservable;
  26961. },
  26962. enumerable: true,
  26963. configurable: true
  26964. });
  26965. Texture.prototype.serialize = function () {
  26966. var serializationObject = _super.prototype.serialize.call(this);
  26967. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26968. serializationObject.base64String = this._buffer;
  26969. serializationObject.name = serializationObject.name.replace("data:", "");
  26970. }
  26971. return serializationObject;
  26972. };
  26973. Texture.prototype.getClassName = function () {
  26974. return "Texture";
  26975. };
  26976. Texture.prototype.dispose = function () {
  26977. _super.prototype.dispose.call(this);
  26978. if (this.onLoadObservable) {
  26979. this.onLoadObservable.clear();
  26980. this._onLoadObservable = null;
  26981. }
  26982. this._delayedOnLoad = null;
  26983. this._delayedOnError = null;
  26984. };
  26985. // Statics
  26986. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26987. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26988. if (onLoad === void 0) { onLoad = null; }
  26989. if (onError === void 0) { onError = null; }
  26990. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26991. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26992. };
  26993. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26994. if (parsedTexture.customType) {
  26995. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26996. // Update Sampling Mode
  26997. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26998. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26999. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27000. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27001. }
  27002. }
  27003. return parsedCustomTexture;
  27004. }
  27005. if (parsedTexture.isCube) {
  27006. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27007. }
  27008. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27009. return null;
  27010. }
  27011. var texture = BABYLON.SerializationHelper.Parse(function () {
  27012. var generateMipMaps = true;
  27013. if (parsedTexture.noMipmap) {
  27014. generateMipMaps = false;
  27015. }
  27016. if (parsedTexture.mirrorPlane) {
  27017. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27018. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27019. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27020. return mirrorTexture;
  27021. }
  27022. else if (parsedTexture.isRenderTarget) {
  27023. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27024. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27025. return renderTargetTexture;
  27026. }
  27027. else {
  27028. var texture;
  27029. if (parsedTexture.base64String) {
  27030. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27031. }
  27032. else {
  27033. var url = rootUrl + parsedTexture.name;
  27034. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27035. url = parsedTexture.url;
  27036. }
  27037. texture = new Texture(url, scene, !generateMipMaps);
  27038. }
  27039. return texture;
  27040. }
  27041. }, parsedTexture, scene);
  27042. // Update Sampling Mode
  27043. if (parsedTexture.samplingMode) {
  27044. var sampling = parsedTexture.samplingMode;
  27045. if (texture._samplingMode !== sampling) {
  27046. texture.updateSamplingMode(sampling);
  27047. }
  27048. }
  27049. // Animations
  27050. if (parsedTexture.animations) {
  27051. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27052. var parsedAnimation = parsedTexture.animations[animationIndex];
  27053. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27054. }
  27055. }
  27056. return texture;
  27057. };
  27058. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27059. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27060. if (noMipmap === void 0) { noMipmap = false; }
  27061. if (invertY === void 0) { invertY = true; }
  27062. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27063. if (onLoad === void 0) { onLoad = null; }
  27064. if (onError === void 0) { onError = null; }
  27065. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27066. if (name.substr(0, 5) !== "data:") {
  27067. name = "data:" + name;
  27068. }
  27069. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27070. };
  27071. // Constants
  27072. Texture.NEAREST_SAMPLINGMODE = 1;
  27073. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27074. Texture.BILINEAR_SAMPLINGMODE = 2;
  27075. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27076. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27077. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27078. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27079. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27080. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27081. Texture.NEAREST_LINEAR = 7;
  27082. Texture.NEAREST_NEAREST = 8;
  27083. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27084. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27085. Texture.LINEAR_LINEAR = 11;
  27086. Texture.LINEAR_NEAREST = 12;
  27087. Texture.EXPLICIT_MODE = 0;
  27088. Texture.SPHERICAL_MODE = 1;
  27089. Texture.PLANAR_MODE = 2;
  27090. Texture.CUBIC_MODE = 3;
  27091. Texture.PROJECTION_MODE = 4;
  27092. Texture.SKYBOX_MODE = 5;
  27093. Texture.INVCUBIC_MODE = 6;
  27094. Texture.EQUIRECTANGULAR_MODE = 7;
  27095. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27096. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27097. Texture.CLAMP_ADDRESSMODE = 0;
  27098. Texture.WRAP_ADDRESSMODE = 1;
  27099. Texture.MIRROR_ADDRESSMODE = 2;
  27100. /**
  27101. * 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
  27102. */
  27103. Texture.UseSerializedUrlIfAny = false;
  27104. __decorate([
  27105. BABYLON.serialize()
  27106. ], Texture.prototype, "url", void 0);
  27107. __decorate([
  27108. BABYLON.serialize()
  27109. ], Texture.prototype, "uOffset", void 0);
  27110. __decorate([
  27111. BABYLON.serialize()
  27112. ], Texture.prototype, "vOffset", void 0);
  27113. __decorate([
  27114. BABYLON.serialize()
  27115. ], Texture.prototype, "uScale", void 0);
  27116. __decorate([
  27117. BABYLON.serialize()
  27118. ], Texture.prototype, "vScale", void 0);
  27119. __decorate([
  27120. BABYLON.serialize()
  27121. ], Texture.prototype, "uAng", void 0);
  27122. __decorate([
  27123. BABYLON.serialize()
  27124. ], Texture.prototype, "vAng", void 0);
  27125. __decorate([
  27126. BABYLON.serialize()
  27127. ], Texture.prototype, "wAng", void 0);
  27128. __decorate([
  27129. BABYLON.serialize()
  27130. ], Texture.prototype, "isBlocking", null);
  27131. return Texture;
  27132. }(BABYLON.BaseTexture));
  27133. BABYLON.Texture = Texture;
  27134. })(BABYLON || (BABYLON = {}));
  27135. //# sourceMappingURL=babylon.texture.js.map
  27136. var BABYLON;
  27137. (function (BABYLON) {
  27138. var _InstancesBatch = /** @class */ (function () {
  27139. function _InstancesBatch() {
  27140. this.mustReturn = false;
  27141. this.visibleInstances = new Array();
  27142. this.renderSelf = new Array();
  27143. }
  27144. return _InstancesBatch;
  27145. }());
  27146. BABYLON._InstancesBatch = _InstancesBatch;
  27147. var Mesh = /** @class */ (function (_super) {
  27148. __extends(Mesh, _super);
  27149. /**
  27150. * @constructor
  27151. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27152. * @param {Scene} scene The scene to add this mesh to.
  27153. * @param {Node} parent The parent of this mesh, if it has one
  27154. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27155. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27156. * When false, achieved by calling a clone(), also passing False.
  27157. * This will make creation of children, recursive.
  27158. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27159. */
  27160. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27161. if (scene === void 0) { scene = null; }
  27162. if (parent === void 0) { parent = null; }
  27163. if (source === void 0) { source = null; }
  27164. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27165. var _this = _super.call(this, name, scene) || this;
  27166. // Events
  27167. /**
  27168. * An event triggered before rendering the mesh
  27169. * @type {BABYLON.Observable}
  27170. */
  27171. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27172. /**
  27173. * An event triggered after rendering the mesh
  27174. * @type {BABYLON.Observable}
  27175. */
  27176. _this.onAfterRenderObservable = new BABYLON.Observable();
  27177. /**
  27178. * An event triggered before drawing the mesh
  27179. * @type {BABYLON.Observable}
  27180. */
  27181. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27182. // Members
  27183. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27184. _this.instances = new Array();
  27185. _this._LODLevels = new Array();
  27186. _this._visibleInstances = {};
  27187. _this._renderIdForInstances = new Array();
  27188. _this._batchCache = new _InstancesBatch();
  27189. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27190. // Use by builder only to know what orientation were the mesh build in.
  27191. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27192. _this.overrideMaterialSideOrientation = null;
  27193. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27194. // Will be used to save a source mesh reference, If any
  27195. _this._source = null;
  27196. scene = _this.getScene();
  27197. if (source) {
  27198. // Source mesh
  27199. _this._source = source;
  27200. // Geometry
  27201. if (source._geometry) {
  27202. source._geometry.applyToMesh(_this);
  27203. }
  27204. // Deep copy
  27205. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27206. // Metadata
  27207. if (source.metadata && source.metadata.clone) {
  27208. _this.metadata = source.metadata.clone();
  27209. }
  27210. else {
  27211. _this.metadata = source.metadata;
  27212. }
  27213. // Tags
  27214. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27215. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27216. }
  27217. // Parent
  27218. _this.parent = source.parent;
  27219. // Pivot
  27220. _this.setPivotMatrix(source.getPivotMatrix());
  27221. _this.id = name + "." + source.id;
  27222. // Material
  27223. _this.material = source.material;
  27224. var index;
  27225. if (!doNotCloneChildren) {
  27226. // Children
  27227. var directDescendants = source.getDescendants(true);
  27228. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27229. var child = directDescendants[index_1];
  27230. if (child.clone) {
  27231. child.clone(name + "." + child.name, _this);
  27232. }
  27233. }
  27234. }
  27235. // Physics clone
  27236. var physicsEngine = _this.getScene().getPhysicsEngine();
  27237. if (clonePhysicsImpostor && physicsEngine) {
  27238. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27239. if (impostor) {
  27240. _this.physicsImpostor = impostor.clone(_this);
  27241. }
  27242. }
  27243. // Particles
  27244. for (index = 0; index < scene.particleSystems.length; index++) {
  27245. var system = scene.particleSystems[index];
  27246. if (system.emitter === source) {
  27247. system.clone(system.name, _this);
  27248. }
  27249. }
  27250. _this.computeWorldMatrix(true);
  27251. }
  27252. // Parent
  27253. if (parent !== null) {
  27254. _this.parent = parent;
  27255. }
  27256. return _this;
  27257. }
  27258. Object.defineProperty(Mesh, "FRONTSIDE", {
  27259. /**
  27260. * Mesh side orientation : usually the external or front surface
  27261. */
  27262. get: function () {
  27263. return Mesh._FRONTSIDE;
  27264. },
  27265. enumerable: true,
  27266. configurable: true
  27267. });
  27268. Object.defineProperty(Mesh, "BACKSIDE", {
  27269. /**
  27270. * Mesh side orientation : usually the internal or back surface
  27271. */
  27272. get: function () {
  27273. return Mesh._BACKSIDE;
  27274. },
  27275. enumerable: true,
  27276. configurable: true
  27277. });
  27278. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27279. /**
  27280. * Mesh side orientation : both internal and external or front and back surfaces
  27281. */
  27282. get: function () {
  27283. return Mesh._DOUBLESIDE;
  27284. },
  27285. enumerable: true,
  27286. configurable: true
  27287. });
  27288. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27289. /**
  27290. * Mesh side orientation : by default, `FRONTSIDE`
  27291. */
  27292. get: function () {
  27293. return Mesh._DEFAULTSIDE;
  27294. },
  27295. enumerable: true,
  27296. configurable: true
  27297. });
  27298. Object.defineProperty(Mesh, "NO_CAP", {
  27299. /**
  27300. * Mesh cap setting : no cap
  27301. */
  27302. get: function () {
  27303. return Mesh._NO_CAP;
  27304. },
  27305. enumerable: true,
  27306. configurable: true
  27307. });
  27308. Object.defineProperty(Mesh, "CAP_START", {
  27309. /**
  27310. * Mesh cap setting : one cap at the beginning of the mesh
  27311. */
  27312. get: function () {
  27313. return Mesh._CAP_START;
  27314. },
  27315. enumerable: true,
  27316. configurable: true
  27317. });
  27318. Object.defineProperty(Mesh, "CAP_END", {
  27319. /**
  27320. * Mesh cap setting : one cap at the end of the mesh
  27321. */
  27322. get: function () {
  27323. return Mesh._CAP_END;
  27324. },
  27325. enumerable: true,
  27326. configurable: true
  27327. });
  27328. Object.defineProperty(Mesh, "CAP_ALL", {
  27329. /**
  27330. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27331. */
  27332. get: function () {
  27333. return Mesh._CAP_ALL;
  27334. },
  27335. enumerable: true,
  27336. configurable: true
  27337. });
  27338. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27339. set: function (callback) {
  27340. if (this._onBeforeDrawObserver) {
  27341. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27342. }
  27343. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27349. get: function () {
  27350. return this._morphTargetManager;
  27351. },
  27352. set: function (value) {
  27353. if (this._morphTargetManager === value) {
  27354. return;
  27355. }
  27356. this._morphTargetManager = value;
  27357. this._syncGeometryWithMorphTargetManager();
  27358. },
  27359. enumerable: true,
  27360. configurable: true
  27361. });
  27362. Object.defineProperty(Mesh.prototype, "source", {
  27363. get: function () {
  27364. return this._source;
  27365. },
  27366. enumerable: true,
  27367. configurable: true
  27368. });
  27369. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27370. get: function () {
  27371. return this._unIndexed;
  27372. },
  27373. set: function (value) {
  27374. if (this._unIndexed !== value) {
  27375. this._unIndexed = value;
  27376. this._markSubMeshesAsAttributesDirty();
  27377. }
  27378. },
  27379. enumerable: true,
  27380. configurable: true
  27381. });
  27382. // Methods
  27383. /**
  27384. * Returns the string "Mesh".
  27385. */
  27386. Mesh.prototype.getClassName = function () {
  27387. return "Mesh";
  27388. };
  27389. /**
  27390. * Returns a string.
  27391. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27392. */
  27393. Mesh.prototype.toString = function (fullDetails) {
  27394. var ret = _super.prototype.toString.call(this, fullDetails);
  27395. ret += ", n vertices: " + this.getTotalVertices();
  27396. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27397. if (this.animations) {
  27398. for (var i = 0; i < this.animations.length; i++) {
  27399. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27400. }
  27401. }
  27402. if (fullDetails) {
  27403. if (this._geometry) {
  27404. var ib = this.getIndices();
  27405. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27406. if (vb && ib) {
  27407. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27408. }
  27409. }
  27410. else {
  27411. ret += ", flat shading: UNKNOWN";
  27412. }
  27413. }
  27414. return ret;
  27415. };
  27416. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27417. /**
  27418. * True if the mesh has some Levels Of Details (LOD).
  27419. * Returns a boolean.
  27420. */
  27421. get: function () {
  27422. return this._LODLevels.length > 0;
  27423. },
  27424. enumerable: true,
  27425. configurable: true
  27426. });
  27427. /**
  27428. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27429. * @returns an array of {BABYLON.MeshLODLevel}
  27430. */
  27431. Mesh.prototype.getLODLevels = function () {
  27432. return this._LODLevels;
  27433. };
  27434. Mesh.prototype._sortLODLevels = function () {
  27435. this._LODLevels.sort(function (a, b) {
  27436. if (a.distance < b.distance) {
  27437. return 1;
  27438. }
  27439. if (a.distance > b.distance) {
  27440. return -1;
  27441. }
  27442. return 0;
  27443. });
  27444. };
  27445. /**
  27446. * Add a mesh as LOD level triggered at the given distance.
  27447. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27448. * @param {number} distance The distance from the center of the object to show this level
  27449. * @param {Mesh} mesh The mesh to be added as LOD level
  27450. * @return {Mesh} This mesh (for chaining)
  27451. */
  27452. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27453. if (mesh && mesh._masterMesh) {
  27454. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27455. return this;
  27456. }
  27457. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27458. this._LODLevels.push(level);
  27459. if (mesh) {
  27460. mesh._masterMesh = this;
  27461. }
  27462. this._sortLODLevels();
  27463. return this;
  27464. };
  27465. /**
  27466. * Returns the LOD level mesh at the passed distance or null if not found.
  27467. * It is related to the method `addLODLevel(distance, mesh)`.
  27468. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27469. * Returns an object Mesh or `null`.
  27470. */
  27471. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27472. for (var index = 0; index < this._LODLevels.length; index++) {
  27473. var level = this._LODLevels[index];
  27474. if (level.distance === distance) {
  27475. return level.mesh;
  27476. }
  27477. }
  27478. return null;
  27479. };
  27480. /**
  27481. * Remove a mesh from the LOD array
  27482. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27483. * @param {Mesh} mesh The mesh to be removed.
  27484. * @return {Mesh} This mesh (for chaining)
  27485. */
  27486. Mesh.prototype.removeLODLevel = function (mesh) {
  27487. for (var index = 0; index < this._LODLevels.length; index++) {
  27488. if (this._LODLevels[index].mesh === mesh) {
  27489. this._LODLevels.splice(index, 1);
  27490. if (mesh) {
  27491. mesh._masterMesh = null;
  27492. }
  27493. }
  27494. }
  27495. this._sortLODLevels();
  27496. return this;
  27497. };
  27498. /**
  27499. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27500. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27501. */
  27502. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27503. if (!this._LODLevels || this._LODLevels.length === 0) {
  27504. return this;
  27505. }
  27506. var bSphere;
  27507. if (boundingSphere) {
  27508. bSphere = boundingSphere;
  27509. }
  27510. else {
  27511. var boundingInfo = this.getBoundingInfo();
  27512. bSphere = boundingInfo.boundingSphere;
  27513. }
  27514. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27515. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27516. if (this.onLODLevelSelection) {
  27517. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27518. }
  27519. return this;
  27520. }
  27521. for (var index = 0; index < this._LODLevels.length; index++) {
  27522. var level = this._LODLevels[index];
  27523. if (level.distance < distanceToCamera) {
  27524. if (level.mesh) {
  27525. level.mesh._preActivate();
  27526. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27527. }
  27528. if (this.onLODLevelSelection) {
  27529. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27530. }
  27531. return level.mesh;
  27532. }
  27533. }
  27534. if (this.onLODLevelSelection) {
  27535. this.onLODLevelSelection(distanceToCamera, this, this);
  27536. }
  27537. return this;
  27538. };
  27539. Object.defineProperty(Mesh.prototype, "geometry", {
  27540. /**
  27541. * Returns the mesh internal Geometry object.
  27542. */
  27543. get: function () {
  27544. return this._geometry;
  27545. },
  27546. enumerable: true,
  27547. configurable: true
  27548. });
  27549. /**
  27550. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27551. */
  27552. Mesh.prototype.getTotalVertices = function () {
  27553. if (this._geometry === null || this._geometry === undefined) {
  27554. return 0;
  27555. }
  27556. return this._geometry.getTotalVertices();
  27557. };
  27558. /**
  27559. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27560. * 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.
  27561. * You can force the copy with forceCopy === true
  27562. * Returns null if the mesh has no geometry or no vertex buffer.
  27563. * Possible `kind` values :
  27564. * - BABYLON.VertexBuffer.PositionKind
  27565. * - BABYLON.VertexBuffer.UVKind
  27566. * - BABYLON.VertexBuffer.UV2Kind
  27567. * - BABYLON.VertexBuffer.UV3Kind
  27568. * - BABYLON.VertexBuffer.UV4Kind
  27569. * - BABYLON.VertexBuffer.UV5Kind
  27570. * - BABYLON.VertexBuffer.UV6Kind
  27571. * - BABYLON.VertexBuffer.ColorKind
  27572. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27573. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27574. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27575. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27576. */
  27577. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27578. if (!this._geometry) {
  27579. return null;
  27580. }
  27581. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27582. };
  27583. /**
  27584. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27585. * Returns `null` if the mesh has no geometry.
  27586. * Possible `kind` values :
  27587. * - BABYLON.VertexBuffer.PositionKind
  27588. * - BABYLON.VertexBuffer.UVKind
  27589. * - BABYLON.VertexBuffer.UV2Kind
  27590. * - BABYLON.VertexBuffer.UV3Kind
  27591. * - BABYLON.VertexBuffer.UV4Kind
  27592. * - BABYLON.VertexBuffer.UV5Kind
  27593. * - BABYLON.VertexBuffer.UV6Kind
  27594. * - BABYLON.VertexBuffer.ColorKind
  27595. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27596. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27597. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27598. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27599. */
  27600. Mesh.prototype.getVertexBuffer = function (kind) {
  27601. if (!this._geometry) {
  27602. return null;
  27603. }
  27604. return this._geometry.getVertexBuffer(kind);
  27605. };
  27606. /**
  27607. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27608. * Possible `kind` values :
  27609. * - BABYLON.VertexBuffer.PositionKind
  27610. * - BABYLON.VertexBuffer.UVKind
  27611. * - BABYLON.VertexBuffer.UV2Kind
  27612. * - BABYLON.VertexBuffer.UV3Kind
  27613. * - BABYLON.VertexBuffer.UV4Kind
  27614. * - BABYLON.VertexBuffer.UV5Kind
  27615. * - BABYLON.VertexBuffer.UV6Kind
  27616. * - BABYLON.VertexBuffer.ColorKind
  27617. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27618. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27619. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27620. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27621. */
  27622. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27623. if (!this._geometry) {
  27624. if (this._delayInfo) {
  27625. return this._delayInfo.indexOf(kind) !== -1;
  27626. }
  27627. return false;
  27628. }
  27629. return this._geometry.isVerticesDataPresent(kind);
  27630. };
  27631. /**
  27632. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27633. * Possible `kind` values :
  27634. * - BABYLON.VertexBuffer.PositionKind
  27635. * - BABYLON.VertexBuffer.UVKind
  27636. * - BABYLON.VertexBuffer.UV2Kind
  27637. * - BABYLON.VertexBuffer.UV3Kind
  27638. * - BABYLON.VertexBuffer.UV4Kind
  27639. * - BABYLON.VertexBuffer.UV5Kind
  27640. * - BABYLON.VertexBuffer.UV6Kind
  27641. * - BABYLON.VertexBuffer.ColorKind
  27642. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27643. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27644. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27645. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27646. */
  27647. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27648. if (!this._geometry) {
  27649. if (this._delayInfo) {
  27650. return this._delayInfo.indexOf(kind) !== -1;
  27651. }
  27652. return false;
  27653. }
  27654. return this._geometry.isVertexBufferUpdatable(kind);
  27655. };
  27656. /**
  27657. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27658. * Possible `kind` values :
  27659. * - BABYLON.VertexBuffer.PositionKind
  27660. * - BABYLON.VertexBuffer.UVKind
  27661. * - BABYLON.VertexBuffer.UV2Kind
  27662. * - BABYLON.VertexBuffer.UV3Kind
  27663. * - BABYLON.VertexBuffer.UV4Kind
  27664. * - BABYLON.VertexBuffer.UV5Kind
  27665. * - BABYLON.VertexBuffer.UV6Kind
  27666. * - BABYLON.VertexBuffer.ColorKind
  27667. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27668. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27669. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27670. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27671. */
  27672. Mesh.prototype.getVerticesDataKinds = function () {
  27673. if (!this._geometry) {
  27674. var result = new Array();
  27675. if (this._delayInfo) {
  27676. this._delayInfo.forEach(function (kind, index, array) {
  27677. result.push(kind);
  27678. });
  27679. }
  27680. return result;
  27681. }
  27682. return this._geometry.getVerticesDataKinds();
  27683. };
  27684. /**
  27685. * Returns a positive integer : the total number of indices in this mesh geometry.
  27686. * Returns zero if the mesh has no geometry.
  27687. */
  27688. Mesh.prototype.getTotalIndices = function () {
  27689. if (!this._geometry) {
  27690. return 0;
  27691. }
  27692. return this._geometry.getTotalIndices();
  27693. };
  27694. /**
  27695. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27696. * 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.
  27697. * Returns an empty array if the mesh has no geometry.
  27698. */
  27699. Mesh.prototype.getIndices = function (copyWhenShared) {
  27700. if (!this._geometry) {
  27701. return [];
  27702. }
  27703. return this._geometry.getIndices(copyWhenShared);
  27704. };
  27705. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27706. get: function () {
  27707. return this._masterMesh !== null && this._masterMesh !== undefined;
  27708. },
  27709. enumerable: true,
  27710. configurable: true
  27711. });
  27712. /**
  27713. * Determine if the current mesh is ready to be rendered
  27714. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27715. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27716. * @returns true if all associated assets are ready (material, textures, shaders)
  27717. */
  27718. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27719. if (completeCheck === void 0) { completeCheck = false; }
  27720. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27721. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27722. return false;
  27723. }
  27724. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27725. return false;
  27726. }
  27727. if (!this.subMeshes || this.subMeshes.length === 0) {
  27728. return true;
  27729. }
  27730. if (!completeCheck) {
  27731. return true;
  27732. }
  27733. var engine = this.getEngine();
  27734. var scene = this.getScene();
  27735. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27736. this.computeWorldMatrix();
  27737. var mat = this.material || scene.defaultMaterial;
  27738. if (mat) {
  27739. if (mat.storeEffectOnSubMeshes) {
  27740. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27741. var subMesh = _a[_i];
  27742. var effectiveMaterial = subMesh.getMaterial();
  27743. if (effectiveMaterial) {
  27744. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27745. return false;
  27746. }
  27747. }
  27748. }
  27749. }
  27750. else {
  27751. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27752. return false;
  27753. }
  27754. }
  27755. }
  27756. // Shadows
  27757. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27758. var light = _c[_b];
  27759. var generator = light.getShadowGenerator();
  27760. if (generator) {
  27761. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27762. var subMesh = _e[_d];
  27763. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27764. return false;
  27765. }
  27766. }
  27767. }
  27768. }
  27769. // LOD
  27770. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27771. var lod = _g[_f];
  27772. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27773. return false;
  27774. }
  27775. }
  27776. return true;
  27777. };
  27778. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27779. /**
  27780. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27781. * This property is pertinent only for updatable parametric shapes.
  27782. */
  27783. get: function () {
  27784. return this._areNormalsFrozen;
  27785. },
  27786. enumerable: true,
  27787. configurable: true
  27788. });
  27789. /**
  27790. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27791. * It has no effect at all on other shapes.
  27792. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27793. * Returns the Mesh.
  27794. */
  27795. Mesh.prototype.freezeNormals = function () {
  27796. this._areNormalsFrozen = true;
  27797. return this;
  27798. };
  27799. /**
  27800. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27801. * It has no effect at all on other shapes.
  27802. * It reactivates the mesh normals computation if it was previously frozen.
  27803. * Returns the Mesh.
  27804. */
  27805. Mesh.prototype.unfreezeNormals = function () {
  27806. this._areNormalsFrozen = false;
  27807. return this;
  27808. };
  27809. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27810. /**
  27811. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27812. */
  27813. set: function (count) {
  27814. this._overridenInstanceCount = count;
  27815. },
  27816. enumerable: true,
  27817. configurable: true
  27818. });
  27819. // Methods
  27820. Mesh.prototype._preActivate = function () {
  27821. var sceneRenderId = this.getScene().getRenderId();
  27822. if (this._preActivateId === sceneRenderId) {
  27823. return this;
  27824. }
  27825. this._preActivateId = sceneRenderId;
  27826. this._visibleInstances = null;
  27827. return this;
  27828. };
  27829. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27830. if (this._visibleInstances) {
  27831. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27832. }
  27833. return this;
  27834. };
  27835. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27836. if (!this._visibleInstances) {
  27837. this._visibleInstances = {};
  27838. this._visibleInstances.defaultRenderId = renderId;
  27839. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27840. }
  27841. if (!this._visibleInstances[renderId]) {
  27842. this._visibleInstances[renderId] = new Array();
  27843. }
  27844. this._visibleInstances[renderId].push(instance);
  27845. return this;
  27846. };
  27847. /**
  27848. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27849. * This means the mesh underlying bounding box and sphere are recomputed.
  27850. * Returns the Mesh.
  27851. */
  27852. Mesh.prototype.refreshBoundingInfo = function () {
  27853. return this._refreshBoundingInfo(false);
  27854. };
  27855. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27856. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27857. return this;
  27858. }
  27859. var data = this._getPositionData(applySkeleton);
  27860. if (data) {
  27861. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27862. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27863. }
  27864. if (this.subMeshes) {
  27865. for (var index = 0; index < this.subMeshes.length; index++) {
  27866. this.subMeshes[index].refreshBoundingInfo();
  27867. }
  27868. }
  27869. this._updateBoundingInfo();
  27870. return this;
  27871. };
  27872. Mesh.prototype._getPositionData = function (applySkeleton) {
  27873. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27874. if (data && applySkeleton && this.skeleton) {
  27875. data = BABYLON.Tools.Slice(data);
  27876. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27877. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27878. if (matricesWeightsData && matricesIndicesData) {
  27879. var needExtras = this.numBoneInfluencers > 4;
  27880. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27881. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27882. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27883. var tempVector = BABYLON.Tmp.Vector3[0];
  27884. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27885. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27886. var matWeightIdx = 0;
  27887. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27888. finalMatrix.reset();
  27889. var inf;
  27890. var weight;
  27891. for (inf = 0; inf < 4; inf++) {
  27892. weight = matricesWeightsData[matWeightIdx + inf];
  27893. if (weight <= 0)
  27894. break;
  27895. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27896. finalMatrix.addToSelf(tempMatrix);
  27897. }
  27898. if (needExtras) {
  27899. for (inf = 0; inf < 4; inf++) {
  27900. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27901. if (weight <= 0)
  27902. break;
  27903. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27904. finalMatrix.addToSelf(tempMatrix);
  27905. }
  27906. }
  27907. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27908. tempVector.toArray(data, index);
  27909. }
  27910. }
  27911. }
  27912. return data;
  27913. };
  27914. Mesh.prototype._createGlobalSubMesh = function (force) {
  27915. var totalVertices = this.getTotalVertices();
  27916. if (!totalVertices || !this.getIndices()) {
  27917. return null;
  27918. }
  27919. // Check if we need to recreate the submeshes
  27920. if (this.subMeshes && this.subMeshes.length > 0) {
  27921. var ib = this.getIndices();
  27922. if (!ib) {
  27923. return null;
  27924. }
  27925. var totalIndices = ib.length;
  27926. var needToRecreate = false;
  27927. if (force) {
  27928. needToRecreate = true;
  27929. }
  27930. else {
  27931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27932. var submesh = _a[_i];
  27933. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27934. needToRecreate = true;
  27935. break;
  27936. }
  27937. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27938. needToRecreate = true;
  27939. break;
  27940. }
  27941. }
  27942. }
  27943. if (!needToRecreate) {
  27944. return this.subMeshes[0];
  27945. }
  27946. }
  27947. this.releaseSubMeshes();
  27948. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27949. };
  27950. Mesh.prototype.subdivide = function (count) {
  27951. if (count < 1) {
  27952. return;
  27953. }
  27954. var totalIndices = this.getTotalIndices();
  27955. var subdivisionSize = (totalIndices / count) | 0;
  27956. var offset = 0;
  27957. // Ensure that subdivisionSize is a multiple of 3
  27958. while (subdivisionSize % 3 !== 0) {
  27959. subdivisionSize++;
  27960. }
  27961. this.releaseSubMeshes();
  27962. for (var index = 0; index < count; index++) {
  27963. if (offset >= totalIndices) {
  27964. break;
  27965. }
  27966. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27967. offset += subdivisionSize;
  27968. }
  27969. this.synchronizeInstances();
  27970. };
  27971. /**
  27972. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27973. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27974. * The `data` are either a numeric array either a Float32Array.
  27975. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27976. * 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).
  27977. * Note that a new underlying VertexBuffer object is created each call.
  27978. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27979. *
  27980. * Possible `kind` values :
  27981. * - BABYLON.VertexBuffer.PositionKind
  27982. * - BABYLON.VertexBuffer.UVKind
  27983. * - BABYLON.VertexBuffer.UV2Kind
  27984. * - BABYLON.VertexBuffer.UV3Kind
  27985. * - BABYLON.VertexBuffer.UV4Kind
  27986. * - BABYLON.VertexBuffer.UV5Kind
  27987. * - BABYLON.VertexBuffer.UV6Kind
  27988. * - BABYLON.VertexBuffer.ColorKind
  27989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27993. *
  27994. * Returns the Mesh.
  27995. */
  27996. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27997. if (updatable === void 0) { updatable = false; }
  27998. if (!this._geometry) {
  27999. var vertexData = new BABYLON.VertexData();
  28000. vertexData.set(data, kind);
  28001. var scene = this.getScene();
  28002. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28003. }
  28004. else {
  28005. this._geometry.setVerticesData(kind, data, updatable, stride);
  28006. }
  28007. return this;
  28008. };
  28009. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28010. if (updatable === void 0) { updatable = true; }
  28011. var vb = this.getVertexBuffer(kind);
  28012. if (!vb || vb.isUpdatable() === updatable) {
  28013. return;
  28014. }
  28015. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28016. };
  28017. /**
  28018. * Sets the mesh VertexBuffer.
  28019. * Returns the Mesh.
  28020. */
  28021. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28022. if (!this._geometry) {
  28023. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28024. }
  28025. this._geometry.setVerticesBuffer(buffer);
  28026. return this;
  28027. };
  28028. /**
  28029. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28030. * If the mesh has no geometry, it is simply returned as it is.
  28031. * The `data` are either a numeric array either a Float32Array.
  28032. * No new underlying VertexBuffer object is created.
  28033. * 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.
  28034. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28035. *
  28036. * Possible `kind` values :
  28037. * - BABYLON.VertexBuffer.PositionKind
  28038. * - BABYLON.VertexBuffer.UVKind
  28039. * - BABYLON.VertexBuffer.UV2Kind
  28040. * - BABYLON.VertexBuffer.UV3Kind
  28041. * - BABYLON.VertexBuffer.UV4Kind
  28042. * - BABYLON.VertexBuffer.UV5Kind
  28043. * - BABYLON.VertexBuffer.UV6Kind
  28044. * - BABYLON.VertexBuffer.ColorKind
  28045. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28046. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28047. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28048. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28049. *
  28050. * Returns the Mesh.
  28051. */
  28052. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28053. if (!this._geometry) {
  28054. return this;
  28055. }
  28056. if (!makeItUnique) {
  28057. this._geometry.updateVerticesData(kind, data, updateExtends);
  28058. }
  28059. else {
  28060. this.makeGeometryUnique();
  28061. this.updateVerticesData(kind, data, updateExtends, false);
  28062. }
  28063. return this;
  28064. };
  28065. /**
  28066. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28067. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28068. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28069. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28070. * Returns the Mesh.
  28071. */
  28072. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28073. if (computeNormals === void 0) { computeNormals = true; }
  28074. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28075. if (!positions) {
  28076. return this;
  28077. }
  28078. positionFunction(positions);
  28079. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28080. if (computeNormals) {
  28081. var indices = this.getIndices();
  28082. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28083. if (!normals) {
  28084. return this;
  28085. }
  28086. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28087. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28088. }
  28089. return this;
  28090. };
  28091. /**
  28092. * Creates a un-shared specific occurence of the geometry for the mesh.
  28093. * Returns the Mesh.
  28094. */
  28095. Mesh.prototype.makeGeometryUnique = function () {
  28096. if (!this._geometry) {
  28097. return this;
  28098. }
  28099. var oldGeometry = this._geometry;
  28100. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28101. oldGeometry.releaseForMesh(this, true);
  28102. geometry.applyToMesh(this);
  28103. return this;
  28104. };
  28105. /**
  28106. * Sets the mesh indices.
  28107. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28108. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28109. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28110. * This method creates a new index buffer each call.
  28111. * Returns the Mesh.
  28112. */
  28113. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28114. if (totalVertices === void 0) { totalVertices = null; }
  28115. if (updatable === void 0) { updatable = false; }
  28116. if (!this._geometry) {
  28117. var vertexData = new BABYLON.VertexData();
  28118. vertexData.indices = indices;
  28119. var scene = this.getScene();
  28120. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28121. }
  28122. else {
  28123. this._geometry.setIndices(indices, totalVertices, updatable);
  28124. }
  28125. return this;
  28126. };
  28127. /**
  28128. * Update the current index buffer
  28129. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28130. * Returns the Mesh.
  28131. */
  28132. Mesh.prototype.updateIndices = function (indices, offset) {
  28133. if (!this._geometry) {
  28134. return this;
  28135. }
  28136. this._geometry.updateIndices(indices, offset);
  28137. return this;
  28138. };
  28139. /**
  28140. * Invert the geometry to move from a right handed system to a left handed one.
  28141. * Returns the Mesh.
  28142. */
  28143. Mesh.prototype.toLeftHanded = function () {
  28144. if (!this._geometry) {
  28145. return this;
  28146. }
  28147. this._geometry.toLeftHanded();
  28148. return this;
  28149. };
  28150. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28151. if (!this._geometry) {
  28152. return this;
  28153. }
  28154. var engine = this.getScene().getEngine();
  28155. // Wireframe
  28156. var indexToBind;
  28157. if (this._unIndexed) {
  28158. indexToBind = null;
  28159. }
  28160. else {
  28161. switch (fillMode) {
  28162. case BABYLON.Material.PointFillMode:
  28163. indexToBind = null;
  28164. break;
  28165. case BABYLON.Material.WireFrameFillMode:
  28166. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28167. break;
  28168. default:
  28169. case BABYLON.Material.TriangleFillMode:
  28170. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28171. break;
  28172. }
  28173. }
  28174. // VBOs
  28175. this._geometry._bind(effect, indexToBind);
  28176. return this;
  28177. };
  28178. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28179. if (alternate === void 0) { alternate = false; }
  28180. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28181. return this;
  28182. }
  28183. this.onBeforeDrawObservable.notifyObservers(this);
  28184. var scene = this.getScene();
  28185. var engine = scene.getEngine();
  28186. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28187. // or triangles as points
  28188. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28189. }
  28190. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28191. // Triangles as wireframe
  28192. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28193. }
  28194. else {
  28195. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28196. }
  28197. if (scene._isAlternateRenderingEnabled && !alternate) {
  28198. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28199. if (!effect || !scene.activeCamera) {
  28200. return this;
  28201. }
  28202. scene._switchToAlternateCameraConfiguration(true);
  28203. this._effectiveMaterial.bindView(effect);
  28204. this._effectiveMaterial.bindViewProjection(effect);
  28205. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28206. this._draw(subMesh, fillMode, instancesCount, true);
  28207. engine.setViewport(scene.activeCamera.viewport);
  28208. scene._switchToAlternateCameraConfiguration(false);
  28209. this._effectiveMaterial.bindView(effect);
  28210. this._effectiveMaterial.bindViewProjection(effect);
  28211. }
  28212. return this;
  28213. };
  28214. /**
  28215. * Registers for this mesh a javascript function called just before the rendering process.
  28216. * This function is passed the current mesh.
  28217. * Return the Mesh.
  28218. */
  28219. Mesh.prototype.registerBeforeRender = function (func) {
  28220. this.onBeforeRenderObservable.add(func);
  28221. return this;
  28222. };
  28223. /**
  28224. * Disposes a previously registered javascript function called before the rendering.
  28225. * This function is passed the current mesh.
  28226. * Returns the Mesh.
  28227. */
  28228. Mesh.prototype.unregisterBeforeRender = function (func) {
  28229. this.onBeforeRenderObservable.removeCallback(func);
  28230. return this;
  28231. };
  28232. /**
  28233. * Registers for this mesh a javascript function called just after the rendering is complete.
  28234. * This function is passed the current mesh.
  28235. * Returns the Mesh.
  28236. */
  28237. Mesh.prototype.registerAfterRender = function (func) {
  28238. this.onAfterRenderObservable.add(func);
  28239. return this;
  28240. };
  28241. /**
  28242. * Disposes a previously registered javascript function called after the rendering.
  28243. * This function is passed the current mesh.
  28244. * Return the Mesh.
  28245. */
  28246. Mesh.prototype.unregisterAfterRender = function (func) {
  28247. this.onAfterRenderObservable.removeCallback(func);
  28248. return this;
  28249. };
  28250. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28251. var scene = this.getScene();
  28252. this._batchCache.mustReturn = false;
  28253. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28254. this._batchCache.visibleInstances[subMeshId] = null;
  28255. if (this._visibleInstances) {
  28256. var currentRenderId = scene.getRenderId();
  28257. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28258. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28259. var selfRenderId = this._renderId;
  28260. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28261. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28262. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28263. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28264. }
  28265. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28266. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28267. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28268. this._batchCache.mustReturn = true;
  28269. return this._batchCache;
  28270. }
  28271. if (currentRenderId !== selfRenderId) {
  28272. this._batchCache.renderSelf[subMeshId] = false;
  28273. }
  28274. }
  28275. this._renderIdForInstances[subMeshId] = currentRenderId;
  28276. }
  28277. return this._batchCache;
  28278. };
  28279. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28280. var visibleInstances = batch.visibleInstances[subMesh._id];
  28281. if (!visibleInstances) {
  28282. return this;
  28283. }
  28284. var matricesCount = visibleInstances.length + 1;
  28285. var bufferSize = matricesCount * 16 * 4;
  28286. var currentInstancesBufferSize = this._instancesBufferSize;
  28287. var instancesBuffer = this._instancesBuffer;
  28288. while (this._instancesBufferSize < bufferSize) {
  28289. this._instancesBufferSize *= 2;
  28290. }
  28291. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28292. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28293. }
  28294. var offset = 0;
  28295. var instancesCount = 0;
  28296. var world = this.getWorldMatrix();
  28297. if (batch.renderSelf[subMesh._id]) {
  28298. world.copyToArray(this._instancesData, offset);
  28299. offset += 16;
  28300. instancesCount++;
  28301. }
  28302. if (visibleInstances) {
  28303. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28304. var instance = visibleInstances[instanceIndex];
  28305. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28306. offset += 16;
  28307. instancesCount++;
  28308. }
  28309. }
  28310. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28311. if (instancesBuffer) {
  28312. instancesBuffer.dispose();
  28313. }
  28314. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28315. this._instancesBuffer = instancesBuffer;
  28316. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28317. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28318. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28319. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28320. }
  28321. else {
  28322. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28323. }
  28324. this._bind(subMesh, effect, fillMode);
  28325. this._draw(subMesh, fillMode, instancesCount);
  28326. engine.unbindInstanceAttributes();
  28327. return this;
  28328. };
  28329. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28330. var scene = this.getScene();
  28331. var engine = scene.getEngine();
  28332. if (hardwareInstancedRendering) {
  28333. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28334. }
  28335. else {
  28336. if (batch.renderSelf[subMesh._id]) {
  28337. // Draw
  28338. if (onBeforeDraw) {
  28339. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28340. }
  28341. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28342. }
  28343. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28344. if (visibleInstancesForSubMesh) {
  28345. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28346. var instance = visibleInstancesForSubMesh[instanceIndex];
  28347. // World
  28348. var world = instance.getWorldMatrix();
  28349. if (onBeforeDraw) {
  28350. onBeforeDraw(true, world, effectiveMaterial);
  28351. }
  28352. // Draw
  28353. this._draw(subMesh, fillMode);
  28354. }
  28355. }
  28356. }
  28357. return this;
  28358. };
  28359. /**
  28360. * Triggers the draw call for the mesh.
  28361. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28362. * Returns the Mesh.
  28363. */
  28364. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28365. this.checkOcclusionQuery();
  28366. if (this._isOccluded) {
  28367. return this;
  28368. }
  28369. var scene = this.getScene();
  28370. // Managing instances
  28371. var batch = this._getInstancesRenderList(subMesh._id);
  28372. if (batch.mustReturn) {
  28373. return this;
  28374. }
  28375. // Checking geometry state
  28376. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28377. return this;
  28378. }
  28379. this.onBeforeRenderObservable.notifyObservers(this);
  28380. var engine = scene.getEngine();
  28381. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28382. // Material
  28383. var material = subMesh.getMaterial();
  28384. if (!material) {
  28385. return this;
  28386. }
  28387. this._effectiveMaterial = material;
  28388. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28389. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28390. return this;
  28391. }
  28392. }
  28393. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28394. return this;
  28395. }
  28396. // Alpha mode
  28397. if (enableAlphaMode) {
  28398. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28399. }
  28400. // Outline - step 1
  28401. var savedDepthWrite = engine.getDepthWrite();
  28402. if (this.renderOutline) {
  28403. engine.setDepthWrite(false);
  28404. scene.getOutlineRenderer().render(subMesh, batch);
  28405. engine.setDepthWrite(savedDepthWrite);
  28406. }
  28407. var effect;
  28408. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28409. effect = subMesh.effect;
  28410. }
  28411. else {
  28412. effect = this._effectiveMaterial.getEffect();
  28413. }
  28414. if (!effect) {
  28415. return this;
  28416. }
  28417. var sideOrientation = this.overrideMaterialSideOrientation;
  28418. if (sideOrientation == null) {
  28419. sideOrientation = this._effectiveMaterial.sideOrientation;
  28420. if (this._getWorldMatrixDeterminant() < 0) {
  28421. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28422. }
  28423. }
  28424. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28425. if (this._effectiveMaterial.forceDepthWrite) {
  28426. engine.setDepthWrite(true);
  28427. }
  28428. // Bind
  28429. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28430. if (!hardwareInstancedRendering) {
  28431. this._bind(subMesh, effect, fillMode);
  28432. }
  28433. var world = this.getWorldMatrix();
  28434. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28435. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28436. }
  28437. else {
  28438. this._effectiveMaterial.bind(world, this);
  28439. }
  28440. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28441. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28442. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28443. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28444. }
  28445. // Draw
  28446. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28447. // Unbind
  28448. this._effectiveMaterial.unbind();
  28449. // Outline - step 2
  28450. if (this.renderOutline && savedDepthWrite) {
  28451. engine.setDepthWrite(true);
  28452. engine.setColorWrite(false);
  28453. scene.getOutlineRenderer().render(subMesh, batch);
  28454. engine.setColorWrite(true);
  28455. }
  28456. // Overlay
  28457. if (this.renderOverlay) {
  28458. var currentMode = engine.getAlphaMode();
  28459. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28460. scene.getOutlineRenderer().render(subMesh, batch, true);
  28461. engine.setAlphaMode(currentMode);
  28462. }
  28463. this.onAfterRenderObservable.notifyObservers(this);
  28464. return this;
  28465. };
  28466. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28467. if (isInstance && effectiveMaterial) {
  28468. effectiveMaterial.bindOnlyWorldMatrix(world);
  28469. }
  28470. };
  28471. /**
  28472. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28473. */
  28474. Mesh.prototype.getEmittedParticleSystems = function () {
  28475. var results = new Array();
  28476. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28477. var particleSystem = this.getScene().particleSystems[index];
  28478. if (particleSystem.emitter === this) {
  28479. results.push(particleSystem);
  28480. }
  28481. }
  28482. return results;
  28483. };
  28484. /**
  28485. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28486. */
  28487. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28488. var results = new Array();
  28489. var descendants = this.getDescendants();
  28490. descendants.push(this);
  28491. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28492. var particleSystem = this.getScene().particleSystems[index];
  28493. var emitter = particleSystem.emitter;
  28494. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28495. results.push(particleSystem);
  28496. }
  28497. }
  28498. return results;
  28499. };
  28500. Mesh.prototype._checkDelayState = function () {
  28501. var scene = this.getScene();
  28502. if (this._geometry) {
  28503. this._geometry.load(scene);
  28504. }
  28505. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28507. this._queueLoad(scene);
  28508. }
  28509. return this;
  28510. };
  28511. Mesh.prototype._queueLoad = function (scene) {
  28512. var _this = this;
  28513. scene._addPendingData(this);
  28514. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28515. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28516. if (data instanceof ArrayBuffer) {
  28517. _this._delayLoadingFunction(data, _this);
  28518. }
  28519. else {
  28520. _this._delayLoadingFunction(JSON.parse(data), _this);
  28521. }
  28522. _this.instances.forEach(function (instance) {
  28523. instance._syncSubMeshes();
  28524. });
  28525. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28526. scene._removePendingData(_this);
  28527. }, function () { }, scene.database, getBinaryData);
  28528. return this;
  28529. };
  28530. /**
  28531. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28532. */
  28533. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28534. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28535. return false;
  28536. }
  28537. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28538. return false;
  28539. }
  28540. this._checkDelayState();
  28541. return true;
  28542. };
  28543. /**
  28544. * Sets the mesh material by the material or multiMaterial `id` property.
  28545. * The material `id` is a string identifying the material or the multiMaterial.
  28546. * This method returns the Mesh.
  28547. */
  28548. Mesh.prototype.setMaterialByID = function (id) {
  28549. var materials = this.getScene().materials;
  28550. var index;
  28551. for (index = materials.length - 1; index > -1; index--) {
  28552. if (materials[index].id === id) {
  28553. this.material = materials[index];
  28554. return this;
  28555. }
  28556. }
  28557. // Multi
  28558. var multiMaterials = this.getScene().multiMaterials;
  28559. for (index = multiMaterials.length - 1; index > -1; index--) {
  28560. if (multiMaterials[index].id === id) {
  28561. this.material = multiMaterials[index];
  28562. return this;
  28563. }
  28564. }
  28565. return this;
  28566. };
  28567. /**
  28568. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28569. */
  28570. Mesh.prototype.getAnimatables = function () {
  28571. var results = new Array();
  28572. if (this.material) {
  28573. results.push(this.material);
  28574. }
  28575. if (this.skeleton) {
  28576. results.push(this.skeleton);
  28577. }
  28578. return results;
  28579. };
  28580. /**
  28581. * Modifies the mesh geometry according to the passed transformation matrix.
  28582. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28583. * The mesh normals are modified accordingly the same transformation.
  28584. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28585. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28586. * Returns the Mesh.
  28587. */
  28588. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28589. // Position
  28590. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28591. return this;
  28592. }
  28593. var submeshes = this.subMeshes.splice(0);
  28594. this._resetPointsArrayCache();
  28595. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28596. var temp = new Array();
  28597. var index;
  28598. for (index = 0; index < data.length; index += 3) {
  28599. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28600. }
  28601. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28602. // Normals
  28603. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28604. return this;
  28605. }
  28606. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28607. temp = [];
  28608. for (index = 0; index < data.length; index += 3) {
  28609. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28610. }
  28611. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28612. // flip faces?
  28613. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28614. this.flipFaces();
  28615. }
  28616. // Restore submeshes
  28617. this.releaseSubMeshes();
  28618. this.subMeshes = submeshes;
  28619. return this;
  28620. };
  28621. /**
  28622. * Modifies the mesh geometry according to its own current World Matrix.
  28623. * The mesh World Matrix is then reset.
  28624. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28625. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28626. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28627. * Returns the Mesh.
  28628. */
  28629. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28630. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28631. this.scaling.copyFromFloats(1, 1, 1);
  28632. this.position.copyFromFloats(0, 0, 0);
  28633. this.rotation.copyFromFloats(0, 0, 0);
  28634. //only if quaternion is already set
  28635. if (this.rotationQuaternion) {
  28636. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28637. }
  28638. this._worldMatrix = BABYLON.Matrix.Identity();
  28639. return this;
  28640. };
  28641. Object.defineProperty(Mesh.prototype, "_positions", {
  28642. // Cache
  28643. get: function () {
  28644. if (this._geometry) {
  28645. return this._geometry._positions;
  28646. }
  28647. return null;
  28648. },
  28649. enumerable: true,
  28650. configurable: true
  28651. });
  28652. Mesh.prototype._resetPointsArrayCache = function () {
  28653. if (this._geometry) {
  28654. this._geometry._resetPointsArrayCache();
  28655. }
  28656. return this;
  28657. };
  28658. Mesh.prototype._generatePointsArray = function () {
  28659. if (this._geometry) {
  28660. return this._geometry._generatePointsArray();
  28661. }
  28662. return false;
  28663. };
  28664. /**
  28665. * Returns a new Mesh object generated from the current mesh properties.
  28666. * This method must not get confused with createInstance().
  28667. * The parameter `name` is a string, the name given to the new mesh.
  28668. * The optional parameter `newParent` can be any Node object (default `null`).
  28669. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28670. * 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.
  28671. */
  28672. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28673. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28674. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28675. };
  28676. /**
  28677. * Disposes the Mesh.
  28678. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28679. * Returns nothing.
  28680. */
  28681. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28682. var _this = this;
  28683. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28684. this.morphTargetManager = null;
  28685. if (this._geometry) {
  28686. this._geometry.releaseForMesh(this, true);
  28687. }
  28688. // Sources
  28689. var meshes = this.getScene().meshes;
  28690. meshes.forEach(function (abstractMesh) {
  28691. var mesh = abstractMesh;
  28692. if (mesh._source && mesh._source === _this) {
  28693. mesh._source = null;
  28694. }
  28695. });
  28696. this._source = null;
  28697. // Instances
  28698. if (this._instancesBuffer) {
  28699. this._instancesBuffer.dispose();
  28700. this._instancesBuffer = null;
  28701. }
  28702. while (this.instances.length) {
  28703. this.instances[0].dispose();
  28704. }
  28705. // Effect layers.
  28706. var effectLayers = this.getScene().effectLayers;
  28707. for (var i = 0; i < effectLayers.length; i++) {
  28708. var effectLayer = effectLayers[i];
  28709. if (effectLayer) {
  28710. effectLayer._disposeMesh(this);
  28711. }
  28712. }
  28713. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28714. };
  28715. /**
  28716. * Modifies the mesh geometry according to a displacement map.
  28717. * 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.
  28718. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28719. * This method returns nothing.
  28720. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28721. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28722. * 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.
  28723. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28724. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28725. *
  28726. * Returns the Mesh.
  28727. */
  28728. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28729. var _this = this;
  28730. var scene = this.getScene();
  28731. var onload = function (img) {
  28732. // Getting height map data
  28733. var canvas = document.createElement("canvas");
  28734. var context = canvas.getContext("2d");
  28735. var heightMapWidth = img.width;
  28736. var heightMapHeight = img.height;
  28737. canvas.width = heightMapWidth;
  28738. canvas.height = heightMapHeight;
  28739. context.drawImage(img, 0, 0);
  28740. // Create VertexData from map data
  28741. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28742. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28743. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28744. //execute success callback, if set
  28745. if (onSuccess) {
  28746. onSuccess(_this);
  28747. }
  28748. };
  28749. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28750. return this;
  28751. };
  28752. /**
  28753. * Modifies the mesh geometry according to a displacementMap buffer.
  28754. * 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.
  28755. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28756. * This method returns nothing.
  28757. * 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.
  28758. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28759. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28760. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28761. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28762. *
  28763. * Returns the Mesh.
  28764. */
  28765. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28766. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28767. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28768. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28769. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28770. return this;
  28771. }
  28772. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28773. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28774. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28775. var position = BABYLON.Vector3.Zero();
  28776. var normal = BABYLON.Vector3.Zero();
  28777. var uv = BABYLON.Vector2.Zero();
  28778. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28779. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28780. for (var index = 0; index < positions.length; index += 3) {
  28781. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28782. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28783. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28784. // Compute height
  28785. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28786. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28787. var pos = (u + v * heightMapWidth) * 4;
  28788. var r = buffer[pos] / 255.0;
  28789. var g = buffer[pos + 1] / 255.0;
  28790. var b = buffer[pos + 2] / 255.0;
  28791. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28792. normal.normalize();
  28793. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28794. position = position.add(normal);
  28795. position.toArray(positions, index);
  28796. }
  28797. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28798. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28799. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28800. return this;
  28801. };
  28802. /**
  28803. * Modify the mesh to get a flat shading rendering.
  28804. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28805. * This method returns the Mesh.
  28806. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28807. */
  28808. Mesh.prototype.convertToFlatShadedMesh = function () {
  28809. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28810. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28811. var kinds = this.getVerticesDataKinds();
  28812. var vbs = {};
  28813. var data = {};
  28814. var newdata = {};
  28815. var updatableNormals = false;
  28816. var kindIndex;
  28817. var kind;
  28818. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28819. kind = kinds[kindIndex];
  28820. var vertexBuffer = this.getVertexBuffer(kind);
  28821. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28822. updatableNormals = vertexBuffer.isUpdatable();
  28823. kinds.splice(kindIndex, 1);
  28824. kindIndex--;
  28825. continue;
  28826. }
  28827. vbs[kind] = vertexBuffer;
  28828. data[kind] = vbs[kind].getData();
  28829. newdata[kind] = [];
  28830. }
  28831. // Save previous submeshes
  28832. var previousSubmeshes = this.subMeshes.slice(0);
  28833. var indices = this.getIndices();
  28834. var totalIndices = this.getTotalIndices();
  28835. // Generating unique vertices per face
  28836. var index;
  28837. for (index = 0; index < totalIndices; index++) {
  28838. var vertexIndex = indices[index];
  28839. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28840. kind = kinds[kindIndex];
  28841. var stride = vbs[kind].getStrideSize();
  28842. for (var offset = 0; offset < stride; offset++) {
  28843. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28844. }
  28845. }
  28846. }
  28847. // Updating faces & normal
  28848. var normals = [];
  28849. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28850. for (index = 0; index < totalIndices; index += 3) {
  28851. indices[index] = index;
  28852. indices[index + 1] = index + 1;
  28853. indices[index + 2] = index + 2;
  28854. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28855. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28856. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28857. var p1p2 = p1.subtract(p2);
  28858. var p3p2 = p3.subtract(p2);
  28859. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28860. // Store same normals for every vertex
  28861. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28862. normals.push(normal.x);
  28863. normals.push(normal.y);
  28864. normals.push(normal.z);
  28865. }
  28866. }
  28867. this.setIndices(indices);
  28868. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28869. // Updating vertex buffers
  28870. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28871. kind = kinds[kindIndex];
  28872. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28873. }
  28874. // Updating submeshes
  28875. this.releaseSubMeshes();
  28876. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28877. var previousOne = previousSubmeshes[submeshIndex];
  28878. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28879. }
  28880. this.synchronizeInstances();
  28881. return this;
  28882. };
  28883. /**
  28884. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28885. * In other words, more vertices, no more indices and a single bigger VBO.
  28886. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28887. * Returns the Mesh.
  28888. */
  28889. Mesh.prototype.convertToUnIndexedMesh = function () {
  28890. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28891. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28892. var kinds = this.getVerticesDataKinds();
  28893. var vbs = {};
  28894. var data = {};
  28895. var newdata = {};
  28896. var kindIndex;
  28897. var kind;
  28898. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28899. kind = kinds[kindIndex];
  28900. var vertexBuffer = this.getVertexBuffer(kind);
  28901. vbs[kind] = vertexBuffer;
  28902. data[kind] = vbs[kind].getData();
  28903. newdata[kind] = [];
  28904. }
  28905. // Save previous submeshes
  28906. var previousSubmeshes = this.subMeshes.slice(0);
  28907. var indices = this.getIndices();
  28908. var totalIndices = this.getTotalIndices();
  28909. // Generating unique vertices per face
  28910. var index;
  28911. for (index = 0; index < totalIndices; index++) {
  28912. var vertexIndex = indices[index];
  28913. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28914. kind = kinds[kindIndex];
  28915. var stride = vbs[kind].getStrideSize();
  28916. for (var offset = 0; offset < stride; offset++) {
  28917. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28918. }
  28919. }
  28920. }
  28921. // Updating indices
  28922. for (index = 0; index < totalIndices; index += 3) {
  28923. indices[index] = index;
  28924. indices[index + 1] = index + 1;
  28925. indices[index + 2] = index + 2;
  28926. }
  28927. this.setIndices(indices);
  28928. // Updating vertex buffers
  28929. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28930. kind = kinds[kindIndex];
  28931. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28932. }
  28933. // Updating submeshes
  28934. this.releaseSubMeshes();
  28935. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28936. var previousOne = previousSubmeshes[submeshIndex];
  28937. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28938. }
  28939. this._unIndexed = true;
  28940. this.synchronizeInstances();
  28941. return this;
  28942. };
  28943. /**
  28944. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28945. * This method returns the Mesh.
  28946. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28947. */
  28948. Mesh.prototype.flipFaces = function (flipNormals) {
  28949. if (flipNormals === void 0) { flipNormals = false; }
  28950. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28951. var i;
  28952. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28953. for (i = 0; i < vertex_data.normals.length; i++) {
  28954. vertex_data.normals[i] *= -1;
  28955. }
  28956. }
  28957. if (vertex_data.indices) {
  28958. var temp;
  28959. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28960. // reassign indices
  28961. temp = vertex_data.indices[i + 1];
  28962. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28963. vertex_data.indices[i + 2] = temp;
  28964. }
  28965. }
  28966. vertex_data.applyToMesh(this);
  28967. return this;
  28968. };
  28969. // Instances
  28970. /**
  28971. * Creates a new InstancedMesh object from the mesh model.
  28972. * An instance shares the same properties and the same material than its model.
  28973. * Only these properties of each instance can then be set individually :
  28974. * - position
  28975. * - rotation
  28976. * - rotationQuaternion
  28977. * - setPivotMatrix
  28978. * - scaling
  28979. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28980. * Warning : this method is not supported for Line mesh and LineSystem
  28981. */
  28982. Mesh.prototype.createInstance = function (name) {
  28983. return new BABYLON.InstancedMesh(name, this);
  28984. };
  28985. /**
  28986. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28987. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28988. * This method returns the Mesh.
  28989. */
  28990. Mesh.prototype.synchronizeInstances = function () {
  28991. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28992. var instance = this.instances[instanceIndex];
  28993. instance._syncSubMeshes();
  28994. }
  28995. return this;
  28996. };
  28997. /**
  28998. * Simplify the mesh according to the given array of settings.
  28999. * Function will return immediately and will simplify async. It returns the Mesh.
  29000. * @param settings a collection of simplification settings.
  29001. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29002. * @param type the type of simplification to run.
  29003. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29004. */
  29005. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29006. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29007. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29008. this.getScene().simplificationQueue.addTask({
  29009. settings: settings,
  29010. parallelProcessing: parallelProcessing,
  29011. mesh: this,
  29012. simplificationType: simplificationType,
  29013. successCallback: successCallback
  29014. });
  29015. return this;
  29016. };
  29017. /**
  29018. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29019. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29020. * This should be used together with the simplification to avoid disappearing triangles.
  29021. * Returns the Mesh.
  29022. * @param successCallback an optional success callback to be called after the optimization finished.
  29023. */
  29024. Mesh.prototype.optimizeIndices = function (successCallback) {
  29025. var _this = this;
  29026. var indices = this.getIndices();
  29027. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29028. if (!positions || !indices) {
  29029. return this;
  29030. }
  29031. var vectorPositions = new Array();
  29032. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29033. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29034. }
  29035. var dupes = new Array();
  29036. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29037. var realPos = vectorPositions.length - 1 - iteration;
  29038. var testedPosition = vectorPositions[realPos];
  29039. for (var j = 0; j < realPos; ++j) {
  29040. var againstPosition = vectorPositions[j];
  29041. if (testedPosition.equals(againstPosition)) {
  29042. dupes[realPos] = j;
  29043. break;
  29044. }
  29045. }
  29046. }, function () {
  29047. for (var i = 0; i < indices.length; ++i) {
  29048. indices[i] = dupes[indices[i]] || indices[i];
  29049. }
  29050. //indices are now reordered
  29051. var originalSubMeshes = _this.subMeshes.slice(0);
  29052. _this.setIndices(indices);
  29053. _this.subMeshes = originalSubMeshes;
  29054. if (successCallback) {
  29055. successCallback(_this);
  29056. }
  29057. });
  29058. return this;
  29059. };
  29060. Mesh.prototype.serialize = function (serializationObject) {
  29061. serializationObject.name = this.name;
  29062. serializationObject.id = this.id;
  29063. serializationObject.type = this.getClassName();
  29064. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29065. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29066. }
  29067. serializationObject.position = this.position.asArray();
  29068. if (this.rotationQuaternion) {
  29069. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29070. }
  29071. else if (this.rotation) {
  29072. serializationObject.rotation = this.rotation.asArray();
  29073. }
  29074. serializationObject.scaling = this.scaling.asArray();
  29075. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29076. serializationObject.isEnabled = this.isEnabled(false);
  29077. serializationObject.isVisible = this.isVisible;
  29078. serializationObject.infiniteDistance = this.infiniteDistance;
  29079. serializationObject.pickable = this.isPickable;
  29080. serializationObject.receiveShadows = this.receiveShadows;
  29081. serializationObject.billboardMode = this.billboardMode;
  29082. serializationObject.visibility = this.visibility;
  29083. serializationObject.checkCollisions = this.checkCollisions;
  29084. serializationObject.isBlocker = this.isBlocker;
  29085. // Parent
  29086. if (this.parent) {
  29087. serializationObject.parentId = this.parent.id;
  29088. }
  29089. // Geometry
  29090. serializationObject.isUnIndexed = this.isUnIndexed;
  29091. var geometry = this._geometry;
  29092. if (geometry) {
  29093. var geometryId = geometry.id;
  29094. serializationObject.geometryId = geometryId;
  29095. // SubMeshes
  29096. serializationObject.subMeshes = [];
  29097. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29098. var subMesh = this.subMeshes[subIndex];
  29099. serializationObject.subMeshes.push({
  29100. materialIndex: subMesh.materialIndex,
  29101. verticesStart: subMesh.verticesStart,
  29102. verticesCount: subMesh.verticesCount,
  29103. indexStart: subMesh.indexStart,
  29104. indexCount: subMesh.indexCount
  29105. });
  29106. }
  29107. }
  29108. // Material
  29109. if (this.material) {
  29110. serializationObject.materialId = this.material.id;
  29111. }
  29112. else {
  29113. this.material = null;
  29114. }
  29115. // Morph targets
  29116. if (this.morphTargetManager) {
  29117. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29118. }
  29119. // Skeleton
  29120. if (this.skeleton) {
  29121. serializationObject.skeletonId = this.skeleton.id;
  29122. }
  29123. // Physics
  29124. //TODO implement correct serialization for physics impostors.
  29125. var impostor = this.getPhysicsImpostor();
  29126. if (impostor) {
  29127. serializationObject.physicsMass = impostor.getParam("mass");
  29128. serializationObject.physicsFriction = impostor.getParam("friction");
  29129. serializationObject.physicsRestitution = impostor.getParam("mass");
  29130. serializationObject.physicsImpostor = impostor.type;
  29131. }
  29132. // Metadata
  29133. if (this.metadata) {
  29134. serializationObject.metadata = this.metadata;
  29135. }
  29136. // Instances
  29137. serializationObject.instances = [];
  29138. for (var index = 0; index < this.instances.length; index++) {
  29139. var instance = this.instances[index];
  29140. var serializationInstance = {
  29141. name: instance.name,
  29142. id: instance.id,
  29143. position: instance.position.asArray(),
  29144. scaling: instance.scaling.asArray()
  29145. };
  29146. if (instance.rotationQuaternion) {
  29147. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29148. }
  29149. else if (instance.rotation) {
  29150. serializationInstance.rotation = instance.rotation.asArray();
  29151. }
  29152. serializationObject.instances.push(serializationInstance);
  29153. // Animations
  29154. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29155. serializationInstance.ranges = instance.serializeAnimationRanges();
  29156. }
  29157. //
  29158. // Animations
  29159. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29160. serializationObject.ranges = this.serializeAnimationRanges();
  29161. // Layer mask
  29162. serializationObject.layerMask = this.layerMask;
  29163. // Alpha
  29164. serializationObject.alphaIndex = this.alphaIndex;
  29165. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29166. // Overlay
  29167. serializationObject.overlayAlpha = this.overlayAlpha;
  29168. serializationObject.overlayColor = this.overlayColor.asArray();
  29169. serializationObject.renderOverlay = this.renderOverlay;
  29170. // Fog
  29171. serializationObject.applyFog = this.applyFog;
  29172. // Action Manager
  29173. if (this.actionManager) {
  29174. serializationObject.actions = this.actionManager.serialize(this.name);
  29175. }
  29176. };
  29177. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29178. if (!this.geometry) {
  29179. return;
  29180. }
  29181. this._markSubMeshesAsAttributesDirty();
  29182. var morphTargetManager = this._morphTargetManager;
  29183. if (morphTargetManager && morphTargetManager.vertexCount) {
  29184. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29185. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29186. this.morphTargetManager = null;
  29187. return;
  29188. }
  29189. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29190. var morphTarget = morphTargetManager.getActiveTarget(index);
  29191. var positions = morphTarget.getPositions();
  29192. if (!positions) {
  29193. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29194. return;
  29195. }
  29196. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29197. var normals = morphTarget.getNormals();
  29198. if (normals) {
  29199. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29200. }
  29201. var tangents = morphTarget.getTangents();
  29202. if (tangents) {
  29203. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29204. }
  29205. }
  29206. }
  29207. else {
  29208. var index = 0;
  29209. // Positions
  29210. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29211. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29212. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29213. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29214. }
  29215. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29216. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29217. }
  29218. index++;
  29219. }
  29220. }
  29221. };
  29222. // Statics
  29223. /**
  29224. * Returns a new Mesh object parsed from the source provided.
  29225. * The parameter `parsedMesh` is the source.
  29226. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29227. */
  29228. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29229. var mesh;
  29230. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29231. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29232. }
  29233. else {
  29234. mesh = new Mesh(parsedMesh.name, scene);
  29235. }
  29236. mesh.id = parsedMesh.id;
  29237. if (BABYLON.Tags) {
  29238. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29239. }
  29240. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29241. if (parsedMesh.metadata !== undefined) {
  29242. mesh.metadata = parsedMesh.metadata;
  29243. }
  29244. if (parsedMesh.rotationQuaternion) {
  29245. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29246. }
  29247. else if (parsedMesh.rotation) {
  29248. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29249. }
  29250. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29251. if (parsedMesh.localMatrix) {
  29252. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29253. }
  29254. else if (parsedMesh.pivotMatrix) {
  29255. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29256. }
  29257. mesh.setEnabled(parsedMesh.isEnabled);
  29258. mesh.isVisible = parsedMesh.isVisible;
  29259. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29260. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29261. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29262. if (parsedMesh.applyFog !== undefined) {
  29263. mesh.applyFog = parsedMesh.applyFog;
  29264. }
  29265. if (parsedMesh.pickable !== undefined) {
  29266. mesh.isPickable = parsedMesh.pickable;
  29267. }
  29268. if (parsedMesh.alphaIndex !== undefined) {
  29269. mesh.alphaIndex = parsedMesh.alphaIndex;
  29270. }
  29271. mesh.receiveShadows = parsedMesh.receiveShadows;
  29272. mesh.billboardMode = parsedMesh.billboardMode;
  29273. if (parsedMesh.visibility !== undefined) {
  29274. mesh.visibility = parsedMesh.visibility;
  29275. }
  29276. mesh.checkCollisions = parsedMesh.checkCollisions;
  29277. if (parsedMesh.isBlocker !== undefined) {
  29278. mesh.isBlocker = parsedMesh.isBlocker;
  29279. }
  29280. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29281. // freezeWorldMatrix
  29282. if (parsedMesh.freezeWorldMatrix) {
  29283. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29284. }
  29285. // Parent
  29286. if (parsedMesh.parentId) {
  29287. mesh._waitingParentId = parsedMesh.parentId;
  29288. }
  29289. // Actions
  29290. if (parsedMesh.actions !== undefined) {
  29291. mesh._waitingActions = parsedMesh.actions;
  29292. }
  29293. // Overlay
  29294. if (parsedMesh.overlayAlpha !== undefined) {
  29295. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29296. }
  29297. if (parsedMesh.overlayColor !== undefined) {
  29298. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29299. }
  29300. if (parsedMesh.renderOverlay !== undefined) {
  29301. mesh.renderOverlay = parsedMesh.renderOverlay;
  29302. }
  29303. // Geometry
  29304. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29305. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29306. if (parsedMesh.delayLoadingFile) {
  29307. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29308. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29309. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29310. if (parsedMesh._binaryInfo) {
  29311. mesh._binaryInfo = parsedMesh._binaryInfo;
  29312. }
  29313. mesh._delayInfo = [];
  29314. if (parsedMesh.hasUVs) {
  29315. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29316. }
  29317. if (parsedMesh.hasUVs2) {
  29318. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29319. }
  29320. if (parsedMesh.hasUVs3) {
  29321. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29322. }
  29323. if (parsedMesh.hasUVs4) {
  29324. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29325. }
  29326. if (parsedMesh.hasUVs5) {
  29327. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29328. }
  29329. if (parsedMesh.hasUVs6) {
  29330. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29331. }
  29332. if (parsedMesh.hasColors) {
  29333. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29334. }
  29335. if (parsedMesh.hasMatricesIndices) {
  29336. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29337. }
  29338. if (parsedMesh.hasMatricesWeights) {
  29339. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29340. }
  29341. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29342. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29343. mesh._checkDelayState();
  29344. }
  29345. }
  29346. else {
  29347. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29348. }
  29349. // Material
  29350. if (parsedMesh.materialId) {
  29351. mesh.setMaterialByID(parsedMesh.materialId);
  29352. }
  29353. else {
  29354. mesh.material = null;
  29355. }
  29356. // Morph targets
  29357. if (parsedMesh.morphTargetManagerId > -1) {
  29358. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29359. }
  29360. // Skeleton
  29361. if (parsedMesh.skeletonId > -1) {
  29362. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29363. if (parsedMesh.numBoneInfluencers) {
  29364. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29365. }
  29366. }
  29367. // Animations
  29368. if (parsedMesh.animations) {
  29369. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29370. var parsedAnimation = parsedMesh.animations[animationIndex];
  29371. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29372. }
  29373. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29374. }
  29375. if (parsedMesh.autoAnimate) {
  29376. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29377. }
  29378. // Layer Mask
  29379. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29380. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29381. }
  29382. else {
  29383. mesh.layerMask = 0x0FFFFFFF;
  29384. }
  29385. // Physics
  29386. if (parsedMesh.physicsImpostor) {
  29387. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29388. mass: parsedMesh.physicsMass,
  29389. friction: parsedMesh.physicsFriction,
  29390. restitution: parsedMesh.physicsRestitution
  29391. }, scene);
  29392. }
  29393. // Instances
  29394. if (parsedMesh.instances) {
  29395. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29396. var parsedInstance = parsedMesh.instances[index];
  29397. var instance = mesh.createInstance(parsedInstance.name);
  29398. if (parsedInstance.id) {
  29399. instance.id = parsedInstance.id;
  29400. }
  29401. if (BABYLON.Tags) {
  29402. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29403. }
  29404. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29405. if (parsedInstance.parentId) {
  29406. instance._waitingParentId = parsedInstance.parentId;
  29407. }
  29408. if (parsedInstance.rotationQuaternion) {
  29409. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29410. }
  29411. else if (parsedInstance.rotation) {
  29412. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29413. }
  29414. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29415. instance.checkCollisions = mesh.checkCollisions;
  29416. if (parsedMesh.animations) {
  29417. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29418. parsedAnimation = parsedMesh.animations[animationIndex];
  29419. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29420. }
  29421. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29422. }
  29423. }
  29424. }
  29425. return mesh;
  29426. };
  29427. /**
  29428. * Creates a ribbon mesh.
  29429. * Please consider using the same method from the MeshBuilder class instead.
  29430. * 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.
  29431. *
  29432. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29433. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29434. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29435. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29436. * 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.
  29437. * 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.
  29438. * 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
  29439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29442. */
  29443. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29444. if (closeArray === void 0) { closeArray = false; }
  29445. if (updatable === void 0) { updatable = false; }
  29446. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29447. pathArray: pathArray,
  29448. closeArray: closeArray,
  29449. closePath: closePath,
  29450. offset: offset,
  29451. updatable: updatable,
  29452. sideOrientation: sideOrientation,
  29453. instance: instance
  29454. }, scene);
  29455. };
  29456. /**
  29457. * Creates a plane polygonal mesh. By default, this is a disc.
  29458. * Please consider using the same method from the MeshBuilder class instead.
  29459. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29460. * 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.
  29461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29464. */
  29465. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29466. if (scene === void 0) { scene = null; }
  29467. var options = {
  29468. radius: radius,
  29469. tessellation: tessellation,
  29470. sideOrientation: sideOrientation,
  29471. updatable: updatable
  29472. };
  29473. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29474. };
  29475. /**
  29476. * Creates a box mesh.
  29477. * Please consider using the same method from the MeshBuilder class instead.
  29478. * The parameter `size` sets the size (float) of each box side (default 1).
  29479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29480. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29482. */
  29483. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29484. if (scene === void 0) { scene = null; }
  29485. var options = {
  29486. size: size,
  29487. sideOrientation: sideOrientation,
  29488. updatable: updatable
  29489. };
  29490. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29491. };
  29492. /**
  29493. * Creates a sphere mesh.
  29494. * Please consider using the same method from the MeshBuilder class instead.
  29495. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29496. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29497. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29498. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29499. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29500. */
  29501. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29502. var options = {
  29503. segments: segments,
  29504. diameterX: diameter,
  29505. diameterY: diameter,
  29506. diameterZ: diameter,
  29507. sideOrientation: sideOrientation,
  29508. updatable: updatable
  29509. };
  29510. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29511. };
  29512. /**
  29513. * Creates a cylinder or a cone mesh.
  29514. * Please consider using the same method from the MeshBuilder class instead.
  29515. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29516. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29517. * 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.
  29518. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29519. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29523. */
  29524. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29525. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29526. if (scene !== undefined) {
  29527. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29528. updatable = scene;
  29529. }
  29530. scene = subdivisions;
  29531. subdivisions = 1;
  29532. }
  29533. var options = {
  29534. height: height,
  29535. diameterTop: diameterTop,
  29536. diameterBottom: diameterBottom,
  29537. tessellation: tessellation,
  29538. subdivisions: subdivisions,
  29539. sideOrientation: sideOrientation,
  29540. updatable: updatable
  29541. };
  29542. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29543. };
  29544. // Torus (Code from SharpDX.org)
  29545. /**
  29546. * Creates a torus mesh.
  29547. * Please consider using the same method from the MeshBuilder class instead.
  29548. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29549. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29550. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29551. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29552. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29554. */
  29555. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29556. var options = {
  29557. diameter: diameter,
  29558. thickness: thickness,
  29559. tessellation: tessellation,
  29560. sideOrientation: sideOrientation,
  29561. updatable: updatable
  29562. };
  29563. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29564. };
  29565. /**
  29566. * Creates a torus knot mesh.
  29567. * Please consider using the same method from the MeshBuilder class instead.
  29568. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29569. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29570. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29571. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  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.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29577. var options = {
  29578. radius: radius,
  29579. tube: tube,
  29580. radialSegments: radialSegments,
  29581. tubularSegments: tubularSegments,
  29582. p: p,
  29583. q: q,
  29584. sideOrientation: sideOrientation,
  29585. updatable: updatable
  29586. };
  29587. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29588. };
  29589. /**
  29590. * Creates a line mesh.
  29591. * Please consider using the same method from the MeshBuilder class instead.
  29592. * 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.
  29593. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29594. * The parameter `points` is an array successive Vector3.
  29595. * 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
  29596. * When updating an instance, remember that only point positions can change, not the number of points.
  29597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29598. */
  29599. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29600. if (scene === void 0) { scene = null; }
  29601. if (updatable === void 0) { updatable = false; }
  29602. if (instance === void 0) { instance = null; }
  29603. var options = {
  29604. points: points,
  29605. updatable: updatable,
  29606. instance: instance
  29607. };
  29608. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29609. };
  29610. /**
  29611. * Creates a dashed line mesh.
  29612. * Please consider using the same method from the MeshBuilder class instead.
  29613. * 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.
  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 parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29617. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29618. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29619. * 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
  29620. * When updating an instance, remember that only point positions can change, not the number of points.
  29621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29622. */
  29623. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29624. if (scene === void 0) { scene = null; }
  29625. var options = {
  29626. points: points,
  29627. dashSize: dashSize,
  29628. gapSize: gapSize,
  29629. dashNb: dashNb,
  29630. updatable: updatable,
  29631. instance: instance
  29632. };
  29633. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29634. };
  29635. /**
  29636. * Creates a polygon mesh.
  29637. * Please consider using the same method from the MeshBuilder class instead.
  29638. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29639. * 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.
  29640. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29642. * Remember you can only change the shape positions, not their number when updating a polygon.
  29643. */
  29644. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29645. var options = {
  29646. shape: shape,
  29647. holes: holes,
  29648. updatable: updatable,
  29649. sideOrientation: sideOrientation
  29650. };
  29651. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29652. };
  29653. /**
  29654. * Creates an extruded polygon mesh, with depth in the Y direction.
  29655. * Please consider using the same method from the MeshBuilder class instead.
  29656. */
  29657. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29658. var options = {
  29659. shape: shape,
  29660. holes: holes,
  29661. depth: depth,
  29662. updatable: updatable,
  29663. sideOrientation: sideOrientation
  29664. };
  29665. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29666. };
  29667. /**
  29668. * Creates an extruded shape mesh.
  29669. * 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.
  29670. * Please consider using the same method from the MeshBuilder class instead.
  29671. *
  29672. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29673. * 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
  29674. * extruded along the Z axis.
  29675. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29676. * 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.
  29677. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29678. * 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
  29679. * 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
  29680. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29682. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29684. */
  29685. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29686. if (scene === void 0) { scene = null; }
  29687. var options = {
  29688. shape: shape,
  29689. path: path,
  29690. scale: scale,
  29691. rotation: rotation,
  29692. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29693. sideOrientation: sideOrientation,
  29694. instance: instance,
  29695. updatable: updatable
  29696. };
  29697. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29698. };
  29699. /**
  29700. * Creates an custom extruded shape mesh.
  29701. * 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.
  29702. * Please consider using the same method from the MeshBuilder class instead.
  29703. *
  29704. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29705. * 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
  29706. * extruded along the Z axis.
  29707. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29708. * 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
  29709. * and the distance of this point from the begining of the path :
  29710. * ```javascript
  29711. * var rotationFunction = function(i, distance) {
  29712. * // do things
  29713. * return rotationValue; }
  29714. * ```
  29715. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29716. * 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
  29717. * and the distance of this point from the begining of the path :
  29718. * ```javascript
  29719. * var scaleFunction = function(i, distance) {
  29720. * // do things
  29721. * return scaleValue;}
  29722. * ```
  29723. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29724. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29725. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29726. * 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
  29727. * 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
  29728. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29732. */
  29733. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29734. var options = {
  29735. shape: shape,
  29736. path: path,
  29737. scaleFunction: scaleFunction,
  29738. rotationFunction: rotationFunction,
  29739. ribbonCloseArray: ribbonCloseArray,
  29740. ribbonClosePath: ribbonClosePath,
  29741. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29742. sideOrientation: sideOrientation,
  29743. instance: instance,
  29744. updatable: updatable
  29745. };
  29746. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29747. };
  29748. /**
  29749. * Creates lathe mesh.
  29750. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29751. * Please consider using the same method from the MeshBuilder class instead.
  29752. * 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
  29753. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29754. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29755. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29759. */
  29760. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29761. var options = {
  29762. shape: shape,
  29763. radius: radius,
  29764. tessellation: tessellation,
  29765. sideOrientation: sideOrientation,
  29766. updatable: updatable
  29767. };
  29768. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29769. };
  29770. /**
  29771. * Creates a plane mesh.
  29772. * Please consider using the same method from the MeshBuilder class instead.
  29773. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29777. */
  29778. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29779. var options = {
  29780. size: size,
  29781. width: size,
  29782. height: size,
  29783. sideOrientation: sideOrientation,
  29784. updatable: updatable
  29785. };
  29786. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29787. };
  29788. /**
  29789. * Creates a ground mesh.
  29790. * Please consider using the same method from the MeshBuilder class instead.
  29791. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29792. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29794. */
  29795. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29796. var options = {
  29797. width: width,
  29798. height: height,
  29799. subdivisions: subdivisions,
  29800. updatable: updatable
  29801. };
  29802. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29803. };
  29804. /**
  29805. * Creates a tiled ground mesh.
  29806. * Please consider using the same method from the MeshBuilder class instead.
  29807. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29808. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29809. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29810. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29811. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29812. * numbers of subdivisions on the ground width and height of each tile.
  29813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29814. */
  29815. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29816. var options = {
  29817. xmin: xmin,
  29818. zmin: zmin,
  29819. xmax: xmax,
  29820. zmax: zmax,
  29821. subdivisions: subdivisions,
  29822. precision: precision,
  29823. updatable: updatable
  29824. };
  29825. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29826. };
  29827. /**
  29828. * Creates a ground mesh from a height map.
  29829. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29830. * Please consider using the same method from the MeshBuilder class instead.
  29831. * The parameter `url` sets the URL of the height map image resource.
  29832. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29833. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29834. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29835. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29836. * 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).
  29837. * This function is passed the newly built mesh :
  29838. * ```javascript
  29839. * function(mesh) { // do things
  29840. * return; }
  29841. * ```
  29842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29843. */
  29844. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29845. var options = {
  29846. width: width,
  29847. height: height,
  29848. subdivisions: subdivisions,
  29849. minHeight: minHeight,
  29850. maxHeight: maxHeight,
  29851. updatable: updatable,
  29852. onReady: onReady
  29853. };
  29854. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29855. };
  29856. /**
  29857. * Creates a tube mesh.
  29858. * 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.
  29859. * Please consider using the same method from the MeshBuilder class instead.
  29860. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29861. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29862. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29863. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29864. * 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.
  29865. * It must return a radius value (positive float) :
  29866. * ```javascript
  29867. * var radiusFunction = function(i, distance) {
  29868. * // do things
  29869. * return radius; }
  29870. * ```
  29871. * 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
  29872. * 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
  29873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29876. */
  29877. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29878. var options = {
  29879. path: path,
  29880. radius: radius,
  29881. tessellation: tessellation,
  29882. radiusFunction: radiusFunction,
  29883. arc: 1,
  29884. cap: cap,
  29885. updatable: updatable,
  29886. sideOrientation: sideOrientation,
  29887. instance: instance
  29888. };
  29889. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29890. };
  29891. /**
  29892. * Creates a polyhedron mesh.
  29893. * Please consider using the same method from the MeshBuilder class instead.
  29894. * 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
  29895. * to choose the wanted type.
  29896. * The parameter `size` (positive float, default 1) sets the polygon size.
  29897. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29898. * 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`.
  29899. * 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
  29900. * 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)`).
  29901. * 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
  29902. * 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.
  29903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29904. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29906. */
  29907. Mesh.CreatePolyhedron = function (name, options, scene) {
  29908. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29909. };
  29910. /**
  29911. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29912. * Please consider using the same method from the MeshBuilder class instead.
  29913. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29914. * 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`).
  29915. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29916. * 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.
  29917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29920. */
  29921. Mesh.CreateIcoSphere = function (name, options, scene) {
  29922. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29923. };
  29924. /**
  29925. * Creates a decal mesh.
  29926. * Please consider using the same method from the MeshBuilder class instead.
  29927. * 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.
  29928. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29929. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29930. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29931. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29932. */
  29933. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29934. var options = {
  29935. position: position,
  29936. normal: normal,
  29937. size: size,
  29938. angle: angle
  29939. };
  29940. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29941. };
  29942. // Skeletons
  29943. /**
  29944. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29945. */
  29946. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29947. if (!this._sourcePositions) {
  29948. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29949. if (!source) {
  29950. return this._sourcePositions;
  29951. }
  29952. this._sourcePositions = new Float32Array(source);
  29953. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29954. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29955. }
  29956. }
  29957. return this._sourcePositions;
  29958. };
  29959. /**
  29960. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29961. */
  29962. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29963. if (!this._sourceNormals) {
  29964. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29965. if (!source) {
  29966. return this._sourceNormals;
  29967. }
  29968. this._sourceNormals = new Float32Array(source);
  29969. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29970. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29971. }
  29972. }
  29973. return this._sourceNormals;
  29974. };
  29975. /**
  29976. * Updates the vertex buffer by applying transformation from the bones.
  29977. * Returns the Mesh.
  29978. *
  29979. * @param {skeleton} skeleton to apply
  29980. */
  29981. Mesh.prototype.applySkeleton = function (skeleton) {
  29982. if (!this.geometry) {
  29983. return this;
  29984. }
  29985. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29986. return this;
  29987. }
  29988. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29989. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29990. return this;
  29991. }
  29992. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29993. return this;
  29994. }
  29995. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29996. return this;
  29997. }
  29998. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29999. return this;
  30000. }
  30001. if (!this._sourcePositions) {
  30002. var submeshes = this.subMeshes.slice();
  30003. this.setPositionsForCPUSkinning();
  30004. this.subMeshes = submeshes;
  30005. }
  30006. if (!this._sourceNormals) {
  30007. this.setNormalsForCPUSkinning();
  30008. }
  30009. // positionsData checks for not being Float32Array will only pass at most once
  30010. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30011. if (!positionsData) {
  30012. return this;
  30013. }
  30014. if (!(positionsData instanceof Float32Array)) {
  30015. positionsData = new Float32Array(positionsData);
  30016. }
  30017. // normalsData checks for not being Float32Array will only pass at most once
  30018. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30019. if (!normalsData) {
  30020. return this;
  30021. }
  30022. if (!(normalsData instanceof Float32Array)) {
  30023. normalsData = new Float32Array(normalsData);
  30024. }
  30025. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30026. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30027. if (!matricesWeightsData || !matricesIndicesData) {
  30028. return this;
  30029. }
  30030. var needExtras = this.numBoneInfluencers > 4;
  30031. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30032. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30033. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30034. var tempVector3 = BABYLON.Vector3.Zero();
  30035. var finalMatrix = new BABYLON.Matrix();
  30036. var tempMatrix = new BABYLON.Matrix();
  30037. var matWeightIdx = 0;
  30038. var inf;
  30039. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30040. var weight;
  30041. for (inf = 0; inf < 4; inf++) {
  30042. weight = matricesWeightsData[matWeightIdx + inf];
  30043. if (weight > 0) {
  30044. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30045. finalMatrix.addToSelf(tempMatrix);
  30046. }
  30047. else
  30048. break;
  30049. }
  30050. if (needExtras) {
  30051. for (inf = 0; inf < 4; inf++) {
  30052. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30053. if (weight > 0) {
  30054. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30055. finalMatrix.addToSelf(tempMatrix);
  30056. }
  30057. else
  30058. break;
  30059. }
  30060. }
  30061. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30062. tempVector3.toArray(positionsData, index);
  30063. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30064. tempVector3.toArray(normalsData, index);
  30065. finalMatrix.reset();
  30066. }
  30067. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30068. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30069. return this;
  30070. };
  30071. // Tools
  30072. /**
  30073. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30074. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30075. */
  30076. Mesh.MinMax = function (meshes) {
  30077. var minVector = null;
  30078. var maxVector = null;
  30079. meshes.forEach(function (mesh, index, array) {
  30080. var boundingInfo = mesh.getBoundingInfo();
  30081. var boundingBox = boundingInfo.boundingBox;
  30082. if (!minVector || !maxVector) {
  30083. minVector = boundingBox.minimumWorld;
  30084. maxVector = boundingBox.maximumWorld;
  30085. }
  30086. else {
  30087. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30088. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30089. }
  30090. });
  30091. if (!minVector || !maxVector) {
  30092. return {
  30093. min: BABYLON.Vector3.Zero(),
  30094. max: BABYLON.Vector3.Zero()
  30095. };
  30096. }
  30097. return {
  30098. min: minVector,
  30099. max: maxVector
  30100. };
  30101. };
  30102. /**
  30103. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30104. */
  30105. Mesh.Center = function (meshesOrMinMaxVector) {
  30106. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30107. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30108. };
  30109. /**
  30110. * Merge the array of meshes into a single mesh for performance reasons.
  30111. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30112. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30113. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30114. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30115. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30116. */
  30117. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30118. if (disposeSource === void 0) { disposeSource = true; }
  30119. var index;
  30120. if (!allow32BitsIndices) {
  30121. var totalVertices = 0;
  30122. // Counting vertices
  30123. for (index = 0; index < meshes.length; index++) {
  30124. if (meshes[index]) {
  30125. totalVertices += meshes[index].getTotalVertices();
  30126. if (totalVertices > 65536) {
  30127. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30128. return null;
  30129. }
  30130. }
  30131. }
  30132. }
  30133. // Merge
  30134. var vertexData = null;
  30135. var otherVertexData;
  30136. var indiceArray = new Array();
  30137. var source = null;
  30138. for (index = 0; index < meshes.length; index++) {
  30139. if (meshes[index]) {
  30140. meshes[index].computeWorldMatrix(true);
  30141. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30142. otherVertexData.transform(meshes[index].getWorldMatrix());
  30143. if (vertexData) {
  30144. vertexData.merge(otherVertexData);
  30145. }
  30146. else {
  30147. vertexData = otherVertexData;
  30148. source = meshes[index];
  30149. }
  30150. if (subdivideWithSubMeshes) {
  30151. indiceArray.push(meshes[index].getTotalIndices());
  30152. }
  30153. }
  30154. }
  30155. source = source;
  30156. if (!meshSubclass) {
  30157. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30158. }
  30159. vertexData.applyToMesh(meshSubclass);
  30160. // Setting properties
  30161. meshSubclass.material = source.material;
  30162. meshSubclass.checkCollisions = source.checkCollisions;
  30163. // Cleaning
  30164. if (disposeSource) {
  30165. for (index = 0; index < meshes.length; index++) {
  30166. if (meshes[index]) {
  30167. meshes[index].dispose();
  30168. }
  30169. }
  30170. }
  30171. // Subdivide
  30172. if (subdivideWithSubMeshes) {
  30173. //-- Suppresions du submesh global
  30174. meshSubclass.releaseSubMeshes();
  30175. index = 0;
  30176. var offset = 0;
  30177. //-- aplique la subdivision en fonction du tableau d'indices
  30178. while (index < indiceArray.length) {
  30179. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30180. offset += indiceArray[index];
  30181. index++;
  30182. }
  30183. }
  30184. return meshSubclass;
  30185. };
  30186. // Consts
  30187. Mesh._FRONTSIDE = 0;
  30188. Mesh._BACKSIDE = 1;
  30189. Mesh._DOUBLESIDE = 2;
  30190. Mesh._DEFAULTSIDE = 0;
  30191. Mesh._NO_CAP = 0;
  30192. Mesh._CAP_START = 1;
  30193. Mesh._CAP_END = 2;
  30194. Mesh._CAP_ALL = 3;
  30195. return Mesh;
  30196. }(BABYLON.AbstractMesh));
  30197. BABYLON.Mesh = Mesh;
  30198. })(BABYLON || (BABYLON = {}));
  30199. //# sourceMappingURL=babylon.mesh.js.map
  30200. var BABYLON;
  30201. (function (BABYLON) {
  30202. var BaseSubMesh = /** @class */ (function () {
  30203. function BaseSubMesh() {
  30204. }
  30205. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30206. get: function () {
  30207. return this._materialEffect;
  30208. },
  30209. enumerable: true,
  30210. configurable: true
  30211. });
  30212. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30213. if (defines === void 0) { defines = null; }
  30214. if (this._materialEffect === effect) {
  30215. if (!effect) {
  30216. this._materialDefines = null;
  30217. }
  30218. return;
  30219. }
  30220. this._materialDefines = defines;
  30221. this._materialEffect = effect;
  30222. };
  30223. return BaseSubMesh;
  30224. }());
  30225. BABYLON.BaseSubMesh = BaseSubMesh;
  30226. var SubMesh = /** @class */ (function (_super) {
  30227. __extends(SubMesh, _super);
  30228. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30229. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30230. var _this = _super.call(this) || this;
  30231. _this.materialIndex = materialIndex;
  30232. _this.verticesStart = verticesStart;
  30233. _this.verticesCount = verticesCount;
  30234. _this.indexStart = indexStart;
  30235. _this.indexCount = indexCount;
  30236. _this._renderId = 0;
  30237. _this._mesh = mesh;
  30238. _this._renderingMesh = renderingMesh || mesh;
  30239. mesh.subMeshes.push(_this);
  30240. _this._trianglePlanes = [];
  30241. _this._id = mesh.subMeshes.length - 1;
  30242. if (createBoundingBox) {
  30243. _this.refreshBoundingInfo();
  30244. mesh.computeWorldMatrix(true);
  30245. }
  30246. return _this;
  30247. }
  30248. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30249. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30250. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30251. };
  30252. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30253. get: function () {
  30254. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30255. },
  30256. enumerable: true,
  30257. configurable: true
  30258. });
  30259. /**
  30260. * Returns the submesh BoudingInfo object.
  30261. */
  30262. SubMesh.prototype.getBoundingInfo = function () {
  30263. if (this.IsGlobal) {
  30264. return this._mesh.getBoundingInfo();
  30265. }
  30266. return this._boundingInfo;
  30267. };
  30268. /**
  30269. * Sets the submesh BoundingInfo.
  30270. * Return the SubMesh.
  30271. */
  30272. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30273. this._boundingInfo = boundingInfo;
  30274. return this;
  30275. };
  30276. /**
  30277. * Returns the mesh of the current submesh.
  30278. */
  30279. SubMesh.prototype.getMesh = function () {
  30280. return this._mesh;
  30281. };
  30282. /**
  30283. * Returns the rendering mesh of the submesh.
  30284. */
  30285. SubMesh.prototype.getRenderingMesh = function () {
  30286. return this._renderingMesh;
  30287. };
  30288. /**
  30289. * Returns the submesh material.
  30290. */
  30291. SubMesh.prototype.getMaterial = function () {
  30292. var rootMaterial = this._renderingMesh.material;
  30293. if (rootMaterial === null || rootMaterial === undefined) {
  30294. return this._mesh.getScene().defaultMaterial;
  30295. }
  30296. else if (rootMaterial.getSubMaterial) {
  30297. var multiMaterial = rootMaterial;
  30298. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30299. if (this._currentMaterial !== effectiveMaterial) {
  30300. this._currentMaterial = effectiveMaterial;
  30301. this._materialDefines = null;
  30302. }
  30303. return effectiveMaterial;
  30304. }
  30305. return rootMaterial;
  30306. };
  30307. // Methods
  30308. /**
  30309. * Sets a new updated BoundingInfo object to the submesh.
  30310. * Returns the SubMesh.
  30311. */
  30312. SubMesh.prototype.refreshBoundingInfo = function () {
  30313. this._lastColliderWorldVertices = null;
  30314. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30315. return this;
  30316. }
  30317. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30318. if (!data) {
  30319. this._boundingInfo = this._mesh.getBoundingInfo();
  30320. return this;
  30321. }
  30322. var indices = this._renderingMesh.getIndices();
  30323. var extend;
  30324. //is this the only submesh?
  30325. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30326. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30327. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30328. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30329. }
  30330. else {
  30331. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30332. }
  30333. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30334. return this;
  30335. };
  30336. SubMesh.prototype._checkCollision = function (collider) {
  30337. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30338. return boundingInfo._checkCollision(collider);
  30339. };
  30340. /**
  30341. * Updates the submesh BoundingInfo.
  30342. * Returns the Submesh.
  30343. */
  30344. SubMesh.prototype.updateBoundingInfo = function (world) {
  30345. var boundingInfo = this.getBoundingInfo();
  30346. if (!boundingInfo) {
  30347. this.refreshBoundingInfo();
  30348. boundingInfo = this.getBoundingInfo();
  30349. }
  30350. boundingInfo.update(world);
  30351. return this;
  30352. };
  30353. /**
  30354. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30355. * Boolean returned.
  30356. */
  30357. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30358. var boundingInfo = this.getBoundingInfo();
  30359. if (!boundingInfo) {
  30360. return false;
  30361. }
  30362. return boundingInfo.isInFrustum(frustumPlanes);
  30363. };
  30364. /**
  30365. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30366. * Boolean returned.
  30367. */
  30368. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30369. var boundingInfo = this.getBoundingInfo();
  30370. if (!boundingInfo) {
  30371. return false;
  30372. }
  30373. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30374. };
  30375. /**
  30376. * Renders the submesh.
  30377. * Returns it.
  30378. */
  30379. SubMesh.prototype.render = function (enableAlphaMode) {
  30380. this._renderingMesh.render(this, enableAlphaMode);
  30381. return this;
  30382. };
  30383. /**
  30384. * Returns a new Index Buffer.
  30385. * Type returned : WebGLBuffer.
  30386. */
  30387. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30388. if (!this._linesIndexBuffer) {
  30389. var linesIndices = [];
  30390. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30391. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30392. }
  30393. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30394. this.linesIndexCount = linesIndices.length;
  30395. }
  30396. return this._linesIndexBuffer;
  30397. };
  30398. /**
  30399. * True is the passed Ray intersects the submesh bounding box.
  30400. * Boolean returned.
  30401. */
  30402. SubMesh.prototype.canIntersects = function (ray) {
  30403. var boundingInfo = this.getBoundingInfo();
  30404. if (!boundingInfo) {
  30405. return false;
  30406. }
  30407. return ray.intersectsBox(boundingInfo.boundingBox);
  30408. };
  30409. /**
  30410. * Returns an object IntersectionInfo.
  30411. */
  30412. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30413. var intersectInfo = null;
  30414. // LineMesh first as it's also a Mesh...
  30415. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30416. var lineMesh = this._mesh;
  30417. // Line test
  30418. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30419. var p0 = positions[indices[index]];
  30420. var p1 = positions[indices[index + 1]];
  30421. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30422. if (length < 0) {
  30423. continue;
  30424. }
  30425. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30426. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30427. if (fastCheck) {
  30428. break;
  30429. }
  30430. }
  30431. }
  30432. }
  30433. else {
  30434. // Triangles test
  30435. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30436. var p0 = positions[indices[index]];
  30437. var p1 = positions[indices[index + 1]];
  30438. var p2 = positions[indices[index + 2]];
  30439. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30440. if (currentIntersectInfo) {
  30441. if (currentIntersectInfo.distance < 0) {
  30442. continue;
  30443. }
  30444. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30445. intersectInfo = currentIntersectInfo;
  30446. intersectInfo.faceId = index / 3;
  30447. if (fastCheck) {
  30448. break;
  30449. }
  30450. }
  30451. }
  30452. }
  30453. }
  30454. return intersectInfo;
  30455. };
  30456. SubMesh.prototype._rebuild = function () {
  30457. if (this._linesIndexBuffer) {
  30458. this._linesIndexBuffer = null;
  30459. }
  30460. };
  30461. // Clone
  30462. /**
  30463. * Creates a new Submesh from the passed Mesh.
  30464. */
  30465. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30466. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30467. if (!this.IsGlobal) {
  30468. var boundingInfo = this.getBoundingInfo();
  30469. if (!boundingInfo) {
  30470. return result;
  30471. }
  30472. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30473. }
  30474. return result;
  30475. };
  30476. // Dispose
  30477. /**
  30478. * Disposes the Submesh.
  30479. * Returns nothing.
  30480. */
  30481. SubMesh.prototype.dispose = function () {
  30482. if (this._linesIndexBuffer) {
  30483. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30484. this._linesIndexBuffer = null;
  30485. }
  30486. // Remove from mesh
  30487. var index = this._mesh.subMeshes.indexOf(this);
  30488. this._mesh.subMeshes.splice(index, 1);
  30489. };
  30490. // Statics
  30491. /**
  30492. * Creates a new Submesh from the passed parameters :
  30493. * - materialIndex (integer) : the index of the main mesh material.
  30494. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30495. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30496. * - mesh (Mesh) : the main mesh to create the submesh from.
  30497. * - renderingMesh (optional Mesh) : rendering mesh.
  30498. */
  30499. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30500. var minVertexIndex = Number.MAX_VALUE;
  30501. var maxVertexIndex = -Number.MAX_VALUE;
  30502. renderingMesh = (renderingMesh || mesh);
  30503. var indices = renderingMesh.getIndices();
  30504. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30505. var vertexIndex = indices[index];
  30506. if (vertexIndex < minVertexIndex)
  30507. minVertexIndex = vertexIndex;
  30508. if (vertexIndex > maxVertexIndex)
  30509. maxVertexIndex = vertexIndex;
  30510. }
  30511. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30512. };
  30513. return SubMesh;
  30514. }(BaseSubMesh));
  30515. BABYLON.SubMesh = SubMesh;
  30516. })(BABYLON || (BABYLON = {}));
  30517. //# sourceMappingURL=babylon.subMesh.js.map
  30518. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30519. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30520. s = arguments[i];
  30521. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30522. t[p] = s[p];
  30523. }
  30524. return t;
  30525. };
  30526. var BABYLON;
  30527. (function (BABYLON) {
  30528. /**
  30529. * Manages the defines for the Material.
  30530. */
  30531. var MaterialDefines = /** @class */ (function () {
  30532. function MaterialDefines() {
  30533. this._isDirty = true;
  30534. this._areLightsDirty = true;
  30535. this._areAttributesDirty = true;
  30536. this._areTexturesDirty = true;
  30537. this._areFresnelDirty = true;
  30538. this._areMiscDirty = true;
  30539. this._areImageProcessingDirty = true;
  30540. this._normals = false;
  30541. this._uvs = false;
  30542. this._needNormals = false;
  30543. this._needUVs = false;
  30544. }
  30545. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30546. /**
  30547. * Specifies if the material needs to be re-calculated.
  30548. */
  30549. get: function () {
  30550. return this._isDirty;
  30551. },
  30552. enumerable: true,
  30553. configurable: true
  30554. });
  30555. /**
  30556. * Marks the material to indicate that it has been re-calculated.
  30557. */
  30558. MaterialDefines.prototype.markAsProcessed = function () {
  30559. this._isDirty = false;
  30560. this._areAttributesDirty = false;
  30561. this._areTexturesDirty = false;
  30562. this._areFresnelDirty = false;
  30563. this._areLightsDirty = false;
  30564. this._areMiscDirty = false;
  30565. this._areImageProcessingDirty = false;
  30566. };
  30567. /**
  30568. * Marks the material to indicate that it needs to be re-calculated.
  30569. */
  30570. MaterialDefines.prototype.markAsUnprocessed = function () {
  30571. this._isDirty = true;
  30572. };
  30573. /**
  30574. * Marks the material to indicate all of its defines need to be re-calculated.
  30575. */
  30576. MaterialDefines.prototype.markAllAsDirty = function () {
  30577. this._areTexturesDirty = true;
  30578. this._areAttributesDirty = true;
  30579. this._areLightsDirty = true;
  30580. this._areFresnelDirty = true;
  30581. this._areMiscDirty = true;
  30582. this._areImageProcessingDirty = true;
  30583. this._isDirty = true;
  30584. };
  30585. /**
  30586. * Marks the material to indicate that image processing needs to be re-calculated.
  30587. */
  30588. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30589. this._areImageProcessingDirty = true;
  30590. this._isDirty = true;
  30591. };
  30592. /**
  30593. * Marks the material to indicate the lights need to be re-calculated.
  30594. */
  30595. MaterialDefines.prototype.markAsLightDirty = function () {
  30596. this._areLightsDirty = true;
  30597. this._isDirty = true;
  30598. };
  30599. /**
  30600. * Marks the attribute state as changed.
  30601. */
  30602. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30603. this._areAttributesDirty = true;
  30604. this._isDirty = true;
  30605. };
  30606. /**
  30607. * Marks the texture state as changed.
  30608. */
  30609. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30610. this._areTexturesDirty = true;
  30611. this._isDirty = true;
  30612. };
  30613. /**
  30614. * Marks the fresnel state as changed.
  30615. */
  30616. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30617. this._areFresnelDirty = true;
  30618. this._isDirty = true;
  30619. };
  30620. /**
  30621. * Marks the misc state as changed.
  30622. */
  30623. MaterialDefines.prototype.markAsMiscDirty = function () {
  30624. this._areMiscDirty = true;
  30625. this._isDirty = true;
  30626. };
  30627. /**
  30628. * Rebuilds the material defines.
  30629. */
  30630. MaterialDefines.prototype.rebuild = function () {
  30631. if (this._keys) {
  30632. delete this._keys;
  30633. }
  30634. this._keys = [];
  30635. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30636. var key = _a[_i];
  30637. if (key[0] === "_") {
  30638. continue;
  30639. }
  30640. this._keys.push(key);
  30641. }
  30642. };
  30643. /**
  30644. * Specifies if two material defines are equal.
  30645. * @param other - A material define instance to compare to.
  30646. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30647. */
  30648. MaterialDefines.prototype.isEqual = function (other) {
  30649. if (this._keys.length !== other._keys.length) {
  30650. return false;
  30651. }
  30652. for (var index = 0; index < this._keys.length; index++) {
  30653. var prop = this._keys[index];
  30654. if (this[prop] !== other[prop]) {
  30655. return false;
  30656. }
  30657. }
  30658. return true;
  30659. };
  30660. /**
  30661. * Clones this instance's defines to another instance.
  30662. * @param other - material defines to clone values to.
  30663. */
  30664. MaterialDefines.prototype.cloneTo = function (other) {
  30665. if (this._keys.length !== other._keys.length) {
  30666. other._keys = this._keys.slice(0);
  30667. }
  30668. for (var index = 0; index < this._keys.length; index++) {
  30669. var prop = this._keys[index];
  30670. other[prop] = this[prop];
  30671. }
  30672. };
  30673. /**
  30674. * Resets the material define values.
  30675. */
  30676. MaterialDefines.prototype.reset = function () {
  30677. for (var index = 0; index < this._keys.length; index++) {
  30678. var prop = this._keys[index];
  30679. if (typeof (this[prop]) === "number") {
  30680. this[prop] = 0;
  30681. }
  30682. else {
  30683. this[prop] = false;
  30684. }
  30685. }
  30686. };
  30687. /**
  30688. * Converts the material define values to a string.
  30689. * @returns - String of material define information.
  30690. */
  30691. MaterialDefines.prototype.toString = function () {
  30692. var result = "";
  30693. for (var index = 0; index < this._keys.length; index++) {
  30694. var prop = this._keys[index];
  30695. var value = this[prop];
  30696. if (typeof (value) === "number") {
  30697. result += "#define " + prop + " " + this[prop] + "\n";
  30698. }
  30699. else if (value) {
  30700. result += "#define " + prop + "\n";
  30701. }
  30702. }
  30703. return result;
  30704. };
  30705. return MaterialDefines;
  30706. }());
  30707. BABYLON.MaterialDefines = MaterialDefines;
  30708. /**
  30709. * This offers the main features of a material in BJS.
  30710. */
  30711. var Material = /** @class */ (function () {
  30712. /**
  30713. * Creates a material instance.
  30714. * @param name - The name of the material.
  30715. * @param scene - The BJS scene to reference.
  30716. * @param doNotAdd - Specifies if the material should be added to the scene.
  30717. */
  30718. function Material(name, scene, doNotAdd) {
  30719. /**
  30720. * Specifies if the ready state should be checked on each call.
  30721. */
  30722. this.checkReadyOnEveryCall = false;
  30723. /**
  30724. * Specifies if the ready state should be checked once.
  30725. */
  30726. this.checkReadyOnlyOnce = false;
  30727. /**
  30728. * The state of the material.
  30729. */
  30730. this.state = "";
  30731. /**
  30732. * The alpha value of the material.
  30733. */
  30734. this._alpha = 1.0;
  30735. /**
  30736. * Specifies if back face culling is enabled.
  30737. */
  30738. this._backFaceCulling = true;
  30739. /**
  30740. * Specifies if the material should be serialized.
  30741. */
  30742. this.doNotSerialize = false;
  30743. /**
  30744. * Specifies if the effect should be stored on sub meshes.
  30745. */
  30746. this.storeEffectOnSubMeshes = false;
  30747. /**
  30748. * An event triggered when the material is disposed.
  30749. * @type {BABYLON.Observable}
  30750. */
  30751. this.onDisposeObservable = new BABYLON.Observable();
  30752. /**
  30753. * An event triggered when the material is bound.
  30754. * @type {BABYLON.Observable}
  30755. */
  30756. this.onBindObservable = new BABYLON.Observable();
  30757. /**
  30758. * An event triggered when the material is unbound.
  30759. * @type {BABYLON.Observable}
  30760. */
  30761. this.onUnBindObservable = new BABYLON.Observable();
  30762. /**
  30763. * Stores the value of the alpha mode.
  30764. */
  30765. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30766. /**
  30767. * Stores the state of the need depth pre-pass value.
  30768. */
  30769. this._needDepthPrePass = false;
  30770. /**
  30771. * Specifies if depth writing should be disabled.
  30772. */
  30773. this.disableDepthWrite = false;
  30774. /**
  30775. * Specifies if depth writing should be forced.
  30776. */
  30777. this.forceDepthWrite = false;
  30778. /**
  30779. * Specifies if there should be a separate pass for culling.
  30780. */
  30781. this.separateCullingPass = false;
  30782. /**
  30783. * Stores the state specifing if fog should be enabled.
  30784. */
  30785. this._fogEnabled = true;
  30786. /**
  30787. * Stores the size of points.
  30788. */
  30789. this.pointSize = 1.0;
  30790. /**
  30791. * Stores the z offset value.
  30792. */
  30793. this.zOffset = 0;
  30794. /**
  30795. * Specifies if the material was previously ready.
  30796. */
  30797. this._wasPreviouslyReady = false;
  30798. /**
  30799. * Stores the fill mode state.
  30800. */
  30801. this._fillMode = Material.TriangleFillMode;
  30802. this.name = name;
  30803. this.id = name || BABYLON.Tools.RandomId();
  30804. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30805. if (this._scene.useRightHandedSystem) {
  30806. this.sideOrientation = Material.ClockWiseSideOrientation;
  30807. }
  30808. else {
  30809. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30810. }
  30811. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30812. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30813. if (!doNotAdd) {
  30814. this._scene.materials.push(this);
  30815. }
  30816. }
  30817. Object.defineProperty(Material, "TriangleFillMode", {
  30818. /**
  30819. * Returns the triangle fill mode.
  30820. */
  30821. get: function () {
  30822. return Material._TriangleFillMode;
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. Object.defineProperty(Material, "WireFrameFillMode", {
  30828. /**
  30829. * Returns the wireframe mode.
  30830. */
  30831. get: function () {
  30832. return Material._WireFrameFillMode;
  30833. },
  30834. enumerable: true,
  30835. configurable: true
  30836. });
  30837. Object.defineProperty(Material, "PointFillMode", {
  30838. /**
  30839. * Returns the point fill mode.
  30840. */
  30841. get: function () {
  30842. return Material._PointFillMode;
  30843. },
  30844. enumerable: true,
  30845. configurable: true
  30846. });
  30847. Object.defineProperty(Material, "PointListDrawMode", {
  30848. /**
  30849. * Returns the point list draw mode.
  30850. */
  30851. get: function () {
  30852. return Material._PointListDrawMode;
  30853. },
  30854. enumerable: true,
  30855. configurable: true
  30856. });
  30857. Object.defineProperty(Material, "LineListDrawMode", {
  30858. /**
  30859. * Returns the line list draw mode.
  30860. */
  30861. get: function () {
  30862. return Material._LineListDrawMode;
  30863. },
  30864. enumerable: true,
  30865. configurable: true
  30866. });
  30867. Object.defineProperty(Material, "LineLoopDrawMode", {
  30868. /**
  30869. * Returns the line loop draw mode.
  30870. */
  30871. get: function () {
  30872. return Material._LineLoopDrawMode;
  30873. },
  30874. enumerable: true,
  30875. configurable: true
  30876. });
  30877. Object.defineProperty(Material, "LineStripDrawMode", {
  30878. /**
  30879. * Returns the line strip draw mode.
  30880. */
  30881. get: function () {
  30882. return Material._LineStripDrawMode;
  30883. },
  30884. enumerable: true,
  30885. configurable: true
  30886. });
  30887. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30888. /**
  30889. * Returns the triangle strip draw mode.
  30890. */
  30891. get: function () {
  30892. return Material._TriangleStripDrawMode;
  30893. },
  30894. enumerable: true,
  30895. configurable: true
  30896. });
  30897. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30898. /**
  30899. * Returns the triangle fan draw mode.
  30900. */
  30901. get: function () {
  30902. return Material._TriangleFanDrawMode;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30908. /**
  30909. * Returns the clock-wise side orientation.
  30910. */
  30911. get: function () {
  30912. return Material._ClockWiseSideOrientation;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30918. /**
  30919. * Returns the counter clock-wise side orientation.
  30920. */
  30921. get: function () {
  30922. return Material._CounterClockWiseSideOrientation;
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. Object.defineProperty(Material, "TextureDirtyFlag", {
  30928. /**
  30929. * Returns the dirty texture flag value.
  30930. */
  30931. get: function () {
  30932. return Material._TextureDirtyFlag;
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. Object.defineProperty(Material, "LightDirtyFlag", {
  30938. /**
  30939. * Returns the dirty light flag value.
  30940. */
  30941. get: function () {
  30942. return Material._LightDirtyFlag;
  30943. },
  30944. enumerable: true,
  30945. configurable: true
  30946. });
  30947. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30948. /**
  30949. * Returns the dirty fresnel flag value.
  30950. */
  30951. get: function () {
  30952. return Material._FresnelDirtyFlag;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30958. /**
  30959. * Returns the dirty attributes flag value.
  30960. */
  30961. get: function () {
  30962. return Material._AttributesDirtyFlag;
  30963. },
  30964. enumerable: true,
  30965. configurable: true
  30966. });
  30967. Object.defineProperty(Material, "MiscDirtyFlag", {
  30968. /**
  30969. * Returns the dirty misc flag value.
  30970. */
  30971. get: function () {
  30972. return Material._MiscDirtyFlag;
  30973. },
  30974. enumerable: true,
  30975. configurable: true
  30976. });
  30977. Object.defineProperty(Material.prototype, "alpha", {
  30978. /**
  30979. * Gets the alpha value of the material.
  30980. */
  30981. get: function () {
  30982. return this._alpha;
  30983. },
  30984. /**
  30985. * Sets the alpha value of the material.
  30986. */
  30987. set: function (value) {
  30988. if (this._alpha === value) {
  30989. return;
  30990. }
  30991. this._alpha = value;
  30992. this.markAsDirty(Material.MiscDirtyFlag);
  30993. },
  30994. enumerable: true,
  30995. configurable: true
  30996. });
  30997. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30998. /**
  30999. * Gets the back-face culling state.
  31000. */
  31001. get: function () {
  31002. return this._backFaceCulling;
  31003. },
  31004. /**
  31005. * Sets the back-face culling state.
  31006. */
  31007. set: function (value) {
  31008. if (this._backFaceCulling === value) {
  31009. return;
  31010. }
  31011. this._backFaceCulling = value;
  31012. this.markAsDirty(Material.TextureDirtyFlag);
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(Material.prototype, "onDispose", {
  31018. /**
  31019. * Called during a dispose event.
  31020. */
  31021. set: function (callback) {
  31022. if (this._onDisposeObserver) {
  31023. this.onDisposeObservable.remove(this._onDisposeObserver);
  31024. }
  31025. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31026. },
  31027. enumerable: true,
  31028. configurable: true
  31029. });
  31030. Object.defineProperty(Material.prototype, "onBind", {
  31031. /**
  31032. * Called during a bind event.
  31033. */
  31034. set: function (callback) {
  31035. if (this._onBindObserver) {
  31036. this.onBindObservable.remove(this._onBindObserver);
  31037. }
  31038. this._onBindObserver = this.onBindObservable.add(callback);
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(Material.prototype, "alphaMode", {
  31044. /**
  31045. * Gets the value of the alpha mode.
  31046. */
  31047. get: function () {
  31048. return this._alphaMode;
  31049. },
  31050. /**
  31051. * Sets the value of the alpha mode.
  31052. */
  31053. set: function (value) {
  31054. if (this._alphaMode === value) {
  31055. return;
  31056. }
  31057. this._alphaMode = value;
  31058. this.markAsDirty(Material.TextureDirtyFlag);
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31064. /**
  31065. * Gets the depth pre-pass value.
  31066. */
  31067. get: function () {
  31068. return this._needDepthPrePass;
  31069. },
  31070. /**
  31071. * Sets the need depth pre-pass value.
  31072. */
  31073. set: function (value) {
  31074. if (this._needDepthPrePass === value) {
  31075. return;
  31076. }
  31077. this._needDepthPrePass = value;
  31078. if (this._needDepthPrePass) {
  31079. this.checkReadyOnEveryCall = true;
  31080. }
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Object.defineProperty(Material.prototype, "fogEnabled", {
  31086. /**
  31087. * Gets the value of the fog enabled state.
  31088. */
  31089. get: function () {
  31090. return this._fogEnabled;
  31091. },
  31092. /**
  31093. * Sets the state for enabling fog.
  31094. */
  31095. set: function (value) {
  31096. if (this._fogEnabled === value) {
  31097. return;
  31098. }
  31099. this._fogEnabled = value;
  31100. this.markAsDirty(Material.MiscDirtyFlag);
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. Object.defineProperty(Material.prototype, "wireframe", {
  31106. /**
  31107. * Gets a value specifying if wireframe mode is enabled.
  31108. */
  31109. get: function () {
  31110. return this._fillMode === Material.WireFrameFillMode;
  31111. },
  31112. /**
  31113. * Sets the state of wireframe mode.
  31114. */
  31115. set: function (value) {
  31116. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31117. },
  31118. enumerable: true,
  31119. configurable: true
  31120. });
  31121. Object.defineProperty(Material.prototype, "pointsCloud", {
  31122. /**
  31123. * Gets the value specifying if point clouds are enabled.
  31124. */
  31125. get: function () {
  31126. return this._fillMode === Material.PointFillMode;
  31127. },
  31128. /**
  31129. * Sets the state of point cloud mode.
  31130. */
  31131. set: function (value) {
  31132. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Material.prototype, "fillMode", {
  31138. /**
  31139. * Gets the material fill mode.
  31140. */
  31141. get: function () {
  31142. return this._fillMode;
  31143. },
  31144. /**
  31145. * Sets the material fill mode.
  31146. */
  31147. set: function (value) {
  31148. if (this._fillMode === value) {
  31149. return;
  31150. }
  31151. this._fillMode = value;
  31152. this.markAsDirty(Material.MiscDirtyFlag);
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. /**
  31158. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31159. * subclasses should override adding information pertainent to themselves.
  31160. * @returns - String with material information.
  31161. */
  31162. Material.prototype.toString = function (fullDetails) {
  31163. var ret = "Name: " + this.name;
  31164. if (fullDetails) {
  31165. }
  31166. return ret;
  31167. };
  31168. /**
  31169. * Gets the class name of the material.
  31170. * @returns - String with the class name of the material.
  31171. */
  31172. Material.prototype.getClassName = function () {
  31173. return "Material";
  31174. };
  31175. Object.defineProperty(Material.prototype, "isFrozen", {
  31176. /**
  31177. * Specifies if updates for the material been locked.
  31178. */
  31179. get: function () {
  31180. return this.checkReadyOnlyOnce;
  31181. },
  31182. enumerable: true,
  31183. configurable: true
  31184. });
  31185. /**
  31186. * Locks updates for the material.
  31187. */
  31188. Material.prototype.freeze = function () {
  31189. this.checkReadyOnlyOnce = true;
  31190. };
  31191. /**
  31192. * Unlocks updates for the material.
  31193. */
  31194. Material.prototype.unfreeze = function () {
  31195. this.checkReadyOnlyOnce = false;
  31196. };
  31197. /**
  31198. * Specifies if the material is ready to be used.
  31199. * @param mesh - BJS mesh.
  31200. * @param useInstances - Specifies if instances should be used.
  31201. * @returns - Boolean indicating if the material is ready to be used.
  31202. */
  31203. Material.prototype.isReady = function (mesh, useInstances) {
  31204. return true;
  31205. };
  31206. /**
  31207. * Specifies that the submesh is ready to be used.
  31208. * @param mesh - BJS mesh.
  31209. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31210. * @param useInstances - Specifies that instances should be used.
  31211. * @returns - boolean indicating that the submesh is ready or not.
  31212. */
  31213. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31214. return false;
  31215. };
  31216. /**
  31217. * Returns the material effect.
  31218. * @returns - Nullable material effect.
  31219. */
  31220. Material.prototype.getEffect = function () {
  31221. return this._effect;
  31222. };
  31223. /**
  31224. * Returns the BJS scene.
  31225. * @returns - BJS Scene.
  31226. */
  31227. Material.prototype.getScene = function () {
  31228. return this._scene;
  31229. };
  31230. /**
  31231. * Specifies if the material will require alpha blending
  31232. * @returns - Boolean specifying if alpha blending is needed.
  31233. */
  31234. Material.prototype.needAlphaBlending = function () {
  31235. return (this.alpha < 1.0);
  31236. };
  31237. /**
  31238. * Specifies if the mesh will require alpha blending.
  31239. * @param mesh - BJS mesh.
  31240. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31241. */
  31242. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31243. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31244. };
  31245. /**
  31246. * Specifies if this material should be rendered in alpha test mode.
  31247. * @returns - Boolean specifying if an alpha test is needed.
  31248. */
  31249. Material.prototype.needAlphaTesting = function () {
  31250. return false;
  31251. };
  31252. /**
  31253. * Gets the texture used for the alpha test.
  31254. * @returns - Nullable alpha test texture.
  31255. */
  31256. Material.prototype.getAlphaTestTexture = function () {
  31257. return null;
  31258. };
  31259. /**
  31260. * Marks the material to indicate that it needs to be re-calculated.
  31261. */
  31262. Material.prototype.markDirty = function () {
  31263. this._wasPreviouslyReady = false;
  31264. };
  31265. Material.prototype._preBind = function (effect, overrideOrientation) {
  31266. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31267. var engine = this._scene.getEngine();
  31268. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31269. var reverse = orientation === Material.ClockWiseSideOrientation;
  31270. engine.enableEffect(effect ? effect : this._effect);
  31271. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31272. return reverse;
  31273. };
  31274. /**
  31275. * Binds the material to the mesh.
  31276. * @param world - World transformation matrix.
  31277. * @param mesh - Mesh to bind the material to.
  31278. */
  31279. Material.prototype.bind = function (world, mesh) {
  31280. };
  31281. /**
  31282. * Binds the submesh to the material.
  31283. * @param world - World transformation matrix.
  31284. * @param mesh - Mesh containing the submesh.
  31285. * @param subMesh - Submesh to bind the material to.
  31286. */
  31287. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31288. };
  31289. /**
  31290. * Binds the world matrix to the material.
  31291. * @param world - World transformation matrix.
  31292. */
  31293. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31294. };
  31295. /**
  31296. * Binds the scene's uniform buffer to the effect.
  31297. * @param effect - Effect to bind to the scene uniform buffer.
  31298. * @param sceneUbo - Scene uniform buffer.
  31299. */
  31300. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31301. sceneUbo.bindToEffect(effect, "Scene");
  31302. };
  31303. /**
  31304. * Binds the view matrix to the effect.
  31305. * @param effect - Effect to bind the view matrix to.
  31306. */
  31307. Material.prototype.bindView = function (effect) {
  31308. if (!this._useUBO) {
  31309. effect.setMatrix("view", this.getScene().getViewMatrix());
  31310. }
  31311. else {
  31312. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31313. }
  31314. };
  31315. /**
  31316. * Binds the view projection matrix to the effect.
  31317. * @param effect - Effect to bind the view projection matrix to.
  31318. */
  31319. Material.prototype.bindViewProjection = function (effect) {
  31320. if (!this._useUBO) {
  31321. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31322. }
  31323. else {
  31324. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31325. }
  31326. };
  31327. /**
  31328. * Specifies if material alpha testing should be turned on for the mesh.
  31329. * @param mesh - BJS mesh.
  31330. */
  31331. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31332. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31333. };
  31334. /**
  31335. * Processes to execute after binding the material to a mesh.
  31336. * @param mesh - BJS mesh.
  31337. */
  31338. Material.prototype._afterBind = function (mesh) {
  31339. this._scene._cachedMaterial = this;
  31340. if (mesh) {
  31341. this._scene._cachedVisibility = mesh.visibility;
  31342. }
  31343. else {
  31344. this._scene._cachedVisibility = 1;
  31345. }
  31346. if (mesh) {
  31347. this.onBindObservable.notifyObservers(mesh);
  31348. }
  31349. if (this.disableDepthWrite) {
  31350. var engine = this._scene.getEngine();
  31351. this._cachedDepthWriteState = engine.getDepthWrite();
  31352. engine.setDepthWrite(false);
  31353. }
  31354. };
  31355. /**
  31356. * Unbinds the material from the mesh.
  31357. */
  31358. Material.prototype.unbind = function () {
  31359. this.onUnBindObservable.notifyObservers(this);
  31360. if (this.disableDepthWrite) {
  31361. var engine = this._scene.getEngine();
  31362. engine.setDepthWrite(this._cachedDepthWriteState);
  31363. }
  31364. };
  31365. /**
  31366. * Gets the active textures from the material.
  31367. * @returns - Array of textures.
  31368. */
  31369. Material.prototype.getActiveTextures = function () {
  31370. return [];
  31371. };
  31372. /**
  31373. * Specifies if the material uses a texture.
  31374. * @param texture - Texture to check against the material.
  31375. * @returns - Boolean specifying if the material uses the texture.
  31376. */
  31377. Material.prototype.hasTexture = function (texture) {
  31378. return false;
  31379. };
  31380. /**
  31381. * Makes a duplicate of the material, and gives it a new name.
  31382. * @param name - Name to call the duplicated material.
  31383. * @returns - Nullable cloned material
  31384. */
  31385. Material.prototype.clone = function (name) {
  31386. return null;
  31387. };
  31388. /**
  31389. * Gets the meshes bound to the material.
  31390. * @returns - Array of meshes bound to the material.
  31391. */
  31392. Material.prototype.getBindedMeshes = function () {
  31393. var result = new Array();
  31394. for (var index = 0; index < this._scene.meshes.length; index++) {
  31395. var mesh = this._scene.meshes[index];
  31396. if (mesh.material === this) {
  31397. result.push(mesh);
  31398. }
  31399. }
  31400. return result;
  31401. };
  31402. /**
  31403. * Force shader compilation
  31404. * @param mesh - BJS mesh.
  31405. * @param onCompiled - function to execute once the material is compiled.
  31406. * @param options - options to pass to this function.
  31407. */
  31408. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31409. var _this = this;
  31410. var localOptions = __assign({ clipPlane: false }, options);
  31411. var subMesh = new BABYLON.BaseSubMesh();
  31412. var scene = this.getScene();
  31413. var checkReady = function () {
  31414. if (!_this._scene || !_this._scene.getEngine()) {
  31415. return;
  31416. }
  31417. if (subMesh._materialDefines) {
  31418. subMesh._materialDefines._renderId = -1;
  31419. }
  31420. var clipPlaneState = scene.clipPlane;
  31421. if (localOptions.clipPlane) {
  31422. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31423. }
  31424. if (_this.storeEffectOnSubMeshes) {
  31425. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31426. if (onCompiled) {
  31427. onCompiled(_this);
  31428. }
  31429. }
  31430. else {
  31431. setTimeout(checkReady, 16);
  31432. }
  31433. }
  31434. else {
  31435. if (_this.isReady(mesh)) {
  31436. if (onCompiled) {
  31437. onCompiled(_this);
  31438. }
  31439. }
  31440. else {
  31441. setTimeout(checkReady, 16);
  31442. }
  31443. }
  31444. if (localOptions.clipPlane) {
  31445. scene.clipPlane = clipPlaneState;
  31446. }
  31447. };
  31448. checkReady();
  31449. };
  31450. /**
  31451. * Force shader compilation.
  31452. * @param mesh The mesh that will use this material
  31453. * @param options Additional options for compiling the shaders
  31454. * @returns A promise that resolves when the compilation completes
  31455. */
  31456. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31457. var _this = this;
  31458. return new Promise(function (resolve) {
  31459. _this.forceCompilation(mesh, function () {
  31460. resolve();
  31461. }, options);
  31462. });
  31463. };
  31464. /**
  31465. * Marks a define in the material to indicate that it needs to be re-computed.
  31466. * @param flag - Material define flag.
  31467. */
  31468. Material.prototype.markAsDirty = function (flag) {
  31469. if (flag & Material.TextureDirtyFlag) {
  31470. this._markAllSubMeshesAsTexturesDirty();
  31471. }
  31472. if (flag & Material.LightDirtyFlag) {
  31473. this._markAllSubMeshesAsLightsDirty();
  31474. }
  31475. if (flag & Material.FresnelDirtyFlag) {
  31476. this._markAllSubMeshesAsFresnelDirty();
  31477. }
  31478. if (flag & Material.AttributesDirtyFlag) {
  31479. this._markAllSubMeshesAsAttributesDirty();
  31480. }
  31481. if (flag & Material.MiscDirtyFlag) {
  31482. this._markAllSubMeshesAsMiscDirty();
  31483. }
  31484. this.getScene().resetCachedMaterial();
  31485. };
  31486. /**
  31487. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31488. * @param func - function which checks material defines against the submeshes.
  31489. */
  31490. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31491. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31492. var mesh = _a[_i];
  31493. if (!mesh.subMeshes) {
  31494. continue;
  31495. }
  31496. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31497. var subMesh = _c[_b];
  31498. if (subMesh.getMaterial() !== this) {
  31499. continue;
  31500. }
  31501. if (!subMesh._materialDefines) {
  31502. continue;
  31503. }
  31504. func(subMesh._materialDefines);
  31505. }
  31506. }
  31507. };
  31508. /**
  31509. * Indicates that image processing needs to be re-calculated for all submeshes.
  31510. */
  31511. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31512. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31513. };
  31514. /**
  31515. * Indicates that textures need to be re-calculated for all submeshes.
  31516. */
  31517. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31518. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31519. };
  31520. /**
  31521. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31522. */
  31523. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31524. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31525. };
  31526. /**
  31527. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31528. */
  31529. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31530. this._markAllSubMeshesAsDirty(function (defines) {
  31531. defines.markAsFresnelDirty();
  31532. defines.markAsMiscDirty();
  31533. });
  31534. };
  31535. /**
  31536. * Indicates that lights need to be re-calculated for all submeshes.
  31537. */
  31538. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31539. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31540. };
  31541. /**
  31542. * Indicates that attributes need to be re-calculated for all submeshes.
  31543. */
  31544. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31545. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31546. };
  31547. /**
  31548. * Indicates that misc needs to be re-calculated for all submeshes.
  31549. */
  31550. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31551. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31552. };
  31553. /**
  31554. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31555. */
  31556. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31557. this._markAllSubMeshesAsDirty(function (defines) {
  31558. defines.markAsTexturesDirty();
  31559. defines.markAsMiscDirty();
  31560. });
  31561. };
  31562. /**
  31563. * Disposes the material.
  31564. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31565. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31566. */
  31567. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31568. // Animations
  31569. this.getScene().stopAnimation(this);
  31570. // Remove from scene
  31571. var index = this._scene.materials.indexOf(this);
  31572. if (index >= 0) {
  31573. this._scene.materials.splice(index, 1);
  31574. }
  31575. // Remove from meshes
  31576. for (index = 0; index < this._scene.meshes.length; index++) {
  31577. var mesh = this._scene.meshes[index];
  31578. if (mesh.material === this) {
  31579. mesh.material = null;
  31580. if (mesh.geometry) {
  31581. var geometry = (mesh.geometry);
  31582. if (this.storeEffectOnSubMeshes) {
  31583. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31584. var subMesh = _a[_i];
  31585. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31586. if (forceDisposeEffect && subMesh._materialEffect) {
  31587. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31588. }
  31589. }
  31590. }
  31591. else {
  31592. geometry._releaseVertexArrayObject(this._effect);
  31593. }
  31594. }
  31595. }
  31596. }
  31597. this._uniformBuffer.dispose();
  31598. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31599. if (forceDisposeEffect && this._effect) {
  31600. if (!this.storeEffectOnSubMeshes) {
  31601. this._scene.getEngine()._releaseEffect(this._effect);
  31602. }
  31603. this._effect = null;
  31604. }
  31605. // Callback
  31606. this.onDisposeObservable.notifyObservers(this);
  31607. this.onDisposeObservable.clear();
  31608. this.onBindObservable.clear();
  31609. this.onUnBindObservable.clear();
  31610. };
  31611. /**
  31612. * Serializes this material.
  31613. * @returns - serialized material object.
  31614. */
  31615. Material.prototype.serialize = function () {
  31616. return BABYLON.SerializationHelper.Serialize(this);
  31617. };
  31618. /**
  31619. * Creates a MultiMaterial from parse MultiMaterial data.
  31620. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31621. * @param scene - BJS scene.
  31622. * @returns - MultiMaterial.
  31623. */
  31624. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31625. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31626. multiMaterial.id = parsedMultiMaterial.id;
  31627. if (BABYLON.Tags) {
  31628. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31629. }
  31630. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31631. var subMatId = parsedMultiMaterial.materials[matIndex];
  31632. if (subMatId) {
  31633. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31634. }
  31635. else {
  31636. multiMaterial.subMaterials.push(null);
  31637. }
  31638. }
  31639. return multiMaterial;
  31640. };
  31641. /**
  31642. * Creates a material from parsed material data.
  31643. * @param parsedMaterial - Parsed material data.
  31644. * @param scene - BJS scene.
  31645. * @param rootUrl - Root URL containing the material information.
  31646. * @returns - Parsed material.
  31647. */
  31648. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31649. if (!parsedMaterial.customType) {
  31650. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31651. }
  31652. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31653. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31654. if (!BABYLON.LegacyPBRMaterial) {
  31655. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31656. return;
  31657. }
  31658. }
  31659. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31660. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31661. ;
  31662. };
  31663. // Triangle views
  31664. Material._TriangleFillMode = 0;
  31665. Material._WireFrameFillMode = 1;
  31666. Material._PointFillMode = 2;
  31667. // Draw modes
  31668. Material._PointListDrawMode = 3;
  31669. Material._LineListDrawMode = 4;
  31670. Material._LineLoopDrawMode = 5;
  31671. Material._LineStripDrawMode = 6;
  31672. Material._TriangleStripDrawMode = 7;
  31673. Material._TriangleFanDrawMode = 8;
  31674. /**
  31675. * Stores the clock-wise side orientation.
  31676. */
  31677. Material._ClockWiseSideOrientation = 0;
  31678. /**
  31679. * Stores the counter clock-wise side orientation.
  31680. */
  31681. Material._CounterClockWiseSideOrientation = 1;
  31682. /**
  31683. * The dirty texture flag value.
  31684. */
  31685. Material._TextureDirtyFlag = 1;
  31686. /**
  31687. * The dirty light flag value.
  31688. */
  31689. Material._LightDirtyFlag = 2;
  31690. /**
  31691. * The dirty fresnel flag value.
  31692. */
  31693. Material._FresnelDirtyFlag = 4;
  31694. /**
  31695. * The dirty attribute flag value.
  31696. */
  31697. Material._AttributesDirtyFlag = 8;
  31698. /**
  31699. * The dirty misc flag value.
  31700. */
  31701. Material._MiscDirtyFlag = 16;
  31702. __decorate([
  31703. BABYLON.serialize()
  31704. ], Material.prototype, "id", void 0);
  31705. __decorate([
  31706. BABYLON.serialize()
  31707. ], Material.prototype, "name", void 0);
  31708. __decorate([
  31709. BABYLON.serialize()
  31710. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31711. __decorate([
  31712. BABYLON.serialize()
  31713. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31714. __decorate([
  31715. BABYLON.serialize()
  31716. ], Material.prototype, "state", void 0);
  31717. __decorate([
  31718. BABYLON.serialize("alpha")
  31719. ], Material.prototype, "_alpha", void 0);
  31720. __decorate([
  31721. BABYLON.serialize("backFaceCulling")
  31722. ], Material.prototype, "_backFaceCulling", void 0);
  31723. __decorate([
  31724. BABYLON.serialize()
  31725. ], Material.prototype, "sideOrientation", void 0);
  31726. __decorate([
  31727. BABYLON.serialize("alphaMode")
  31728. ], Material.prototype, "_alphaMode", void 0);
  31729. __decorate([
  31730. BABYLON.serialize()
  31731. ], Material.prototype, "_needDepthPrePass", void 0);
  31732. __decorate([
  31733. BABYLON.serialize()
  31734. ], Material.prototype, "disableDepthWrite", void 0);
  31735. __decorate([
  31736. BABYLON.serialize()
  31737. ], Material.prototype, "forceDepthWrite", void 0);
  31738. __decorate([
  31739. BABYLON.serialize()
  31740. ], Material.prototype, "separateCullingPass", void 0);
  31741. __decorate([
  31742. BABYLON.serialize("fogEnabled")
  31743. ], Material.prototype, "_fogEnabled", void 0);
  31744. __decorate([
  31745. BABYLON.serialize()
  31746. ], Material.prototype, "pointSize", void 0);
  31747. __decorate([
  31748. BABYLON.serialize()
  31749. ], Material.prototype, "zOffset", void 0);
  31750. __decorate([
  31751. BABYLON.serialize()
  31752. ], Material.prototype, "wireframe", null);
  31753. __decorate([
  31754. BABYLON.serialize()
  31755. ], Material.prototype, "pointsCloud", null);
  31756. __decorate([
  31757. BABYLON.serialize()
  31758. ], Material.prototype, "fillMode", null);
  31759. return Material;
  31760. }());
  31761. BABYLON.Material = Material;
  31762. })(BABYLON || (BABYLON = {}));
  31763. //# sourceMappingURL=babylon.material.js.map
  31764. var BABYLON;
  31765. (function (BABYLON) {
  31766. var UniformBuffer = /** @class */ (function () {
  31767. /**
  31768. * Uniform buffer objects.
  31769. *
  31770. * Handles blocks of uniform on the GPU.
  31771. *
  31772. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31773. *
  31774. * For more information, please refer to :
  31775. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31776. */
  31777. function UniformBuffer(engine, data, dynamic) {
  31778. this._engine = engine;
  31779. this._noUBO = !engine.supportsUniformBuffers;
  31780. this._dynamic = dynamic;
  31781. this._data = data || [];
  31782. this._uniformLocations = {};
  31783. this._uniformSizes = {};
  31784. this._uniformLocationPointer = 0;
  31785. this._needSync = false;
  31786. if (this._noUBO) {
  31787. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31788. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31789. this.updateFloat = this._updateFloatForEffect;
  31790. this.updateFloat2 = this._updateFloat2ForEffect;
  31791. this.updateFloat3 = this._updateFloat3ForEffect;
  31792. this.updateFloat4 = this._updateFloat4ForEffect;
  31793. this.updateMatrix = this._updateMatrixForEffect;
  31794. this.updateVector3 = this._updateVector3ForEffect;
  31795. this.updateVector4 = this._updateVector4ForEffect;
  31796. this.updateColor3 = this._updateColor3ForEffect;
  31797. this.updateColor4 = this._updateColor4ForEffect;
  31798. }
  31799. else {
  31800. this._engine._uniformBuffers.push(this);
  31801. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31802. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31803. this.updateFloat = this._updateFloatForUniform;
  31804. this.updateFloat2 = this._updateFloat2ForUniform;
  31805. this.updateFloat3 = this._updateFloat3ForUniform;
  31806. this.updateFloat4 = this._updateFloat4ForUniform;
  31807. this.updateMatrix = this._updateMatrixForUniform;
  31808. this.updateVector3 = this._updateVector3ForUniform;
  31809. this.updateVector4 = this._updateVector4ForUniform;
  31810. this.updateColor3 = this._updateColor3ForUniform;
  31811. this.updateColor4 = this._updateColor4ForUniform;
  31812. }
  31813. }
  31814. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31815. // Properties
  31816. /**
  31817. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31818. * or just falling back on setUniformXXX calls.
  31819. */
  31820. get: function () {
  31821. return !this._noUBO;
  31822. },
  31823. enumerable: true,
  31824. configurable: true
  31825. });
  31826. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31827. /**
  31828. * Indicates if the WebGL underlying uniform buffer is in sync
  31829. * with the javascript cache data.
  31830. */
  31831. get: function () {
  31832. return !this._needSync;
  31833. },
  31834. enumerable: true,
  31835. configurable: true
  31836. });
  31837. /**
  31838. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31839. * Also, a dynamic UniformBuffer will disable cache verification and always
  31840. * update the underlying WebGL uniform buffer to the GPU.
  31841. */
  31842. UniformBuffer.prototype.isDynamic = function () {
  31843. return this._dynamic !== undefined;
  31844. };
  31845. /**
  31846. * The data cache on JS side.
  31847. */
  31848. UniformBuffer.prototype.getData = function () {
  31849. return this._bufferData;
  31850. };
  31851. /**
  31852. * The underlying WebGL Uniform buffer.
  31853. */
  31854. UniformBuffer.prototype.getBuffer = function () {
  31855. return this._buffer;
  31856. };
  31857. /**
  31858. * std140 layout specifies how to align data within an UBO structure.
  31859. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31860. * for specs.
  31861. */
  31862. UniformBuffer.prototype._fillAlignment = function (size) {
  31863. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31864. // and 4x4 matrices
  31865. // TODO : change if other types are used
  31866. var alignment;
  31867. if (size <= 2) {
  31868. alignment = size;
  31869. }
  31870. else {
  31871. alignment = 4;
  31872. }
  31873. if ((this._uniformLocationPointer % alignment) !== 0) {
  31874. var oldPointer = this._uniformLocationPointer;
  31875. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31876. var diff = this._uniformLocationPointer - oldPointer;
  31877. for (var i = 0; i < diff; i++) {
  31878. this._data.push(0);
  31879. }
  31880. }
  31881. };
  31882. /**
  31883. * Adds an uniform in the buffer.
  31884. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31885. * for the layout to be correct !
  31886. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31887. * @param {number|number[]} size Data size, or data directly.
  31888. */
  31889. UniformBuffer.prototype.addUniform = function (name, size) {
  31890. if (this._noUBO) {
  31891. return;
  31892. }
  31893. if (this._uniformLocations[name] !== undefined) {
  31894. // Already existing uniform
  31895. return;
  31896. }
  31897. // This function must be called in the order of the shader layout !
  31898. // size can be the size of the uniform, or data directly
  31899. var data;
  31900. if (size instanceof Array) {
  31901. data = size;
  31902. size = data.length;
  31903. }
  31904. else {
  31905. size = size;
  31906. data = [];
  31907. // Fill with zeros
  31908. for (var i = 0; i < size; i++) {
  31909. data.push(0);
  31910. }
  31911. }
  31912. this._fillAlignment(size);
  31913. this._uniformSizes[name] = size;
  31914. this._uniformLocations[name] = this._uniformLocationPointer;
  31915. this._uniformLocationPointer += size;
  31916. for (var i = 0; i < size; i++) {
  31917. this._data.push(data[i]);
  31918. }
  31919. this._needSync = true;
  31920. };
  31921. /**
  31922. * Wrapper for addUniform.
  31923. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31924. * @param {Matrix} mat A 4x4 matrix.
  31925. */
  31926. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31927. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31928. };
  31929. /**
  31930. * Wrapper for addUniform.
  31931. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31932. * @param {number} x
  31933. * @param {number} y
  31934. */
  31935. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31936. var temp = [x, y];
  31937. this.addUniform(name, temp);
  31938. };
  31939. /**
  31940. * Wrapper for addUniform.
  31941. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31942. * @param {number} x
  31943. * @param {number} y
  31944. * @param {number} z
  31945. */
  31946. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31947. var temp = [x, y, z];
  31948. this.addUniform(name, temp);
  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 {Color3} color
  31954. */
  31955. UniformBuffer.prototype.addColor3 = function (name, color) {
  31956. var temp = new Array();
  31957. color.toArray(temp);
  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 {Color3} color
  31964. * @param {number} alpha
  31965. */
  31966. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31967. var temp = new Array();
  31968. color.toArray(temp);
  31969. temp.push(alpha);
  31970. this.addUniform(name, temp);
  31971. };
  31972. /**
  31973. * Wrapper for addUniform.
  31974. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31975. * @param {Vector3} vector
  31976. */
  31977. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31978. var temp = new Array();
  31979. vector.toArray(temp);
  31980. this.addUniform(name, temp);
  31981. };
  31982. /**
  31983. * Wrapper for addUniform.
  31984. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31985. */
  31986. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31987. this.addUniform(name, 12);
  31988. };
  31989. /**
  31990. * Wrapper for addUniform.
  31991. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31992. */
  31993. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31994. this.addUniform(name, 8);
  31995. };
  31996. /**
  31997. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31998. */
  31999. UniformBuffer.prototype.create = function () {
  32000. if (this._noUBO) {
  32001. return;
  32002. }
  32003. if (this._buffer) {
  32004. return; // nothing to do
  32005. }
  32006. // See spec, alignment must be filled as a vec4
  32007. this._fillAlignment(4);
  32008. this._bufferData = new Float32Array(this._data);
  32009. this._rebuild();
  32010. this._needSync = true;
  32011. };
  32012. UniformBuffer.prototype._rebuild = function () {
  32013. if (this._noUBO) {
  32014. return;
  32015. }
  32016. if (this._dynamic) {
  32017. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32018. }
  32019. else {
  32020. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32021. }
  32022. };
  32023. /**
  32024. * Updates the WebGL Uniform Buffer on the GPU.
  32025. * If the `dynamic` flag is set to true, no cache comparison is done.
  32026. * Otherwise, the buffer will be updated only if the cache differs.
  32027. */
  32028. UniformBuffer.prototype.update = function () {
  32029. if (!this._buffer) {
  32030. this.create();
  32031. return;
  32032. }
  32033. if (!this._dynamic && !this._needSync) {
  32034. return;
  32035. }
  32036. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32037. this._needSync = false;
  32038. };
  32039. /**
  32040. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32041. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32042. * @param {number[]|Float32Array} data Flattened data
  32043. * @param {number} size Size of the data.
  32044. */
  32045. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32046. var location = this._uniformLocations[uniformName];
  32047. if (location === undefined) {
  32048. if (this._buffer) {
  32049. // Cannot add an uniform if the buffer is already created
  32050. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32051. return;
  32052. }
  32053. this.addUniform(uniformName, size);
  32054. location = this._uniformLocations[uniformName];
  32055. }
  32056. if (!this._buffer) {
  32057. this.create();
  32058. }
  32059. if (!this._dynamic) {
  32060. // Cache for static uniform buffers
  32061. var changed = false;
  32062. for (var i = 0; i < size; i++) {
  32063. if (this._bufferData[location + i] !== data[i]) {
  32064. changed = true;
  32065. this._bufferData[location + i] = data[i];
  32066. }
  32067. }
  32068. this._needSync = this._needSync || changed;
  32069. }
  32070. else {
  32071. // No cache for dynamic
  32072. for (var i = 0; i < size; i++) {
  32073. this._bufferData[location + i] = data[i];
  32074. }
  32075. }
  32076. };
  32077. // Update methods
  32078. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32079. // To match std140, matrix must be realigned
  32080. for (var i = 0; i < 3; i++) {
  32081. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32082. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32083. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32084. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32085. }
  32086. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32087. };
  32088. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32089. this._currentEffect.setMatrix3x3(name, matrix);
  32090. };
  32091. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32092. this._currentEffect.setMatrix2x2(name, matrix);
  32093. };
  32094. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32095. // To match std140, matrix must be realigned
  32096. for (var i = 0; i < 2; i++) {
  32097. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32098. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32099. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32100. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32101. }
  32102. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32103. };
  32104. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32105. this._currentEffect.setFloat(name, x);
  32106. };
  32107. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32108. UniformBuffer._tempBuffer[0] = x;
  32109. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32110. };
  32111. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32112. if (suffix === void 0) { suffix = ""; }
  32113. this._currentEffect.setFloat2(name + suffix, x, y);
  32114. };
  32115. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32116. if (suffix === void 0) { suffix = ""; }
  32117. UniformBuffer._tempBuffer[0] = x;
  32118. UniformBuffer._tempBuffer[1] = y;
  32119. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32120. };
  32121. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32122. if (suffix === void 0) { suffix = ""; }
  32123. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32124. };
  32125. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32126. if (suffix === void 0) { suffix = ""; }
  32127. UniformBuffer._tempBuffer[0] = x;
  32128. UniformBuffer._tempBuffer[1] = y;
  32129. UniformBuffer._tempBuffer[2] = z;
  32130. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32131. };
  32132. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32133. if (suffix === void 0) { suffix = ""; }
  32134. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32135. };
  32136. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32137. if (suffix === void 0) { suffix = ""; }
  32138. UniformBuffer._tempBuffer[0] = x;
  32139. UniformBuffer._tempBuffer[1] = y;
  32140. UniformBuffer._tempBuffer[2] = z;
  32141. UniformBuffer._tempBuffer[3] = w;
  32142. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32143. };
  32144. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32145. this._currentEffect.setMatrix(name, mat);
  32146. };
  32147. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32148. this.updateUniform(name, mat.toArray(), 16);
  32149. };
  32150. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32151. this._currentEffect.setVector3(name, vector);
  32152. };
  32153. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32154. vector.toArray(UniformBuffer._tempBuffer);
  32155. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32156. };
  32157. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32158. this._currentEffect.setVector4(name, vector);
  32159. };
  32160. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32161. vector.toArray(UniformBuffer._tempBuffer);
  32162. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32163. };
  32164. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32165. if (suffix === void 0) { suffix = ""; }
  32166. this._currentEffect.setColor3(name + suffix, color);
  32167. };
  32168. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32169. if (suffix === void 0) { suffix = ""; }
  32170. color.toArray(UniformBuffer._tempBuffer);
  32171. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32172. };
  32173. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32174. if (suffix === void 0) { suffix = ""; }
  32175. this._currentEffect.setColor4(name + suffix, color, alpha);
  32176. };
  32177. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32178. if (suffix === void 0) { suffix = ""; }
  32179. color.toArray(UniformBuffer._tempBuffer);
  32180. UniformBuffer._tempBuffer[3] = alpha;
  32181. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32182. };
  32183. /**
  32184. * Sets a sampler uniform on the effect.
  32185. * @param {string} name Name of the sampler.
  32186. * @param {Texture} texture
  32187. */
  32188. UniformBuffer.prototype.setTexture = function (name, texture) {
  32189. this._currentEffect.setTexture(name, texture);
  32190. };
  32191. /**
  32192. * Directly updates the value of the uniform in the cache AND on the GPU.
  32193. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32194. * @param {number[]|Float32Array} data Flattened data
  32195. */
  32196. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32197. this.updateUniform(uniformName, data, data.length);
  32198. this.update();
  32199. };
  32200. /**
  32201. * Binds this uniform buffer to an effect.
  32202. * @param {Effect} effect
  32203. * @param {string} name Name of the uniform block in the shader.
  32204. */
  32205. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32206. this._currentEffect = effect;
  32207. if (this._noUBO || !this._buffer) {
  32208. return;
  32209. }
  32210. effect.bindUniformBuffer(this._buffer, name);
  32211. };
  32212. /**
  32213. * Disposes the uniform buffer.
  32214. */
  32215. UniformBuffer.prototype.dispose = function () {
  32216. if (this._noUBO) {
  32217. return;
  32218. }
  32219. var index = this._engine._uniformBuffers.indexOf(this);
  32220. if (index !== -1) {
  32221. this._engine._uniformBuffers.splice(index, 1);
  32222. }
  32223. if (!this._buffer) {
  32224. return;
  32225. }
  32226. if (this._engine._releaseBuffer(this._buffer)) {
  32227. this._buffer = null;
  32228. }
  32229. };
  32230. // Pool for avoiding memory leaks
  32231. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32232. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32233. return UniformBuffer;
  32234. }());
  32235. BABYLON.UniformBuffer = UniformBuffer;
  32236. })(BABYLON || (BABYLON = {}));
  32237. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32238. var BABYLON;
  32239. (function (BABYLON) {
  32240. var VertexData = /** @class */ (function () {
  32241. function VertexData() {
  32242. }
  32243. VertexData.prototype.set = function (data, kind) {
  32244. switch (kind) {
  32245. case BABYLON.VertexBuffer.PositionKind:
  32246. this.positions = data;
  32247. break;
  32248. case BABYLON.VertexBuffer.NormalKind:
  32249. this.normals = data;
  32250. break;
  32251. case BABYLON.VertexBuffer.TangentKind:
  32252. this.tangents = data;
  32253. break;
  32254. case BABYLON.VertexBuffer.UVKind:
  32255. this.uvs = data;
  32256. break;
  32257. case BABYLON.VertexBuffer.UV2Kind:
  32258. this.uvs2 = data;
  32259. break;
  32260. case BABYLON.VertexBuffer.UV3Kind:
  32261. this.uvs3 = data;
  32262. break;
  32263. case BABYLON.VertexBuffer.UV4Kind:
  32264. this.uvs4 = data;
  32265. break;
  32266. case BABYLON.VertexBuffer.UV5Kind:
  32267. this.uvs5 = data;
  32268. break;
  32269. case BABYLON.VertexBuffer.UV6Kind:
  32270. this.uvs6 = data;
  32271. break;
  32272. case BABYLON.VertexBuffer.ColorKind:
  32273. this.colors = data;
  32274. break;
  32275. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32276. this.matricesIndices = data;
  32277. break;
  32278. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32279. this.matricesWeights = data;
  32280. break;
  32281. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32282. this.matricesIndicesExtra = data;
  32283. break;
  32284. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32285. this.matricesWeightsExtra = data;
  32286. break;
  32287. }
  32288. };
  32289. /**
  32290. * Associates the vertexData to the passed Mesh.
  32291. * Sets it as updatable or not (default `false`).
  32292. * Returns the VertexData.
  32293. */
  32294. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32295. this._applyTo(mesh, updatable);
  32296. return this;
  32297. };
  32298. /**
  32299. * Associates the vertexData to the passed Geometry.
  32300. * Sets it as updatable or not (default `false`).
  32301. * Returns the VertexData.
  32302. */
  32303. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32304. this._applyTo(geometry, updatable);
  32305. return this;
  32306. };
  32307. /**
  32308. * Updates the associated mesh.
  32309. * Returns the VertexData.
  32310. */
  32311. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32312. this._update(mesh);
  32313. return this;
  32314. };
  32315. /**
  32316. * Updates the associated geometry.
  32317. * Returns the VertexData.
  32318. */
  32319. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32320. this._update(geometry);
  32321. return this;
  32322. };
  32323. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32324. if (updatable === void 0) { updatable = false; }
  32325. if (this.positions) {
  32326. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32327. }
  32328. if (this.normals) {
  32329. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32330. }
  32331. if (this.tangents) {
  32332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32333. }
  32334. if (this.uvs) {
  32335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32336. }
  32337. if (this.uvs2) {
  32338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32339. }
  32340. if (this.uvs3) {
  32341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32342. }
  32343. if (this.uvs4) {
  32344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32345. }
  32346. if (this.uvs5) {
  32347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32348. }
  32349. if (this.uvs6) {
  32350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32351. }
  32352. if (this.colors) {
  32353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32354. }
  32355. if (this.matricesIndices) {
  32356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32357. }
  32358. if (this.matricesWeights) {
  32359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32360. }
  32361. if (this.matricesIndicesExtra) {
  32362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32363. }
  32364. if (this.matricesWeightsExtra) {
  32365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32366. }
  32367. if (this.indices) {
  32368. meshOrGeometry.setIndices(this.indices, null, updatable);
  32369. }
  32370. return this;
  32371. };
  32372. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32373. if (this.positions) {
  32374. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32375. }
  32376. if (this.normals) {
  32377. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32378. }
  32379. if (this.tangents) {
  32380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32381. }
  32382. if (this.uvs) {
  32383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32384. }
  32385. if (this.uvs2) {
  32386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32387. }
  32388. if (this.uvs3) {
  32389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32390. }
  32391. if (this.uvs4) {
  32392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32393. }
  32394. if (this.uvs5) {
  32395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32396. }
  32397. if (this.uvs6) {
  32398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32399. }
  32400. if (this.colors) {
  32401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32402. }
  32403. if (this.matricesIndices) {
  32404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32405. }
  32406. if (this.matricesWeights) {
  32407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32408. }
  32409. if (this.matricesIndicesExtra) {
  32410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32411. }
  32412. if (this.matricesWeightsExtra) {
  32413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32414. }
  32415. if (this.indices) {
  32416. meshOrGeometry.setIndices(this.indices, null);
  32417. }
  32418. return this;
  32419. };
  32420. /**
  32421. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32422. * Returns the VertexData.
  32423. */
  32424. VertexData.prototype.transform = function (matrix) {
  32425. var transformed = BABYLON.Vector3.Zero();
  32426. var index;
  32427. if (this.positions) {
  32428. var position = BABYLON.Vector3.Zero();
  32429. for (index = 0; index < this.positions.length; index += 3) {
  32430. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32431. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32432. this.positions[index] = transformed.x;
  32433. this.positions[index + 1] = transformed.y;
  32434. this.positions[index + 2] = transformed.z;
  32435. }
  32436. }
  32437. if (this.normals) {
  32438. var normal = BABYLON.Vector3.Zero();
  32439. for (index = 0; index < this.normals.length; index += 3) {
  32440. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32441. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32442. this.normals[index] = transformed.x;
  32443. this.normals[index + 1] = transformed.y;
  32444. this.normals[index + 2] = transformed.z;
  32445. }
  32446. }
  32447. if (this.tangents) {
  32448. var tangent = BABYLON.Vector4.Zero();
  32449. var tangentTransformed = BABYLON.Vector4.Zero();
  32450. for (index = 0; index < this.tangents.length; index += 4) {
  32451. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32452. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32453. this.tangents[index] = tangentTransformed.x;
  32454. this.tangents[index + 1] = tangentTransformed.y;
  32455. this.tangents[index + 2] = tangentTransformed.z;
  32456. this.tangents[index + 3] = tangentTransformed.w;
  32457. }
  32458. }
  32459. return this;
  32460. };
  32461. /**
  32462. * Merges the passed VertexData into the current one.
  32463. * Returns the modified VertexData.
  32464. */
  32465. VertexData.prototype.merge = function (other) {
  32466. this._validate();
  32467. other._validate();
  32468. if (!this.normals !== !other.normals ||
  32469. !this.tangents !== !other.tangents ||
  32470. !this.uvs !== !other.uvs ||
  32471. !this.uvs2 !== !other.uvs2 ||
  32472. !this.uvs3 !== !other.uvs3 ||
  32473. !this.uvs4 !== !other.uvs4 ||
  32474. !this.uvs5 !== !other.uvs5 ||
  32475. !this.uvs6 !== !other.uvs6 ||
  32476. !this.colors !== !other.colors ||
  32477. !this.matricesIndices !== !other.matricesIndices ||
  32478. !this.matricesWeights !== !other.matricesWeights ||
  32479. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32480. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32481. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32482. }
  32483. if (other.indices) {
  32484. if (!this.indices) {
  32485. this.indices = [];
  32486. }
  32487. var offset = this.positions ? this.positions.length / 3 : 0;
  32488. for (var index = 0; index < other.indices.length; index++) {
  32489. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32490. this.indices.push(other.indices[index] + offset);
  32491. }
  32492. }
  32493. this.positions = this._mergeElement(this.positions, other.positions);
  32494. this.normals = this._mergeElement(this.normals, other.normals);
  32495. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32496. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32497. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32498. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32499. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32500. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32501. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32502. this.colors = this._mergeElement(this.colors, other.colors);
  32503. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32504. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32505. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32506. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32507. return this;
  32508. };
  32509. VertexData.prototype._mergeElement = function (source, other) {
  32510. if (!source) {
  32511. return other;
  32512. }
  32513. if (!other) {
  32514. return source;
  32515. }
  32516. var len = other.length + source.length;
  32517. var isSrcTypedArray = source instanceof Float32Array;
  32518. var isOthTypedArray = other instanceof Float32Array;
  32519. // use non-loop method when the source is Float32Array
  32520. if (isSrcTypedArray) {
  32521. var ret32 = new Float32Array(len);
  32522. ret32.set(source);
  32523. ret32.set(other, source.length);
  32524. return ret32;
  32525. // source is number[], when other is also use concat
  32526. }
  32527. else if (!isOthTypedArray) {
  32528. return source.concat(other);
  32529. // source is a number[], but other is a Float32Array, loop required
  32530. }
  32531. else {
  32532. var ret = source.slice(0); // copy source to a separate array
  32533. for (var i = 0, len = other.length; i < len; i++) {
  32534. ret.push(other[i]);
  32535. }
  32536. return ret;
  32537. }
  32538. };
  32539. VertexData.prototype._validate = function () {
  32540. if (!this.positions) {
  32541. throw new Error("Positions are required");
  32542. }
  32543. var getElementCount = function (kind, values) {
  32544. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32545. if ((values.length % stride) !== 0) {
  32546. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32547. }
  32548. return values.length / stride;
  32549. };
  32550. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32551. var validateElementCount = function (kind, values) {
  32552. var elementCount = getElementCount(kind, values);
  32553. if (elementCount !== positionsElementCount) {
  32554. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32555. }
  32556. };
  32557. if (this.normals)
  32558. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32559. if (this.tangents)
  32560. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32561. if (this.uvs)
  32562. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32563. if (this.uvs2)
  32564. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32565. if (this.uvs3)
  32566. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32567. if (this.uvs4)
  32568. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32569. if (this.uvs5)
  32570. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32571. if (this.uvs6)
  32572. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32573. if (this.colors)
  32574. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32575. if (this.matricesIndices)
  32576. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32577. if (this.matricesWeights)
  32578. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32579. if (this.matricesIndicesExtra)
  32580. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32581. if (this.matricesWeightsExtra)
  32582. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32583. };
  32584. /**
  32585. * Serializes the VertexData.
  32586. * Returns a serialized object.
  32587. */
  32588. VertexData.prototype.serialize = function () {
  32589. var serializationObject = this.serialize();
  32590. if (this.positions) {
  32591. serializationObject.positions = this.positions;
  32592. }
  32593. if (this.normals) {
  32594. serializationObject.normals = this.normals;
  32595. }
  32596. if (this.tangents) {
  32597. serializationObject.tangents = this.tangents;
  32598. }
  32599. if (this.uvs) {
  32600. serializationObject.uvs = this.uvs;
  32601. }
  32602. if (this.uvs2) {
  32603. serializationObject.uvs2 = this.uvs2;
  32604. }
  32605. if (this.uvs3) {
  32606. serializationObject.uvs3 = this.uvs3;
  32607. }
  32608. if (this.uvs4) {
  32609. serializationObject.uvs4 = this.uvs4;
  32610. }
  32611. if (this.uvs5) {
  32612. serializationObject.uvs5 = this.uvs5;
  32613. }
  32614. if (this.uvs6) {
  32615. serializationObject.uvs6 = this.uvs6;
  32616. }
  32617. if (this.colors) {
  32618. serializationObject.colors = this.colors;
  32619. }
  32620. if (this.matricesIndices) {
  32621. serializationObject.matricesIndices = this.matricesIndices;
  32622. serializationObject.matricesIndices._isExpanded = true;
  32623. }
  32624. if (this.matricesWeights) {
  32625. serializationObject.matricesWeights = this.matricesWeights;
  32626. }
  32627. if (this.matricesIndicesExtra) {
  32628. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32629. serializationObject.matricesIndicesExtra._isExpanded = true;
  32630. }
  32631. if (this.matricesWeightsExtra) {
  32632. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32633. }
  32634. serializationObject.indices = this.indices;
  32635. return serializationObject;
  32636. };
  32637. // Statics
  32638. /**
  32639. * Returns the object VertexData associated to the passed mesh.
  32640. */
  32641. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32642. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32643. };
  32644. /**
  32645. * Returns the object VertexData associated to the passed geometry.
  32646. */
  32647. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32648. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32649. };
  32650. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32651. var result = new VertexData();
  32652. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32653. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32654. }
  32655. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32656. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32657. }
  32658. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32659. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32660. }
  32661. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32662. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32663. }
  32664. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32665. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32666. }
  32667. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32668. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32669. }
  32670. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32671. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32672. }
  32673. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32674. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32675. }
  32676. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32677. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32678. }
  32679. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32680. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32681. }
  32682. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32683. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32684. }
  32685. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32686. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32687. }
  32688. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32689. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32690. }
  32691. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32692. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32693. }
  32694. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32695. return result;
  32696. };
  32697. /**
  32698. * Creates the vertexData of the Ribbon.
  32699. */
  32700. VertexData.CreateRibbon = function (options) {
  32701. var pathArray = options.pathArray;
  32702. var closeArray = options.closeArray || false;
  32703. var closePath = options.closePath || false;
  32704. var invertUV = options.invertUV || false;
  32705. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32706. var offset = options.offset || defaultOffset;
  32707. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32709. var customUV = options.uvs;
  32710. var customColors = options.colors;
  32711. var positions = [];
  32712. var indices = [];
  32713. var normals = [];
  32714. var uvs = [];
  32715. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32716. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32717. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32718. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32719. var minlg; // minimal length among all paths from pathArray
  32720. var lg = []; // array of path lengths : nb of vertex per path
  32721. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32722. var p; // path iterator
  32723. var i; // point iterator
  32724. var j; // point iterator
  32725. // if single path in pathArray
  32726. if (pathArray.length < 2) {
  32727. var ar1 = [];
  32728. var ar2 = [];
  32729. for (i = 0; i < pathArray[0].length - offset; i++) {
  32730. ar1.push(pathArray[0][i]);
  32731. ar2.push(pathArray[0][i + offset]);
  32732. }
  32733. pathArray = [ar1, ar2];
  32734. }
  32735. // positions and horizontal distances (u)
  32736. var idc = 0;
  32737. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32738. var path;
  32739. var l;
  32740. minlg = pathArray[0].length;
  32741. var vectlg;
  32742. var dist;
  32743. for (p = 0; p < pathArray.length; p++) {
  32744. uTotalDistance[p] = 0;
  32745. us[p] = [0];
  32746. path = pathArray[p];
  32747. l = path.length;
  32748. minlg = (minlg < l) ? minlg : l;
  32749. j = 0;
  32750. while (j < l) {
  32751. positions.push(path[j].x, path[j].y, path[j].z);
  32752. if (j > 0) {
  32753. vectlg = path[j].subtract(path[j - 1]).length();
  32754. dist = vectlg + uTotalDistance[p];
  32755. us[p].push(dist);
  32756. uTotalDistance[p] = dist;
  32757. }
  32758. j++;
  32759. }
  32760. if (closePath) {
  32761. j--;
  32762. positions.push(path[0].x, path[0].y, path[0].z);
  32763. vectlg = path[j].subtract(path[0]).length();
  32764. dist = vectlg + uTotalDistance[p];
  32765. us[p].push(dist);
  32766. uTotalDistance[p] = dist;
  32767. }
  32768. lg[p] = l + closePathCorr;
  32769. idx[p] = idc;
  32770. idc += (l + closePathCorr);
  32771. }
  32772. // vertical distances (v)
  32773. var path1;
  32774. var path2;
  32775. var vertex1 = null;
  32776. var vertex2 = null;
  32777. for (i = 0; i < minlg + closePathCorr; i++) {
  32778. vTotalDistance[i] = 0;
  32779. vs[i] = [0];
  32780. for (p = 0; p < pathArray.length - 1; p++) {
  32781. path1 = pathArray[p];
  32782. path2 = pathArray[p + 1];
  32783. if (i === minlg) {
  32784. vertex1 = path1[0];
  32785. vertex2 = path2[0];
  32786. }
  32787. else {
  32788. vertex1 = path1[i];
  32789. vertex2 = path2[i];
  32790. }
  32791. vectlg = vertex2.subtract(vertex1).length();
  32792. dist = vectlg + vTotalDistance[i];
  32793. vs[i].push(dist);
  32794. vTotalDistance[i] = dist;
  32795. }
  32796. if (closeArray && vertex2 && vertex1) {
  32797. path1 = pathArray[p];
  32798. path2 = pathArray[0];
  32799. if (i === minlg) {
  32800. vertex2 = path2[0];
  32801. }
  32802. vectlg = vertex2.subtract(vertex1).length();
  32803. dist = vectlg + vTotalDistance[i];
  32804. vTotalDistance[i] = dist;
  32805. }
  32806. }
  32807. // uvs
  32808. var u;
  32809. var v;
  32810. if (customUV) {
  32811. for (p = 0; p < customUV.length; p++) {
  32812. uvs.push(customUV[p].x, customUV[p].y);
  32813. }
  32814. }
  32815. else {
  32816. for (p = 0; p < pathArray.length; p++) {
  32817. for (i = 0; i < minlg + closePathCorr; i++) {
  32818. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32819. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32820. if (invertUV) {
  32821. uvs.push(v, u);
  32822. }
  32823. else {
  32824. uvs.push(u, v);
  32825. }
  32826. }
  32827. }
  32828. }
  32829. // indices
  32830. p = 0; // path index
  32831. var pi = 0; // positions array index
  32832. var l1 = lg[p] - 1; // path1 length
  32833. var l2 = lg[p + 1] - 1; // path2 length
  32834. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32835. var shft = idx[1] - idx[0]; // shift
  32836. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32837. while (pi <= min && p < path1nb) {
  32838. // 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
  32839. indices.push(pi, pi + shft, pi + 1);
  32840. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32841. pi += 1;
  32842. if (pi === min) {
  32843. p++;
  32844. if (p === lg.length - 1) {
  32845. shft = idx[0] - idx[p];
  32846. l1 = lg[p] - 1;
  32847. l2 = lg[0] - 1;
  32848. }
  32849. else {
  32850. shft = idx[p + 1] - idx[p];
  32851. l1 = lg[p] - 1;
  32852. l2 = lg[p + 1] - 1;
  32853. }
  32854. pi = idx[p];
  32855. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32856. }
  32857. }
  32858. // normals
  32859. VertexData.ComputeNormals(positions, indices, normals);
  32860. if (closePath) {
  32861. var indexFirst = 0;
  32862. var indexLast = 0;
  32863. for (p = 0; p < pathArray.length; p++) {
  32864. indexFirst = idx[p] * 3;
  32865. if (p + 1 < pathArray.length) {
  32866. indexLast = (idx[p + 1] - 1) * 3;
  32867. }
  32868. else {
  32869. indexLast = normals.length - 3;
  32870. }
  32871. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32872. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32873. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32874. normals[indexLast] = normals[indexFirst];
  32875. normals[indexLast + 1] = normals[indexFirst + 1];
  32876. normals[indexLast + 2] = normals[indexFirst + 2];
  32877. }
  32878. }
  32879. // sides
  32880. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32881. // Colors
  32882. var colors = null;
  32883. if (customColors) {
  32884. colors = new Float32Array(customColors.length * 4);
  32885. for (var c = 0; c < customColors.length; c++) {
  32886. colors[c * 4] = customColors[c].r;
  32887. colors[c * 4 + 1] = customColors[c].g;
  32888. colors[c * 4 + 2] = customColors[c].b;
  32889. colors[c * 4 + 3] = customColors[c].a;
  32890. }
  32891. }
  32892. // Result
  32893. var vertexData = new VertexData();
  32894. var positions32 = new Float32Array(positions);
  32895. var normals32 = new Float32Array(normals);
  32896. var uvs32 = new Float32Array(uvs);
  32897. vertexData.indices = indices;
  32898. vertexData.positions = positions32;
  32899. vertexData.normals = normals32;
  32900. vertexData.uvs = uvs32;
  32901. if (colors) {
  32902. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32903. }
  32904. if (closePath) {
  32905. vertexData._idx = idx;
  32906. }
  32907. return vertexData;
  32908. };
  32909. /**
  32910. * Creates the VertexData of the Box.
  32911. */
  32912. VertexData.CreateBox = function (options) {
  32913. var normalsSource = [
  32914. new BABYLON.Vector3(0, 0, 1),
  32915. new BABYLON.Vector3(0, 0, -1),
  32916. new BABYLON.Vector3(1, 0, 0),
  32917. new BABYLON.Vector3(-1, 0, 0),
  32918. new BABYLON.Vector3(0, 1, 0),
  32919. new BABYLON.Vector3(0, -1, 0)
  32920. ];
  32921. var indices = [];
  32922. var positions = [];
  32923. var normals = [];
  32924. var uvs = [];
  32925. var width = options.width || options.size || 1;
  32926. var height = options.height || options.size || 1;
  32927. var depth = options.depth || options.size || 1;
  32928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32929. var faceUV = options.faceUV || new Array(6);
  32930. var faceColors = options.faceColors;
  32931. var colors = [];
  32932. // default face colors and UV if undefined
  32933. for (var f = 0; f < 6; f++) {
  32934. if (faceUV[f] === undefined) {
  32935. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32936. }
  32937. if (faceColors && faceColors[f] === undefined) {
  32938. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32939. }
  32940. }
  32941. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32942. // Create each face in turn.
  32943. for (var index = 0; index < normalsSource.length; index++) {
  32944. var normal = normalsSource[index];
  32945. // Get two vectors perpendicular to the face normal and to each other.
  32946. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32947. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32948. // Six indices (two triangles) per face.
  32949. var verticesLength = positions.length / 3;
  32950. indices.push(verticesLength);
  32951. indices.push(verticesLength + 1);
  32952. indices.push(verticesLength + 2);
  32953. indices.push(verticesLength);
  32954. indices.push(verticesLength + 2);
  32955. indices.push(verticesLength + 3);
  32956. // Four vertices per face.
  32957. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32958. positions.push(vertex.x, vertex.y, vertex.z);
  32959. normals.push(normal.x, normal.y, normal.z);
  32960. uvs.push(faceUV[index].z, faceUV[index].w);
  32961. if (faceColors) {
  32962. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32963. }
  32964. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32965. positions.push(vertex.x, vertex.y, vertex.z);
  32966. normals.push(normal.x, normal.y, normal.z);
  32967. uvs.push(faceUV[index].x, faceUV[index].w);
  32968. if (faceColors) {
  32969. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32970. }
  32971. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32972. positions.push(vertex.x, vertex.y, vertex.z);
  32973. normals.push(normal.x, normal.y, normal.z);
  32974. uvs.push(faceUV[index].x, faceUV[index].y);
  32975. if (faceColors) {
  32976. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32977. }
  32978. vertex = normal.add(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].y);
  32982. if (faceColors) {
  32983. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32984. }
  32985. }
  32986. // sides
  32987. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32988. // Result
  32989. var vertexData = new VertexData();
  32990. vertexData.indices = indices;
  32991. vertexData.positions = positions;
  32992. vertexData.normals = normals;
  32993. vertexData.uvs = uvs;
  32994. if (faceColors) {
  32995. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32996. vertexData.colors = totalColors;
  32997. }
  32998. return vertexData;
  32999. };
  33000. /**
  33001. * Creates the VertexData of the Sphere.
  33002. */
  33003. VertexData.CreateSphere = function (options) {
  33004. var segments = options.segments || 32;
  33005. var diameterX = options.diameterX || options.diameter || 1;
  33006. var diameterY = options.diameterY || options.diameter || 1;
  33007. var diameterZ = options.diameterZ || options.diameter || 1;
  33008. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33009. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33010. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33011. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33012. var totalZRotationSteps = 2 + segments;
  33013. var totalYRotationSteps = 2 * totalZRotationSteps;
  33014. var indices = [];
  33015. var positions = [];
  33016. var normals = [];
  33017. var uvs = [];
  33018. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33019. var normalizedZ = zRotationStep / totalZRotationSteps;
  33020. var angleZ = normalizedZ * Math.PI * slice;
  33021. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33022. var normalizedY = yRotationStep / totalYRotationSteps;
  33023. var angleY = normalizedY * Math.PI * 2 * arc;
  33024. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33025. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33026. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33027. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33028. var vertex = complete.multiply(radius);
  33029. var normal = complete.divide(radius).normalize();
  33030. positions.push(vertex.x, vertex.y, vertex.z);
  33031. normals.push(normal.x, normal.y, normal.z);
  33032. uvs.push(normalizedY, normalizedZ);
  33033. }
  33034. if (zRotationStep > 0) {
  33035. var verticesCount = positions.length / 3;
  33036. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33037. indices.push((firstIndex));
  33038. indices.push((firstIndex + 1));
  33039. indices.push(firstIndex + totalYRotationSteps + 1);
  33040. indices.push((firstIndex + totalYRotationSteps + 1));
  33041. indices.push((firstIndex + 1));
  33042. indices.push((firstIndex + totalYRotationSteps + 2));
  33043. }
  33044. }
  33045. }
  33046. // Sides
  33047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33048. // Result
  33049. var vertexData = new VertexData();
  33050. vertexData.indices = indices;
  33051. vertexData.positions = positions;
  33052. vertexData.normals = normals;
  33053. vertexData.uvs = uvs;
  33054. return vertexData;
  33055. };
  33056. /**
  33057. * Creates the VertexData of the Cylinder or Cone.
  33058. */
  33059. VertexData.CreateCylinder = function (options) {
  33060. var height = options.height || 2;
  33061. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33062. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33063. var tessellation = options.tessellation || 24;
  33064. var subdivisions = options.subdivisions || 1;
  33065. var hasRings = options.hasRings ? true : false;
  33066. var enclose = options.enclose ? true : false;
  33067. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33068. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33069. var faceUV = options.faceUV || new Array(3);
  33070. var faceColors = options.faceColors;
  33071. // default face colors and UV if undefined
  33072. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33073. var ringNb = (hasRings) ? subdivisions : 1;
  33074. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33075. var f;
  33076. for (f = 0; f < surfaceNb; f++) {
  33077. if (faceColors && faceColors[f] === undefined) {
  33078. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33079. }
  33080. }
  33081. for (f = 0; f < surfaceNb; f++) {
  33082. if (faceUV && faceUV[f] === undefined) {
  33083. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33084. }
  33085. }
  33086. var indices = new Array();
  33087. var positions = new Array();
  33088. var normals = new Array();
  33089. var uvs = new Array();
  33090. var colors = new Array();
  33091. var angle_step = Math.PI * 2 * arc / tessellation;
  33092. var angle;
  33093. var h;
  33094. var radius;
  33095. var tan = (diameterBottom - diameterTop) / 2 / height;
  33096. var ringVertex = BABYLON.Vector3.Zero();
  33097. var ringNormal = BABYLON.Vector3.Zero();
  33098. var ringFirstVertex = BABYLON.Vector3.Zero();
  33099. var ringFirstNormal = BABYLON.Vector3.Zero();
  33100. var quadNormal = BABYLON.Vector3.Zero();
  33101. var Y = BABYLON.Axis.Y;
  33102. // positions, normals, uvs
  33103. var i;
  33104. var j;
  33105. var r;
  33106. var ringIdx = 1;
  33107. var s = 1; // surface index
  33108. var cs = 0;
  33109. var v = 0;
  33110. for (i = 0; i <= subdivisions; i++) {
  33111. h = i / subdivisions;
  33112. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33113. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33114. for (r = 0; r < ringIdx; r++) {
  33115. if (hasRings) {
  33116. s += r;
  33117. }
  33118. if (enclose) {
  33119. s += 2 * r;
  33120. }
  33121. for (j = 0; j <= tessellation; j++) {
  33122. angle = j * angle_step;
  33123. // position
  33124. ringVertex.x = Math.cos(-angle) * radius;
  33125. ringVertex.y = -height / 2 + h * height;
  33126. ringVertex.z = Math.sin(-angle) * radius;
  33127. // normal
  33128. if (diameterTop === 0 && i === subdivisions) {
  33129. // if no top cap, reuse former normals
  33130. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33131. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33132. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33133. }
  33134. else {
  33135. ringNormal.x = ringVertex.x;
  33136. ringNormal.z = ringVertex.z;
  33137. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33138. ringNormal.normalize();
  33139. }
  33140. // keep first ring vertex values for enclose
  33141. if (j === 0) {
  33142. ringFirstVertex.copyFrom(ringVertex);
  33143. ringFirstNormal.copyFrom(ringNormal);
  33144. }
  33145. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33146. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33147. if (hasRings) {
  33148. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33149. }
  33150. else {
  33151. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33152. }
  33153. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33154. if (faceColors) {
  33155. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33156. }
  33157. }
  33158. // if enclose, add four vertices and their dedicated normals
  33159. if (arc !== 1 && enclose) {
  33160. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33161. positions.push(0, ringVertex.y, 0);
  33162. positions.push(0, ringVertex.y, 0);
  33163. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33164. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33165. quadNormal.normalize();
  33166. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33167. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33168. quadNormal.normalize();
  33169. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33170. if (hasRings) {
  33171. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33172. }
  33173. else {
  33174. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33175. }
  33176. uvs.push(faceUV[s + 1].x, v);
  33177. uvs.push(faceUV[s + 1].z, v);
  33178. if (hasRings) {
  33179. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33180. }
  33181. else {
  33182. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33183. }
  33184. uvs.push(faceUV[s + 2].x, v);
  33185. uvs.push(faceUV[s + 2].z, v);
  33186. if (faceColors) {
  33187. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33188. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33189. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33190. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33191. }
  33192. }
  33193. if (cs !== s) {
  33194. cs = s;
  33195. }
  33196. }
  33197. }
  33198. // indices
  33199. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33200. var s;
  33201. i = 0;
  33202. for (s = 0; s < subdivisions; s++) {
  33203. var i0 = 0;
  33204. var i1 = 0;
  33205. var i2 = 0;
  33206. var i3 = 0;
  33207. for (j = 0; j < tessellation; j++) {
  33208. i0 = i * (e + 1) + j;
  33209. i1 = (i + 1) * (e + 1) + j;
  33210. i2 = i * (e + 1) + (j + 1);
  33211. i3 = (i + 1) * (e + 1) + (j + 1);
  33212. indices.push(i0, i1, i2);
  33213. indices.push(i3, i2, i1);
  33214. }
  33215. if (arc !== 1 && enclose) {
  33216. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33217. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33218. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33219. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33220. }
  33221. i = (hasRings) ? (i + 2) : (i + 1);
  33222. }
  33223. // Caps
  33224. var createCylinderCap = function (isTop) {
  33225. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33226. if (radius === 0) {
  33227. return;
  33228. }
  33229. // Cap positions, normals & uvs
  33230. var angle;
  33231. var circleVector;
  33232. var i;
  33233. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33234. var c = null;
  33235. if (faceColors) {
  33236. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33237. }
  33238. // cap center
  33239. var vbase = positions.length / 3;
  33240. var offset = isTop ? height / 2 : -height / 2;
  33241. var center = new BABYLON.Vector3(0, offset, 0);
  33242. positions.push(center.x, center.y, center.z);
  33243. normals.push(0, isTop ? 1 : -1, 0);
  33244. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33245. if (c) {
  33246. colors.push(c.r, c.g, c.b, c.a);
  33247. }
  33248. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33249. for (i = 0; i <= tessellation; i++) {
  33250. angle = Math.PI * 2 * i * arc / tessellation;
  33251. var cos = Math.cos(-angle);
  33252. var sin = Math.sin(-angle);
  33253. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33254. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33255. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33256. normals.push(0, isTop ? 1 : -1, 0);
  33257. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33258. if (c) {
  33259. colors.push(c.r, c.g, c.b, c.a);
  33260. }
  33261. }
  33262. // Cap indices
  33263. for (i = 0; i < tessellation; i++) {
  33264. if (!isTop) {
  33265. indices.push(vbase);
  33266. indices.push(vbase + (i + 1));
  33267. indices.push(vbase + (i + 2));
  33268. }
  33269. else {
  33270. indices.push(vbase);
  33271. indices.push(vbase + (i + 2));
  33272. indices.push(vbase + (i + 1));
  33273. }
  33274. }
  33275. };
  33276. // add caps to geometry
  33277. createCylinderCap(false);
  33278. createCylinderCap(true);
  33279. // Sides
  33280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33281. var vertexData = new VertexData();
  33282. vertexData.indices = indices;
  33283. vertexData.positions = positions;
  33284. vertexData.normals = normals;
  33285. vertexData.uvs = uvs;
  33286. if (faceColors) {
  33287. vertexData.colors = colors;
  33288. }
  33289. return vertexData;
  33290. };
  33291. /**
  33292. * Creates the VertexData of the Torus.
  33293. */
  33294. VertexData.CreateTorus = function (options) {
  33295. var indices = [];
  33296. var positions = [];
  33297. var normals = [];
  33298. var uvs = [];
  33299. var diameter = options.diameter || 1;
  33300. var thickness = options.thickness || 0.5;
  33301. var tessellation = options.tessellation || 16;
  33302. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33303. var stride = tessellation + 1;
  33304. for (var i = 0; i <= tessellation; i++) {
  33305. var u = i / tessellation;
  33306. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33307. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33308. for (var j = 0; j <= tessellation; j++) {
  33309. var v = 1 - j / tessellation;
  33310. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33311. var dx = Math.cos(innerAngle);
  33312. var dy = Math.sin(innerAngle);
  33313. // Create a vertex.
  33314. var normal = new BABYLON.Vector3(dx, dy, 0);
  33315. var position = normal.scale(thickness / 2);
  33316. var textureCoordinate = new BABYLON.Vector2(u, v);
  33317. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33318. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33319. positions.push(position.x, position.y, position.z);
  33320. normals.push(normal.x, normal.y, normal.z);
  33321. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33322. // And create indices for two triangles.
  33323. var nextI = (i + 1) % stride;
  33324. var nextJ = (j + 1) % stride;
  33325. indices.push(i * stride + j);
  33326. indices.push(i * stride + nextJ);
  33327. indices.push(nextI * stride + j);
  33328. indices.push(i * stride + nextJ);
  33329. indices.push(nextI * stride + nextJ);
  33330. indices.push(nextI * stride + j);
  33331. }
  33332. }
  33333. // Sides
  33334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33335. // Result
  33336. var vertexData = new VertexData();
  33337. vertexData.indices = indices;
  33338. vertexData.positions = positions;
  33339. vertexData.normals = normals;
  33340. vertexData.uvs = uvs;
  33341. return vertexData;
  33342. };
  33343. /**
  33344. * Creates the VertexData of the LineSystem.
  33345. */
  33346. VertexData.CreateLineSystem = function (options) {
  33347. var indices = [];
  33348. var positions = [];
  33349. var lines = options.lines;
  33350. var colors = options.colors;
  33351. var vertexColors = [];
  33352. var idx = 0;
  33353. for (var l = 0; l < lines.length; l++) {
  33354. var points = lines[l];
  33355. for (var index = 0; index < points.length; index++) {
  33356. positions.push(points[index].x, points[index].y, points[index].z);
  33357. if (colors) {
  33358. var color = colors[l];
  33359. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33360. }
  33361. if (index > 0) {
  33362. indices.push(idx - 1);
  33363. indices.push(idx);
  33364. }
  33365. idx++;
  33366. }
  33367. }
  33368. var vertexData = new VertexData();
  33369. vertexData.indices = indices;
  33370. vertexData.positions = positions;
  33371. if (colors) {
  33372. vertexData.colors = vertexColors;
  33373. }
  33374. return vertexData;
  33375. };
  33376. /**
  33377. * Create the VertexData of the DashedLines.
  33378. */
  33379. VertexData.CreateDashedLines = function (options) {
  33380. var dashSize = options.dashSize || 3;
  33381. var gapSize = options.gapSize || 1;
  33382. var dashNb = options.dashNb || 200;
  33383. var points = options.points;
  33384. var positions = new Array();
  33385. var indices = new Array();
  33386. var curvect = BABYLON.Vector3.Zero();
  33387. var lg = 0;
  33388. var nb = 0;
  33389. var shft = 0;
  33390. var dashshft = 0;
  33391. var curshft = 0;
  33392. var idx = 0;
  33393. var i = 0;
  33394. for (i = 0; i < points.length - 1; i++) {
  33395. points[i + 1].subtractToRef(points[i], curvect);
  33396. lg += curvect.length();
  33397. }
  33398. shft = lg / dashNb;
  33399. dashshft = dashSize * shft / (dashSize + gapSize);
  33400. for (i = 0; i < points.length - 1; i++) {
  33401. points[i + 1].subtractToRef(points[i], curvect);
  33402. nb = Math.floor(curvect.length() / shft);
  33403. curvect.normalize();
  33404. for (var j = 0; j < nb; j++) {
  33405. curshft = shft * j;
  33406. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33407. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33408. indices.push(idx, idx + 1);
  33409. idx += 2;
  33410. }
  33411. }
  33412. // Result
  33413. var vertexData = new VertexData();
  33414. vertexData.positions = positions;
  33415. vertexData.indices = indices;
  33416. return vertexData;
  33417. };
  33418. /**
  33419. * Creates the VertexData of the Ground.
  33420. */
  33421. VertexData.CreateGround = function (options) {
  33422. var indices = [];
  33423. var positions = [];
  33424. var normals = [];
  33425. var uvs = [];
  33426. var row, col;
  33427. var width = options.width || 1;
  33428. var height = options.height || 1;
  33429. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33430. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33431. for (row = 0; row <= subdivisionsY; row++) {
  33432. for (col = 0; col <= subdivisionsX; col++) {
  33433. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33434. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33435. positions.push(position.x, position.y, position.z);
  33436. normals.push(normal.x, normal.y, normal.z);
  33437. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33438. }
  33439. }
  33440. for (row = 0; row < subdivisionsY; row++) {
  33441. for (col = 0; col < subdivisionsX; col++) {
  33442. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33443. indices.push(col + 1 + row * (subdivisionsX + 1));
  33444. indices.push(col + row * (subdivisionsX + 1));
  33445. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33446. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33447. indices.push(col + row * (subdivisionsX + 1));
  33448. }
  33449. }
  33450. // Result
  33451. var vertexData = new VertexData();
  33452. vertexData.indices = indices;
  33453. vertexData.positions = positions;
  33454. vertexData.normals = normals;
  33455. vertexData.uvs = uvs;
  33456. return vertexData;
  33457. };
  33458. /**
  33459. * Creates the VertexData of the TiledGround.
  33460. */
  33461. VertexData.CreateTiledGround = function (options) {
  33462. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33463. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33464. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33465. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33466. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33467. var precision = options.precision || { w: 1, h: 1 };
  33468. var indices = new Array();
  33469. var positions = new Array();
  33470. var normals = new Array();
  33471. var uvs = new Array();
  33472. var row, col, tileRow, tileCol;
  33473. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33474. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33475. precision.w = (precision.w < 1) ? 1 : precision.w;
  33476. precision.h = (precision.h < 1) ? 1 : precision.h;
  33477. var tileSize = {
  33478. 'w': (xmax - xmin) / subdivisions.w,
  33479. 'h': (zmax - zmin) / subdivisions.h
  33480. };
  33481. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33482. // Indices
  33483. var base = positions.length / 3;
  33484. var rowLength = precision.w + 1;
  33485. for (row = 0; row < precision.h; row++) {
  33486. for (col = 0; col < precision.w; col++) {
  33487. var square = [
  33488. base + col + row * rowLength,
  33489. base + (col + 1) + row * rowLength,
  33490. base + (col + 1) + (row + 1) * rowLength,
  33491. base + col + (row + 1) * rowLength
  33492. ];
  33493. indices.push(square[1]);
  33494. indices.push(square[2]);
  33495. indices.push(square[3]);
  33496. indices.push(square[0]);
  33497. indices.push(square[1]);
  33498. indices.push(square[3]);
  33499. }
  33500. }
  33501. // Position, normals and uvs
  33502. var position = BABYLON.Vector3.Zero();
  33503. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33504. for (row = 0; row <= precision.h; row++) {
  33505. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33506. for (col = 0; col <= precision.w; col++) {
  33507. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33508. position.y = 0;
  33509. positions.push(position.x, position.y, position.z);
  33510. normals.push(normal.x, normal.y, normal.z);
  33511. uvs.push(col / precision.w, row / precision.h);
  33512. }
  33513. }
  33514. }
  33515. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33516. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33517. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33518. }
  33519. }
  33520. // Result
  33521. var vertexData = new VertexData();
  33522. vertexData.indices = indices;
  33523. vertexData.positions = positions;
  33524. vertexData.normals = normals;
  33525. vertexData.uvs = uvs;
  33526. return vertexData;
  33527. };
  33528. /**
  33529. * Creates the VertexData of the Ground designed from a heightmap.
  33530. */
  33531. VertexData.CreateGroundFromHeightMap = function (options) {
  33532. var indices = [];
  33533. var positions = [];
  33534. var normals = [];
  33535. var uvs = [];
  33536. var row, col;
  33537. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33538. // Vertices
  33539. for (row = 0; row <= options.subdivisions; row++) {
  33540. for (col = 0; col <= options.subdivisions; col++) {
  33541. 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));
  33542. // Compute height
  33543. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33544. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33545. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33546. var r = options.buffer[pos] / 255.0;
  33547. var g = options.buffer[pos + 1] / 255.0;
  33548. var b = options.buffer[pos + 2] / 255.0;
  33549. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33550. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33551. // Add vertex
  33552. positions.push(position.x, position.y, position.z);
  33553. normals.push(0, 0, 0);
  33554. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33555. }
  33556. }
  33557. // Indices
  33558. for (row = 0; row < options.subdivisions; row++) {
  33559. for (col = 0; col < options.subdivisions; col++) {
  33560. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33561. indices.push(col + 1 + row * (options.subdivisions + 1));
  33562. indices.push(col + row * (options.subdivisions + 1));
  33563. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33564. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33565. indices.push(col + row * (options.subdivisions + 1));
  33566. }
  33567. }
  33568. // Normals
  33569. VertexData.ComputeNormals(positions, indices, normals);
  33570. // Result
  33571. var vertexData = new VertexData();
  33572. vertexData.indices = indices;
  33573. vertexData.positions = positions;
  33574. vertexData.normals = normals;
  33575. vertexData.uvs = uvs;
  33576. return vertexData;
  33577. };
  33578. /**
  33579. * Creates the VertexData of the Plane.
  33580. */
  33581. VertexData.CreatePlane = function (options) {
  33582. var indices = [];
  33583. var positions = [];
  33584. var normals = [];
  33585. var uvs = [];
  33586. var width = options.width || options.size || 1;
  33587. var height = options.height || options.size || 1;
  33588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33589. // Vertices
  33590. var halfWidth = width / 2.0;
  33591. var halfHeight = height / 2.0;
  33592. positions.push(-halfWidth, -halfHeight, 0);
  33593. normals.push(0, 0, -1.0);
  33594. uvs.push(0.0, 0.0);
  33595. positions.push(halfWidth, -halfHeight, 0);
  33596. normals.push(0, 0, -1.0);
  33597. uvs.push(1.0, 0.0);
  33598. positions.push(halfWidth, halfHeight, 0);
  33599. normals.push(0, 0, -1.0);
  33600. uvs.push(1.0, 1.0);
  33601. positions.push(-halfWidth, halfHeight, 0);
  33602. normals.push(0, 0, -1.0);
  33603. uvs.push(0.0, 1.0);
  33604. // Indices
  33605. indices.push(0);
  33606. indices.push(1);
  33607. indices.push(2);
  33608. indices.push(0);
  33609. indices.push(2);
  33610. indices.push(3);
  33611. // Sides
  33612. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33613. // Result
  33614. var vertexData = new VertexData();
  33615. vertexData.indices = indices;
  33616. vertexData.positions = positions;
  33617. vertexData.normals = normals;
  33618. vertexData.uvs = uvs;
  33619. return vertexData;
  33620. };
  33621. /**
  33622. * Creates the VertexData of the Disc or regular Polygon.
  33623. */
  33624. VertexData.CreateDisc = function (options) {
  33625. var positions = new Array();
  33626. var indices = new Array();
  33627. var normals = new Array();
  33628. var uvs = new Array();
  33629. var radius = options.radius || 0.5;
  33630. var tessellation = options.tessellation || 64;
  33631. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33633. // positions and uvs
  33634. positions.push(0, 0, 0); // disc center first
  33635. uvs.push(0.5, 0.5);
  33636. var theta = Math.PI * 2 * arc;
  33637. var step = theta / tessellation;
  33638. for (var a = 0; a < theta; a += step) {
  33639. var x = Math.cos(a);
  33640. var y = Math.sin(a);
  33641. var u = (x + 1) / 2;
  33642. var v = (1 - y) / 2;
  33643. positions.push(radius * x, radius * y, 0);
  33644. uvs.push(u, v);
  33645. }
  33646. if (arc === 1) {
  33647. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33648. uvs.push(uvs[2], uvs[3]);
  33649. }
  33650. //indices
  33651. var vertexNb = positions.length / 3;
  33652. for (var i = 1; i < vertexNb - 1; i++) {
  33653. indices.push(i + 1, 0, i);
  33654. }
  33655. // result
  33656. VertexData.ComputeNormals(positions, indices, normals);
  33657. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33658. var vertexData = new VertexData();
  33659. vertexData.indices = indices;
  33660. vertexData.positions = positions;
  33661. vertexData.normals = normals;
  33662. vertexData.uvs = uvs;
  33663. return vertexData;
  33664. };
  33665. /**
  33666. * Re-creates the VertexData of the Polygon for sideOrientation.
  33667. */
  33668. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33669. var faceUV = fUV || new Array(3);
  33670. var faceColors = fColors;
  33671. var colors = [];
  33672. // default face colors and UV if undefined
  33673. for (var f = 0; f < 3; f++) {
  33674. if (faceUV[f] === undefined) {
  33675. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33676. }
  33677. if (faceColors && faceColors[f] === undefined) {
  33678. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33679. }
  33680. }
  33681. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33682. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33683. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33684. var indices = polygon.getIndices();
  33685. // set face colours and textures
  33686. var idx = 0;
  33687. var face = 0;
  33688. for (var index = 0; index < normals.length; index += 3) {
  33689. //Edge Face no. 1
  33690. if (Math.abs(normals[index + 1]) < 0.001) {
  33691. face = 1;
  33692. }
  33693. //Top Face no. 0
  33694. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33695. face = 0;
  33696. }
  33697. //Bottom Face no. 2
  33698. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33699. face = 2;
  33700. }
  33701. idx = index / 3;
  33702. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33703. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33704. if (faceColors) {
  33705. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33706. }
  33707. }
  33708. // sides
  33709. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33710. // Result
  33711. var vertexData = new VertexData();
  33712. vertexData.indices = indices;
  33713. vertexData.positions = positions;
  33714. vertexData.normals = normals;
  33715. vertexData.uvs = uvs;
  33716. if (faceColors) {
  33717. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33718. vertexData.colors = totalColors;
  33719. }
  33720. return vertexData;
  33721. };
  33722. /**
  33723. * Creates the VertexData of the IcoSphere.
  33724. */
  33725. VertexData.CreateIcoSphere = function (options) {
  33726. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33727. var radius = options.radius || 1;
  33728. var flat = (options.flat === undefined) ? true : options.flat;
  33729. var subdivisions = options.subdivisions || 4;
  33730. var radiusX = options.radiusX || radius;
  33731. var radiusY = options.radiusY || radius;
  33732. var radiusZ = options.radiusZ || radius;
  33733. var t = (1 + Math.sqrt(5)) / 2;
  33734. // 12 vertex x,y,z
  33735. var ico_vertices = [
  33736. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33737. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33738. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33739. ];
  33740. // index of 3 vertex makes a face of icopshere
  33741. var ico_indices = [
  33742. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33743. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33744. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33745. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33746. ];
  33747. // vertex for uv have aliased position, not for UV
  33748. var vertices_unalias_id = [
  33749. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33750. // vertex alias
  33751. 0,
  33752. 2,
  33753. 3,
  33754. 3,
  33755. 3,
  33756. 4,
  33757. 7,
  33758. 8,
  33759. 9,
  33760. 9,
  33761. 10,
  33762. 11 // 23: B + 12
  33763. ];
  33764. // uv as integer step (not pixels !)
  33765. var ico_vertexuv = [
  33766. 5, 1, 3, 1, 6, 4, 0, 0,
  33767. 5, 3, 4, 2, 2, 2, 4, 0,
  33768. 2, 0, 1, 1, 6, 0, 6, 2,
  33769. // vertex alias (for same vertex on different faces)
  33770. 0, 4,
  33771. 3, 3,
  33772. 4, 4,
  33773. 3, 1,
  33774. 4, 2,
  33775. 4, 4,
  33776. 0, 2,
  33777. 1, 1,
  33778. 2, 2,
  33779. 3, 3,
  33780. 1, 3,
  33781. 2, 4 // 23: B + 12
  33782. ];
  33783. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33784. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33785. // First island of uv mapping
  33786. // v = 4h 3+ 2
  33787. // v = 3h 9+ 4
  33788. // v = 2h 9+ 5 B
  33789. // v = 1h 9 1 0
  33790. // v = 0h 3 8 7 A
  33791. // u = 0 1 2 3 4 5 6 *a
  33792. // Second island of uv mapping
  33793. // v = 4h 0+ B+ 4+
  33794. // v = 3h A+ 2+
  33795. // v = 2h 7+ 6 3+
  33796. // v = 1h 8+ 3+
  33797. // v = 0h
  33798. // u = 0 1 2 3 4 5 6 *a
  33799. // Face layout on texture UV mapping
  33800. // ============
  33801. // \ 4 /\ 16 / ======
  33802. // \ / \ / /\ 11 /
  33803. // \/ 7 \/ / \ /
  33804. // ======= / 10 \/
  33805. // /\ 17 /\ =======
  33806. // / \ / \ \ 15 /\
  33807. // / 8 \/ 12 \ \ / \
  33808. // ============ \/ 6 \
  33809. // \ 18 /\ ============
  33810. // \ / \ \ 5 /\ 0 /
  33811. // \/ 13 \ \ / \ /
  33812. // ======= \/ 1 \/
  33813. // =============
  33814. // /\ 19 /\ 2 /\
  33815. // / \ / \ / \
  33816. // / 14 \/ 9 \/ 3 \
  33817. // ===================
  33818. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33819. var ustep = 138 / 1024;
  33820. var vstep = 239 / 1024;
  33821. var uoffset = 60 / 1024;
  33822. var voffset = 26 / 1024;
  33823. // Second island should have margin, not to touch the first island
  33824. // avoid any borderline artefact in pixel rounding
  33825. var island_u_offset = -40 / 1024;
  33826. var island_v_offset = +20 / 1024;
  33827. // face is either island 0 or 1 :
  33828. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33829. var island = [
  33830. 0, 0, 0, 0, 1,
  33831. 0, 0, 1, 1, 0,
  33832. 0, 0, 1, 1, 0,
  33833. 0, 1, 1, 1, 0 // 15 - 19
  33834. ];
  33835. var indices = new Array();
  33836. var positions = new Array();
  33837. var normals = new Array();
  33838. var uvs = new Array();
  33839. var current_indice = 0;
  33840. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33841. var face_vertex_pos = new Array(3);
  33842. var face_vertex_uv = new Array(3);
  33843. var v012;
  33844. for (v012 = 0; v012 < 3; v012++) {
  33845. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33846. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33847. }
  33848. // create all with normals
  33849. for (var face = 0; face < 20; face++) {
  33850. // 3 vertex per face
  33851. for (v012 = 0; v012 < 3; v012++) {
  33852. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33853. var v_id = ico_indices[3 * face + v012];
  33854. // vertex have 3D position (x,y,z)
  33855. 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]);
  33856. // Normalize to get normal, then scale to radius
  33857. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33858. // uv Coordinates from vertex ID
  33859. 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);
  33860. }
  33861. // Subdivide the face (interpolate pos, norm, uv)
  33862. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33863. // - norm is linear interpolation of vertex corner normal
  33864. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33865. // - uv is linear interpolation
  33866. //
  33867. // Topology is as below for sub-divide by 2
  33868. // vertex shown as v0,v1,v2
  33869. // interp index is i1 to progress in range [v0,v1[
  33870. // interp index is i2 to progress in range [v0,v2[
  33871. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33872. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33873. //
  33874. //
  33875. // i2 v2
  33876. // ^ ^
  33877. // / / \
  33878. // / / \
  33879. // / / \
  33880. // / / (0,1) \
  33881. // / #---------\
  33882. // / / \ (0,0)'/ \
  33883. // / / \ / \
  33884. // / / \ / \
  33885. // / / (0,0) \ / (1,0) \
  33886. // / #---------#---------\
  33887. // v0 v1
  33888. //
  33889. // --------------------> i1
  33890. //
  33891. // interp of (i1,i2):
  33892. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33893. // along i1 : lerp(x0,x1, i1/(S-i2))
  33894. //
  33895. // centroid of triangle is needed to get help normal computation
  33896. // (c1,c2) are used for centroid location
  33897. var interp_vertex = function (i1, i2, c1, c2) {
  33898. // vertex is interpolated from
  33899. // - face_vertex_pos[0..2]
  33900. // - face_vertex_uv[0..2]
  33901. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33902. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33903. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33904. pos_interp.normalize();
  33905. var vertex_normal;
  33906. if (flat) {
  33907. // in flat mode, recalculate normal as face centroid normal
  33908. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33909. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33910. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33911. }
  33912. else {
  33913. // in smooth mode, recalculate normal from each single vertex position
  33914. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33915. }
  33916. // Vertex normal need correction due to X,Y,Z radius scaling
  33917. vertex_normal.x /= radiusX;
  33918. vertex_normal.y /= radiusY;
  33919. vertex_normal.z /= radiusZ;
  33920. vertex_normal.normalize();
  33921. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33922. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33923. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33924. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33925. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33926. uvs.push(uv_interp.x, uv_interp.y);
  33927. // push each vertex has member of a face
  33928. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33929. indices.push(current_indice);
  33930. current_indice++;
  33931. };
  33932. for (var i2 = 0; i2 < subdivisions; i2++) {
  33933. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33934. // face : (i1,i2) for /\ :
  33935. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33936. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33937. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33938. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33939. if (i1 + i2 + 1 < subdivisions) {
  33940. // face : (i1,i2)' for \/ :
  33941. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33942. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33943. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33944. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33945. }
  33946. }
  33947. }
  33948. }
  33949. // Sides
  33950. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33951. // Result
  33952. var vertexData = new VertexData();
  33953. vertexData.indices = indices;
  33954. vertexData.positions = positions;
  33955. vertexData.normals = normals;
  33956. vertexData.uvs = uvs;
  33957. return vertexData;
  33958. };
  33959. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33960. /**
  33961. * Creates the VertexData of the Polyhedron.
  33962. */
  33963. VertexData.CreatePolyhedron = function (options) {
  33964. // provided polyhedron types :
  33965. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33966. // 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)
  33967. var polyhedra = [];
  33968. 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]] };
  33969. 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]] };
  33970. polyhedra[2] = {
  33971. 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]],
  33972. 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]]
  33973. };
  33974. polyhedra[3] = {
  33975. 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]],
  33976. 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]]
  33977. };
  33978. polyhedra[4] = {
  33979. 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]],
  33980. 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]]
  33981. };
  33982. 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]] };
  33983. 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]] };
  33984. 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]] };
  33985. 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]] };
  33986. 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]] };
  33987. 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]] };
  33988. 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]] };
  33989. 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]] };
  33990. 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]] };
  33991. polyhedra[14] = {
  33992. 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]],
  33993. 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]]
  33994. };
  33995. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33996. var size = options.size;
  33997. var sizeX = options.sizeX || size || 1;
  33998. var sizeY = options.sizeY || size || 1;
  33999. var sizeZ = options.sizeZ || size || 1;
  34000. var data = options.custom || polyhedra[type];
  34001. var nbfaces = data.face.length;
  34002. var faceUV = options.faceUV || new Array(nbfaces);
  34003. var faceColors = options.faceColors;
  34004. var flat = (options.flat === undefined) ? true : options.flat;
  34005. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34006. var positions = new Array();
  34007. var indices = new Array();
  34008. var normals = new Array();
  34009. var uvs = new Array();
  34010. var colors = new Array();
  34011. var index = 0;
  34012. var faceIdx = 0; // face cursor in the array "indexes"
  34013. var indexes = new Array();
  34014. var i = 0;
  34015. var f = 0;
  34016. var u, v, ang, x, y, tmp;
  34017. // default face colors and UV if undefined
  34018. if (flat) {
  34019. for (f = 0; f < nbfaces; f++) {
  34020. if (faceColors && faceColors[f] === undefined) {
  34021. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34022. }
  34023. if (faceUV && faceUV[f] === undefined) {
  34024. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34025. }
  34026. }
  34027. }
  34028. if (!flat) {
  34029. for (i = 0; i < data.vertex.length; i++) {
  34030. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34031. uvs.push(0, 0);
  34032. }
  34033. for (f = 0; f < nbfaces; f++) {
  34034. for (i = 0; i < data.face[f].length - 2; i++) {
  34035. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34036. }
  34037. }
  34038. }
  34039. else {
  34040. for (f = 0; f < nbfaces; f++) {
  34041. var fl = data.face[f].length; // number of vertices of the current face
  34042. ang = 2 * Math.PI / fl;
  34043. x = 0.5 * Math.tan(ang / 2);
  34044. y = 0.5;
  34045. // positions, uvs, colors
  34046. for (i = 0; i < fl; i++) {
  34047. // positions
  34048. 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);
  34049. indexes.push(index);
  34050. index++;
  34051. // uvs
  34052. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34053. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34054. uvs.push(u, v);
  34055. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34056. y = x * Math.sin(ang) + y * Math.cos(ang);
  34057. x = tmp;
  34058. // colors
  34059. if (faceColors) {
  34060. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34061. }
  34062. }
  34063. // indices from indexes
  34064. for (i = 0; i < fl - 2; i++) {
  34065. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34066. }
  34067. faceIdx += fl;
  34068. }
  34069. }
  34070. VertexData.ComputeNormals(positions, indices, normals);
  34071. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34072. var vertexData = new VertexData();
  34073. vertexData.positions = positions;
  34074. vertexData.indices = indices;
  34075. vertexData.normals = normals;
  34076. vertexData.uvs = uvs;
  34077. if (faceColors && flat) {
  34078. vertexData.colors = colors;
  34079. }
  34080. return vertexData;
  34081. };
  34082. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34083. /**
  34084. * Creates the VertexData of the Torus Knot.
  34085. */
  34086. VertexData.CreateTorusKnot = function (options) {
  34087. var indices = new Array();
  34088. var positions = new Array();
  34089. var normals = new Array();
  34090. var uvs = new Array();
  34091. var radius = options.radius || 2;
  34092. var tube = options.tube || 0.5;
  34093. var radialSegments = options.radialSegments || 32;
  34094. var tubularSegments = options.tubularSegments || 32;
  34095. var p = options.p || 2;
  34096. var q = options.q || 3;
  34097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34098. // Helper
  34099. var getPos = function (angle) {
  34100. var cu = Math.cos(angle);
  34101. var su = Math.sin(angle);
  34102. var quOverP = q / p * angle;
  34103. var cs = Math.cos(quOverP);
  34104. var tx = radius * (2 + cs) * 0.5 * cu;
  34105. var ty = radius * (2 + cs) * su * 0.5;
  34106. var tz = radius * Math.sin(quOverP) * 0.5;
  34107. return new BABYLON.Vector3(tx, ty, tz);
  34108. };
  34109. // Vertices
  34110. var i;
  34111. var j;
  34112. for (i = 0; i <= radialSegments; i++) {
  34113. var modI = i % radialSegments;
  34114. var u = modI / radialSegments * 2 * p * Math.PI;
  34115. var p1 = getPos(u);
  34116. var p2 = getPos(u + 0.01);
  34117. var tang = p2.subtract(p1);
  34118. var n = p2.add(p1);
  34119. var bitan = BABYLON.Vector3.Cross(tang, n);
  34120. n = BABYLON.Vector3.Cross(bitan, tang);
  34121. bitan.normalize();
  34122. n.normalize();
  34123. for (j = 0; j < tubularSegments; j++) {
  34124. var modJ = j % tubularSegments;
  34125. var v = modJ / tubularSegments * 2 * Math.PI;
  34126. var cx = -tube * Math.cos(v);
  34127. var cy = tube * Math.sin(v);
  34128. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34129. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34130. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34131. uvs.push(i / radialSegments);
  34132. uvs.push(j / tubularSegments);
  34133. }
  34134. }
  34135. for (i = 0; i < radialSegments; i++) {
  34136. for (j = 0; j < tubularSegments; j++) {
  34137. var jNext = (j + 1) % tubularSegments;
  34138. var a = i * tubularSegments + j;
  34139. var b = (i + 1) * tubularSegments + j;
  34140. var c = (i + 1) * tubularSegments + jNext;
  34141. var d = i * tubularSegments + jNext;
  34142. indices.push(d);
  34143. indices.push(b);
  34144. indices.push(a);
  34145. indices.push(d);
  34146. indices.push(c);
  34147. indices.push(b);
  34148. }
  34149. }
  34150. // Normals
  34151. VertexData.ComputeNormals(positions, indices, normals);
  34152. // Sides
  34153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34154. // Result
  34155. var vertexData = new VertexData();
  34156. vertexData.indices = indices;
  34157. vertexData.positions = positions;
  34158. vertexData.normals = normals;
  34159. vertexData.uvs = uvs;
  34160. return vertexData;
  34161. };
  34162. // Tools
  34163. /**
  34164. * @param {any} - positions (number[] or Float32Array)
  34165. * @param {any} - indices (number[] or Uint16Array)
  34166. * @param {any} - normals (number[] or Float32Array)
  34167. * options (optional) :
  34168. * facetPositions : optional array of facet positions (vector3)
  34169. * facetNormals : optional array of facet normals (vector3)
  34170. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34171. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34172. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34173. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34174. * bInfo : optional bounding info, required for facetPartitioning computation
  34175. * useRightHandedSystem: optional boolean to for right handed system computation
  34176. * depthSort : optional boolean to enable the facet depth sort computation
  34177. * distanceTo : optional Vector3 to compute the facet depth from this location
  34178. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34179. */
  34180. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34181. // temporary scalar variables
  34182. var index = 0; // facet index
  34183. var p1p2x = 0.0; // p1p2 vector x coordinate
  34184. var p1p2y = 0.0; // p1p2 vector y coordinate
  34185. var p1p2z = 0.0; // p1p2 vector z coordinate
  34186. var p3p2x = 0.0; // p3p2 vector x coordinate
  34187. var p3p2y = 0.0; // p3p2 vector y coordinate
  34188. var p3p2z = 0.0; // p3p2 vector z coordinate
  34189. var faceNormalx = 0.0; // facet normal x coordinate
  34190. var faceNormaly = 0.0; // facet normal y coordinate
  34191. var faceNormalz = 0.0; // facet normal z coordinate
  34192. var length = 0.0; // facet normal length before normalization
  34193. var v1x = 0; // vector1 x index in the positions array
  34194. var v1y = 0; // vector1 y index in the positions array
  34195. var v1z = 0; // vector1 z index in the positions array
  34196. var v2x = 0; // vector2 x index in the positions array
  34197. var v2y = 0; // vector2 y index in the positions array
  34198. var v2z = 0; // vector2 z index in the positions array
  34199. var v3x = 0; // vector3 x index in the positions array
  34200. var v3y = 0; // vector3 y index in the positions array
  34201. var v3z = 0; // vector3 z index in the positions array
  34202. var computeFacetNormals = false;
  34203. var computeFacetPositions = false;
  34204. var computeFacetPartitioning = false;
  34205. var computeDepthSort = false;
  34206. var faceNormalSign = 1;
  34207. var ratio = 0;
  34208. var distanceTo = null;
  34209. if (options) {
  34210. computeFacetNormals = (options.facetNormals) ? true : false;
  34211. computeFacetPositions = (options.facetPositions) ? true : false;
  34212. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34213. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34214. ratio = options.ratio || 0;
  34215. computeDepthSort = (options.depthSort) ? true : false;
  34216. distanceTo = (options.distanceTo);
  34217. if (computeDepthSort) {
  34218. if (distanceTo === undefined) {
  34219. distanceTo = BABYLON.Vector3.Zero();
  34220. }
  34221. var depthSortedFacets = options.depthSortedFacets;
  34222. }
  34223. }
  34224. // facetPartitioning reinit if needed
  34225. var xSubRatio = 0;
  34226. var ySubRatio = 0;
  34227. var zSubRatio = 0;
  34228. var subSq = 0;
  34229. if (computeFacetPartitioning && options && options.bbSize) {
  34230. var ox = 0; // X partitioning index for facet position
  34231. var oy = 0; // Y partinioning index for facet position
  34232. var oz = 0; // Z partinioning index for facet position
  34233. var b1x = 0; // X partitioning index for facet v1 vertex
  34234. var b1y = 0; // Y partitioning index for facet v1 vertex
  34235. var b1z = 0; // z partitioning index for facet v1 vertex
  34236. var b2x = 0; // X partitioning index for facet v2 vertex
  34237. var b2y = 0; // Y partitioning index for facet v2 vertex
  34238. var b2z = 0; // Z partitioning index for facet v2 vertex
  34239. var b3x = 0; // X partitioning index for facet v3 vertex
  34240. var b3y = 0; // Y partitioning index for facet v3 vertex
  34241. var b3z = 0; // Z partitioning index for facet v3 vertex
  34242. var block_idx_o = 0; // facet barycenter block index
  34243. var block_idx_v1 = 0; // v1 vertex block index
  34244. var block_idx_v2 = 0; // v2 vertex block index
  34245. var block_idx_v3 = 0; // v3 vertex block index
  34246. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34247. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34248. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34249. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34250. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34251. subSq = options.subDiv.max * options.subDiv.max;
  34252. options.facetPartitioning.length = 0;
  34253. }
  34254. // reset the normals
  34255. for (index = 0; index < positions.length; index++) {
  34256. normals[index] = 0.0;
  34257. }
  34258. // Loop : 1 indice triplet = 1 facet
  34259. var nbFaces = (indices.length / 3) | 0;
  34260. for (index = 0; index < nbFaces; index++) {
  34261. // get the indexes of the coordinates of each vertex of the facet
  34262. v1x = indices[index * 3] * 3;
  34263. v1y = v1x + 1;
  34264. v1z = v1x + 2;
  34265. v2x = indices[index * 3 + 1] * 3;
  34266. v2y = v2x + 1;
  34267. v2z = v2x + 2;
  34268. v3x = indices[index * 3 + 2] * 3;
  34269. v3y = v3x + 1;
  34270. v3z = v3x + 2;
  34271. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34272. p1p2y = positions[v1y] - positions[v2y];
  34273. p1p2z = positions[v1z] - positions[v2z];
  34274. p3p2x = positions[v3x] - positions[v2x];
  34275. p3p2y = positions[v3y] - positions[v2y];
  34276. p3p2z = positions[v3z] - positions[v2z];
  34277. // compute the face normal with the cross product
  34278. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34279. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34280. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34281. // normalize this normal and store it in the array facetData
  34282. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34283. length = (length === 0) ? 1.0 : length;
  34284. faceNormalx /= length;
  34285. faceNormaly /= length;
  34286. faceNormalz /= length;
  34287. if (computeFacetNormals && options) {
  34288. options.facetNormals[index].x = faceNormalx;
  34289. options.facetNormals[index].y = faceNormaly;
  34290. options.facetNormals[index].z = faceNormalz;
  34291. }
  34292. if (computeFacetPositions && options) {
  34293. // compute and the facet barycenter coordinates in the array facetPositions
  34294. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34295. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34296. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34297. }
  34298. if (computeFacetPartitioning && options) {
  34299. // store the facet indexes in arrays in the main facetPartitioning array :
  34300. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34301. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34302. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34303. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34304. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34305. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34306. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34307. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34308. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34309. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34310. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34311. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34312. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34313. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34314. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34315. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34316. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34317. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34318. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34319. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34320. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34321. // push each facet index in each block containing the vertex
  34322. options.facetPartitioning[block_idx_v1].push(index);
  34323. if (block_idx_v2 != block_idx_v1) {
  34324. options.facetPartitioning[block_idx_v2].push(index);
  34325. }
  34326. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34327. options.facetPartitioning[block_idx_v3].push(index);
  34328. }
  34329. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34330. options.facetPartitioning[block_idx_o].push(index);
  34331. }
  34332. }
  34333. if (computeDepthSort && options && options.facetPositions) {
  34334. var dsf = depthSortedFacets[index];
  34335. dsf.ind = index * 3;
  34336. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34337. }
  34338. // compute the normals anyway
  34339. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34340. normals[v1y] += faceNormaly;
  34341. normals[v1z] += faceNormalz;
  34342. normals[v2x] += faceNormalx;
  34343. normals[v2y] += faceNormaly;
  34344. normals[v2z] += faceNormalz;
  34345. normals[v3x] += faceNormalx;
  34346. normals[v3y] += faceNormaly;
  34347. normals[v3z] += faceNormalz;
  34348. }
  34349. // last normalization of each normal
  34350. for (index = 0; index < normals.length / 3; index++) {
  34351. faceNormalx = normals[index * 3];
  34352. faceNormaly = normals[index * 3 + 1];
  34353. faceNormalz = normals[index * 3 + 2];
  34354. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34355. length = (length === 0) ? 1.0 : length;
  34356. faceNormalx /= length;
  34357. faceNormaly /= length;
  34358. faceNormalz /= length;
  34359. normals[index * 3] = faceNormalx;
  34360. normals[index * 3 + 1] = faceNormaly;
  34361. normals[index * 3 + 2] = faceNormalz;
  34362. }
  34363. };
  34364. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34365. var li = indices.length;
  34366. var ln = normals.length;
  34367. var i;
  34368. var n;
  34369. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34370. switch (sideOrientation) {
  34371. case BABYLON.Mesh.FRONTSIDE:
  34372. // nothing changed
  34373. break;
  34374. case BABYLON.Mesh.BACKSIDE:
  34375. var tmp;
  34376. // indices
  34377. for (i = 0; i < li; i += 3) {
  34378. tmp = indices[i];
  34379. indices[i] = indices[i + 2];
  34380. indices[i + 2] = tmp;
  34381. }
  34382. // normals
  34383. for (n = 0; n < ln; n++) {
  34384. normals[n] = -normals[n];
  34385. }
  34386. break;
  34387. case BABYLON.Mesh.DOUBLESIDE:
  34388. // positions
  34389. var lp = positions.length;
  34390. var l = lp / 3;
  34391. for (var p = 0; p < lp; p++) {
  34392. positions[lp + p] = positions[p];
  34393. }
  34394. // indices
  34395. for (i = 0; i < li; i += 3) {
  34396. indices[i + li] = indices[i + 2] + l;
  34397. indices[i + 1 + li] = indices[i + 1] + l;
  34398. indices[i + 2 + li] = indices[i] + l;
  34399. }
  34400. // normals
  34401. for (n = 0; n < ln; n++) {
  34402. normals[ln + n] = -normals[n];
  34403. }
  34404. // uvs
  34405. var lu = uvs.length;
  34406. var u = 0;
  34407. for (u = 0; u < lu; u++) {
  34408. uvs[u + lu] = uvs[u];
  34409. }
  34410. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34411. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34412. u = 0;
  34413. for (i = 0; i < lu / 2; i++) {
  34414. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34415. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34416. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34417. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34418. u += 2;
  34419. }
  34420. break;
  34421. }
  34422. };
  34423. /**
  34424. * Creates a new VertexData from the imported parameters.
  34425. */
  34426. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34427. var vertexData = new VertexData();
  34428. // positions
  34429. var positions = parsedVertexData.positions;
  34430. if (positions) {
  34431. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34432. }
  34433. // normals
  34434. var normals = parsedVertexData.normals;
  34435. if (normals) {
  34436. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34437. }
  34438. // tangents
  34439. var tangents = parsedVertexData.tangents;
  34440. if (tangents) {
  34441. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34442. }
  34443. // uvs
  34444. var uvs = parsedVertexData.uvs;
  34445. if (uvs) {
  34446. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34447. }
  34448. // uv2s
  34449. var uv2s = parsedVertexData.uv2s;
  34450. if (uv2s) {
  34451. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34452. }
  34453. // uv3s
  34454. var uv3s = parsedVertexData.uv3s;
  34455. if (uv3s) {
  34456. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34457. }
  34458. // uv4s
  34459. var uv4s = parsedVertexData.uv4s;
  34460. if (uv4s) {
  34461. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34462. }
  34463. // uv5s
  34464. var uv5s = parsedVertexData.uv5s;
  34465. if (uv5s) {
  34466. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34467. }
  34468. // uv6s
  34469. var uv6s = parsedVertexData.uv6s;
  34470. if (uv6s) {
  34471. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34472. }
  34473. // colors
  34474. var colors = parsedVertexData.colors;
  34475. if (colors) {
  34476. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34477. }
  34478. // matricesIndices
  34479. var matricesIndices = parsedVertexData.matricesIndices;
  34480. if (matricesIndices) {
  34481. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34482. }
  34483. // matricesWeights
  34484. var matricesWeights = parsedVertexData.matricesWeights;
  34485. if (matricesWeights) {
  34486. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34487. }
  34488. // indices
  34489. var indices = parsedVertexData.indices;
  34490. if (indices) {
  34491. vertexData.indices = indices;
  34492. }
  34493. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34494. };
  34495. return VertexData;
  34496. }());
  34497. BABYLON.VertexData = VertexData;
  34498. })(BABYLON || (BABYLON = {}));
  34499. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34500. var BABYLON;
  34501. (function (BABYLON) {
  34502. /**
  34503. * Class used to store geometry data (vertex buffers + index buffer)
  34504. */
  34505. var Geometry = /** @class */ (function () {
  34506. /**
  34507. * Creates a new geometry
  34508. * @param id defines the unique ID
  34509. * @param scene defines the hosting scene
  34510. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34511. * @param updatable defines if geometry must be updatable (false by default)
  34512. * @param mesh defines the mesh that will be associated with the geometry
  34513. */
  34514. function Geometry(id, scene, vertexData, updatable, mesh) {
  34515. if (updatable === void 0) { updatable = false; }
  34516. if (mesh === void 0) { mesh = null; }
  34517. /**
  34518. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34519. */
  34520. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34521. this._totalVertices = 0;
  34522. this._isDisposed = false;
  34523. this._indexBufferIsUpdatable = false;
  34524. this.id = id;
  34525. this._engine = scene.getEngine();
  34526. this._meshes = [];
  34527. this._scene = scene;
  34528. //Init vertex buffer cache
  34529. this._vertexBuffers = {};
  34530. this._indices = [];
  34531. this._updatable = updatable;
  34532. // vertexData
  34533. if (vertexData) {
  34534. this.setAllVerticesData(vertexData, updatable);
  34535. }
  34536. else {
  34537. this._totalVertices = 0;
  34538. this._indices = [];
  34539. }
  34540. if (this._engine.getCaps().vertexArrayObject) {
  34541. this._vertexArrayObjects = {};
  34542. }
  34543. // applyToMesh
  34544. if (mesh) {
  34545. if (mesh.getClassName() === "LinesMesh") {
  34546. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34547. this.updateExtend();
  34548. }
  34549. this.applyToMesh(mesh);
  34550. mesh.computeWorldMatrix(true);
  34551. }
  34552. }
  34553. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34554. /**
  34555. * 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
  34556. */
  34557. get: function () {
  34558. return this._boundingBias;
  34559. },
  34560. /**
  34561. * 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
  34562. */
  34563. set: function (value) {
  34564. if (this._boundingBias && this._boundingBias.equals(value)) {
  34565. return;
  34566. }
  34567. this._boundingBias = value.clone();
  34568. this.updateBoundingInfo(true, null);
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. /**
  34574. * Static function used to attach a new empty geometry to a mesh
  34575. * @param mesh defines the mesh to attach the geometry to
  34576. * @returns the new {BABYLON.Geometry}
  34577. */
  34578. Geometry.CreateGeometryForMesh = function (mesh) {
  34579. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34580. geometry.applyToMesh(mesh);
  34581. return geometry;
  34582. };
  34583. Object.defineProperty(Geometry.prototype, "extend", {
  34584. /**
  34585. * Gets the current extend of the geometry
  34586. */
  34587. get: function () {
  34588. return this._extend;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. /**
  34594. * Gets the hosting scene
  34595. * @returns the hosting {BABYLON.Scene}
  34596. */
  34597. Geometry.prototype.getScene = function () {
  34598. return this._scene;
  34599. };
  34600. /**
  34601. * Gets the hosting engine
  34602. * @returns the hosting {BABYLON.Engine}
  34603. */
  34604. Geometry.prototype.getEngine = function () {
  34605. return this._engine;
  34606. };
  34607. /**
  34608. * Defines if the geometry is ready to use
  34609. * @returns true if the geometry is ready to be used
  34610. */
  34611. Geometry.prototype.isReady = function () {
  34612. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34613. };
  34614. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34615. /**
  34616. * Gets a value indicating that the geometry should not be serialized
  34617. */
  34618. get: function () {
  34619. for (var index = 0; index < this._meshes.length; index++) {
  34620. if (!this._meshes[index].doNotSerialize) {
  34621. return false;
  34622. }
  34623. }
  34624. return true;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. /** @ignore */
  34630. Geometry.prototype._rebuild = function () {
  34631. if (this._vertexArrayObjects) {
  34632. this._vertexArrayObjects = {};
  34633. }
  34634. // Index buffer
  34635. if (this._meshes.length !== 0 && this._indices) {
  34636. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34637. }
  34638. // Vertex buffers
  34639. for (var key in this._vertexBuffers) {
  34640. var vertexBuffer = this._vertexBuffers[key];
  34641. vertexBuffer._rebuild();
  34642. }
  34643. };
  34644. /**
  34645. * Affects all gemetry data in one call
  34646. * @param vertexData defines the geometry data
  34647. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34648. */
  34649. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34650. vertexData.applyToGeometry(this, updatable);
  34651. this.notifyUpdate();
  34652. };
  34653. /**
  34654. * Set specific vertex data
  34655. * @param kind defines the data kind (Position, normal, etc...)
  34656. * @param data defines the vertex data to use
  34657. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34658. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34659. */
  34660. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34661. if (updatable === void 0) { updatable = false; }
  34662. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34663. this.setVerticesBuffer(buffer);
  34664. };
  34665. /**
  34666. * Removes a specific vertex data
  34667. * @param kind defines the data kind (Position, normal, etc...)
  34668. */
  34669. Geometry.prototype.removeVerticesData = function (kind) {
  34670. if (this._vertexBuffers[kind]) {
  34671. this._vertexBuffers[kind].dispose();
  34672. delete this._vertexBuffers[kind];
  34673. }
  34674. };
  34675. /**
  34676. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34677. * @param buffer defines the vertex buffer to use
  34678. */
  34679. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34680. var kind = buffer.getKind();
  34681. if (this._vertexBuffers[kind]) {
  34682. this._vertexBuffers[kind].dispose();
  34683. }
  34684. this._vertexBuffers[kind] = buffer;
  34685. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34686. var data = buffer.getData();
  34687. var stride = buffer.getStrideSize();
  34688. this._totalVertices = data.length / stride;
  34689. this.updateExtend(data, stride);
  34690. this._resetPointsArrayCache();
  34691. var meshes = this._meshes;
  34692. var numOfMeshes = meshes.length;
  34693. for (var index = 0; index < numOfMeshes; index++) {
  34694. var mesh = meshes[index];
  34695. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34696. mesh._createGlobalSubMesh(false);
  34697. mesh.computeWorldMatrix(true);
  34698. }
  34699. }
  34700. this.notifyUpdate(kind);
  34701. if (this._vertexArrayObjects) {
  34702. this._disposeVertexArrayObjects();
  34703. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34704. }
  34705. };
  34706. /**
  34707. * Update a specific vertex buffer
  34708. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34709. * It will do nothing if the buffer is not updatable
  34710. * @param kind defines the data kind (Position, normal, etc...)
  34711. * @param data defines the data to use
  34712. * @param offset defines the offset in the target buffer where to store the data
  34713. */
  34714. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34715. var vertexBuffer = this.getVertexBuffer(kind);
  34716. if (!vertexBuffer) {
  34717. return;
  34718. }
  34719. vertexBuffer.updateDirectly(data, offset);
  34720. this.notifyUpdate(kind);
  34721. };
  34722. /**
  34723. * Update a specific vertex buffer
  34724. * This function will create a new buffer if the current one is not updatable
  34725. * @param kind defines the data kind (Position, normal, etc...)
  34726. * @param data defines the data to use
  34727. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34728. */
  34729. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34730. if (updateExtends === void 0) { updateExtends = false; }
  34731. var vertexBuffer = this.getVertexBuffer(kind);
  34732. if (!vertexBuffer) {
  34733. return;
  34734. }
  34735. vertexBuffer.update(data);
  34736. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34737. var stride = vertexBuffer.getStrideSize();
  34738. this._totalVertices = data.length / stride;
  34739. this.updateBoundingInfo(updateExtends, data);
  34740. }
  34741. this.notifyUpdate(kind);
  34742. };
  34743. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34744. if (updateExtends) {
  34745. this.updateExtend(data);
  34746. }
  34747. var meshes = this._meshes;
  34748. var numOfMeshes = meshes.length;
  34749. this._resetPointsArrayCache();
  34750. for (var index = 0; index < numOfMeshes; index++) {
  34751. var mesh = meshes[index];
  34752. if (updateExtends) {
  34753. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34754. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34755. var subMesh = mesh.subMeshes[subIndex];
  34756. subMesh.refreshBoundingInfo();
  34757. }
  34758. }
  34759. }
  34760. };
  34761. /** @ignore */
  34762. Geometry.prototype._bind = function (effect, indexToBind) {
  34763. if (!effect) {
  34764. return;
  34765. }
  34766. if (indexToBind === undefined) {
  34767. indexToBind = this._indexBuffer;
  34768. }
  34769. var vbs = this.getVertexBuffers();
  34770. if (!vbs) {
  34771. return;
  34772. }
  34773. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34774. this._engine.bindBuffers(vbs, indexToBind, effect);
  34775. return;
  34776. }
  34777. // Using VAO
  34778. if (!this._vertexArrayObjects[effect.key]) {
  34779. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34780. }
  34781. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34782. };
  34783. /**
  34784. * Gets total number of vertices
  34785. * @returns the total number of vertices
  34786. */
  34787. Geometry.prototype.getTotalVertices = function () {
  34788. if (!this.isReady()) {
  34789. return 0;
  34790. }
  34791. return this._totalVertices;
  34792. };
  34793. /**
  34794. * Gets a specific vertex data attached to this geometry
  34795. * @param kind defines the data kind (Position, normal, etc...)
  34796. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34797. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34798. * @returns a float array containing vertex data
  34799. */
  34800. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34801. var vertexBuffer = this.getVertexBuffer(kind);
  34802. if (!vertexBuffer) {
  34803. return null;
  34804. }
  34805. var orig = vertexBuffer.getData();
  34806. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34807. return orig;
  34808. }
  34809. else {
  34810. var len = orig.length;
  34811. var copy = [];
  34812. for (var i = 0; i < len; i++) {
  34813. copy.push(orig[i]);
  34814. }
  34815. return copy;
  34816. }
  34817. };
  34818. /**
  34819. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34820. * @param kind defines the data kind (Position, normal, etc...)
  34821. * @returns true if the vertex buffer with the specified kind is updatable
  34822. */
  34823. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34824. var vb = this._vertexBuffers[kind];
  34825. if (!vb) {
  34826. return false;
  34827. }
  34828. return vb.isUpdatable();
  34829. };
  34830. /**
  34831. * Gets a specific vertex buffer
  34832. * @param kind defines the data kind (Position, normal, etc...)
  34833. * @returns a {BABYLON.VertexBuffer}
  34834. */
  34835. Geometry.prototype.getVertexBuffer = function (kind) {
  34836. if (!this.isReady()) {
  34837. return null;
  34838. }
  34839. return this._vertexBuffers[kind];
  34840. };
  34841. /**
  34842. * Returns all vertex buffers
  34843. * @return an object holding all vertex buffers indexed by kind
  34844. */
  34845. Geometry.prototype.getVertexBuffers = function () {
  34846. if (!this.isReady()) {
  34847. return null;
  34848. }
  34849. return this._vertexBuffers;
  34850. };
  34851. /**
  34852. * Gets a boolean indicating if specific vertex buffer is present
  34853. * @param kind defines the data kind (Position, normal, etc...)
  34854. * @returns true if data is present
  34855. */
  34856. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34857. if (!this._vertexBuffers) {
  34858. if (this._delayInfo) {
  34859. return this._delayInfo.indexOf(kind) !== -1;
  34860. }
  34861. return false;
  34862. }
  34863. return this._vertexBuffers[kind] !== undefined;
  34864. };
  34865. /**
  34866. * Gets a list of all attached data kinds (Position, normal, etc...)
  34867. * @returns a list of string containing all kinds
  34868. */
  34869. Geometry.prototype.getVerticesDataKinds = function () {
  34870. var result = [];
  34871. var kind;
  34872. if (!this._vertexBuffers && this._delayInfo) {
  34873. for (kind in this._delayInfo) {
  34874. result.push(kind);
  34875. }
  34876. }
  34877. else {
  34878. for (kind in this._vertexBuffers) {
  34879. result.push(kind);
  34880. }
  34881. }
  34882. return result;
  34883. };
  34884. /**
  34885. * Update index buffer
  34886. * @param indices defines the indices to store in the index buffer
  34887. * @param offset defines the offset in the target buffer where to store the data
  34888. */
  34889. Geometry.prototype.updateIndices = function (indices, offset) {
  34890. if (!this._indexBuffer) {
  34891. return;
  34892. }
  34893. if (!this._indexBufferIsUpdatable) {
  34894. this.setIndices(indices, null, true);
  34895. }
  34896. else {
  34897. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34898. }
  34899. };
  34900. /**
  34901. * Creates a new index buffer
  34902. * @param indices defines the indices to store in the index buffer
  34903. * @param totalVertices defines the total number of vertices (could be null)
  34904. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34905. */
  34906. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34907. if (totalVertices === void 0) { totalVertices = null; }
  34908. if (updatable === void 0) { updatable = false; }
  34909. if (this._indexBuffer) {
  34910. this._engine._releaseBuffer(this._indexBuffer);
  34911. }
  34912. this._disposeVertexArrayObjects();
  34913. this._indices = indices;
  34914. this._indexBufferIsUpdatable = updatable;
  34915. if (this._meshes.length !== 0 && this._indices) {
  34916. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34917. }
  34918. if (totalVertices != undefined) {
  34919. this._totalVertices = totalVertices;
  34920. }
  34921. var meshes = this._meshes;
  34922. var numOfMeshes = meshes.length;
  34923. for (var index = 0; index < numOfMeshes; index++) {
  34924. meshes[index]._createGlobalSubMesh(true);
  34925. }
  34926. this.notifyUpdate();
  34927. };
  34928. /**
  34929. * Return the total number of indices
  34930. * @returns the total number of indices
  34931. */
  34932. Geometry.prototype.getTotalIndices = function () {
  34933. if (!this.isReady()) {
  34934. return 0;
  34935. }
  34936. return this._indices.length;
  34937. };
  34938. /**
  34939. * Gets the index buffer array
  34940. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34941. * @returns the index buffer array
  34942. */
  34943. Geometry.prototype.getIndices = function (copyWhenShared) {
  34944. if (!this.isReady()) {
  34945. return null;
  34946. }
  34947. var orig = this._indices;
  34948. if (!copyWhenShared || this._meshes.length === 1) {
  34949. return orig;
  34950. }
  34951. else {
  34952. var len = orig.length;
  34953. var copy = [];
  34954. for (var i = 0; i < len; i++) {
  34955. copy.push(orig[i]);
  34956. }
  34957. return copy;
  34958. }
  34959. };
  34960. /**
  34961. * Gets the index buffer
  34962. * @return the index buffer
  34963. */
  34964. Geometry.prototype.getIndexBuffer = function () {
  34965. if (!this.isReady()) {
  34966. return null;
  34967. }
  34968. return this._indexBuffer;
  34969. };
  34970. /** @ignore */
  34971. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34972. if (effect === void 0) { effect = null; }
  34973. if (!effect || !this._vertexArrayObjects) {
  34974. return;
  34975. }
  34976. if (this._vertexArrayObjects[effect.key]) {
  34977. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34978. delete this._vertexArrayObjects[effect.key];
  34979. }
  34980. };
  34981. /**
  34982. * Release the associated resources for a specific mesh
  34983. * @param mesh defines the source mesh
  34984. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34985. */
  34986. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34987. var meshes = this._meshes;
  34988. var index = meshes.indexOf(mesh);
  34989. if (index === -1) {
  34990. return;
  34991. }
  34992. meshes.splice(index, 1);
  34993. mesh._geometry = null;
  34994. if (meshes.length === 0 && shouldDispose) {
  34995. this.dispose();
  34996. }
  34997. };
  34998. /**
  34999. * Apply current geometry to a given mesh
  35000. * @param mesh defines the mesh to apply geometry to
  35001. */
  35002. Geometry.prototype.applyToMesh = function (mesh) {
  35003. if (mesh._geometry === this) {
  35004. return;
  35005. }
  35006. var previousGeometry = mesh._geometry;
  35007. if (previousGeometry) {
  35008. previousGeometry.releaseForMesh(mesh);
  35009. }
  35010. var meshes = this._meshes;
  35011. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35012. mesh._geometry = this;
  35013. this._scene.pushGeometry(this);
  35014. meshes.push(mesh);
  35015. if (this.isReady()) {
  35016. this._applyToMesh(mesh);
  35017. }
  35018. else {
  35019. mesh._boundingInfo = this._boundingInfo;
  35020. }
  35021. };
  35022. Geometry.prototype.updateExtend = function (data, stride) {
  35023. if (data === void 0) { data = null; }
  35024. if (!data) {
  35025. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35026. }
  35027. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35028. };
  35029. Geometry.prototype._applyToMesh = function (mesh) {
  35030. var numOfMeshes = this._meshes.length;
  35031. // vertexBuffers
  35032. for (var kind in this._vertexBuffers) {
  35033. if (numOfMeshes === 1) {
  35034. this._vertexBuffers[kind].create();
  35035. }
  35036. var buffer = this._vertexBuffers[kind].getBuffer();
  35037. if (buffer)
  35038. buffer.references = numOfMeshes;
  35039. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35040. if (!this._extend) {
  35041. this.updateExtend(this._vertexBuffers[kind].getData());
  35042. }
  35043. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35044. mesh._createGlobalSubMesh(false);
  35045. //bounding info was just created again, world matrix should be applied again.
  35046. mesh._updateBoundingInfo();
  35047. }
  35048. }
  35049. // indexBuffer
  35050. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35051. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35052. }
  35053. if (this._indexBuffer) {
  35054. this._indexBuffer.references = numOfMeshes;
  35055. }
  35056. };
  35057. Geometry.prototype.notifyUpdate = function (kind) {
  35058. if (this.onGeometryUpdated) {
  35059. this.onGeometryUpdated(this, kind);
  35060. }
  35061. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35062. var mesh = _a[_i];
  35063. mesh._markSubMeshesAsAttributesDirty();
  35064. }
  35065. };
  35066. /**
  35067. * Load the geometry if it was flagged as delay loaded
  35068. * @param scene defines the hosting scene
  35069. * @param onLoaded defines a callback called when the geometry is loaded
  35070. */
  35071. Geometry.prototype.load = function (scene, onLoaded) {
  35072. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35073. return;
  35074. }
  35075. if (this.isReady()) {
  35076. if (onLoaded) {
  35077. onLoaded();
  35078. }
  35079. return;
  35080. }
  35081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35082. this._queueLoad(scene, onLoaded);
  35083. };
  35084. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35085. var _this = this;
  35086. if (!this.delayLoadingFile) {
  35087. return;
  35088. }
  35089. scene._addPendingData(this);
  35090. scene._loadFile(this.delayLoadingFile, function (data) {
  35091. if (!_this._delayLoadingFunction) {
  35092. return;
  35093. }
  35094. _this._delayLoadingFunction(JSON.parse(data), _this);
  35095. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35096. _this._delayInfo = [];
  35097. scene._removePendingData(_this);
  35098. var meshes = _this._meshes;
  35099. var numOfMeshes = meshes.length;
  35100. for (var index = 0; index < numOfMeshes; index++) {
  35101. _this._applyToMesh(meshes[index]);
  35102. }
  35103. if (onLoaded) {
  35104. onLoaded();
  35105. }
  35106. }, undefined, true);
  35107. };
  35108. /**
  35109. * Invert the geometry to move from a right handed system to a left handed one.
  35110. */
  35111. Geometry.prototype.toLeftHanded = function () {
  35112. // Flip faces
  35113. var tIndices = this.getIndices(false);
  35114. if (tIndices != null && tIndices.length > 0) {
  35115. for (var i = 0; i < tIndices.length; i += 3) {
  35116. var tTemp = tIndices[i + 0];
  35117. tIndices[i + 0] = tIndices[i + 2];
  35118. tIndices[i + 2] = tTemp;
  35119. }
  35120. this.setIndices(tIndices);
  35121. }
  35122. // Negate position.z
  35123. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35124. if (tPositions != null && tPositions.length > 0) {
  35125. for (var i = 0; i < tPositions.length; i += 3) {
  35126. tPositions[i + 2] = -tPositions[i + 2];
  35127. }
  35128. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35129. }
  35130. // Negate normal.z
  35131. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35132. if (tNormals != null && tNormals.length > 0) {
  35133. for (var i = 0; i < tNormals.length; i += 3) {
  35134. tNormals[i + 2] = -tNormals[i + 2];
  35135. }
  35136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35137. }
  35138. };
  35139. // Cache
  35140. /** @ignore */
  35141. Geometry.prototype._resetPointsArrayCache = function () {
  35142. this._positions = null;
  35143. };
  35144. /** @ignore */
  35145. Geometry.prototype._generatePointsArray = function () {
  35146. if (this._positions)
  35147. return true;
  35148. this._positions = [];
  35149. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35150. if (!data) {
  35151. return false;
  35152. }
  35153. for (var index = 0; index < data.length; index += 3) {
  35154. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35155. }
  35156. return true;
  35157. };
  35158. /**
  35159. * Gets a value indicating if the geometry is disposed
  35160. * @returns true if the geometry was disposed
  35161. */
  35162. Geometry.prototype.isDisposed = function () {
  35163. return this._isDisposed;
  35164. };
  35165. Geometry.prototype._disposeVertexArrayObjects = function () {
  35166. if (this._vertexArrayObjects) {
  35167. for (var kind in this._vertexArrayObjects) {
  35168. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35169. }
  35170. this._vertexArrayObjects = {};
  35171. }
  35172. };
  35173. /**
  35174. * Free all associated resources
  35175. */
  35176. Geometry.prototype.dispose = function () {
  35177. var meshes = this._meshes;
  35178. var numOfMeshes = meshes.length;
  35179. var index;
  35180. for (index = 0; index < numOfMeshes; index++) {
  35181. this.releaseForMesh(meshes[index]);
  35182. }
  35183. this._meshes = [];
  35184. this._disposeVertexArrayObjects();
  35185. for (var kind in this._vertexBuffers) {
  35186. this._vertexBuffers[kind].dispose();
  35187. }
  35188. this._vertexBuffers = {};
  35189. this._totalVertices = 0;
  35190. if (this._indexBuffer) {
  35191. this._engine._releaseBuffer(this._indexBuffer);
  35192. }
  35193. this._indexBuffer = null;
  35194. this._indices = [];
  35195. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35196. this.delayLoadingFile = null;
  35197. this._delayLoadingFunction = null;
  35198. this._delayInfo = [];
  35199. this._boundingInfo = null;
  35200. this._scene.removeGeometry(this);
  35201. this._isDisposed = true;
  35202. };
  35203. /**
  35204. * Clone the current geometry into a new geometry
  35205. * @param id defines the unique ID of the new geometry
  35206. * @returns a new geometry object
  35207. */
  35208. Geometry.prototype.copy = function (id) {
  35209. var vertexData = new BABYLON.VertexData();
  35210. vertexData.indices = [];
  35211. var indices = this.getIndices();
  35212. if (indices) {
  35213. for (var index = 0; index < indices.length; index++) {
  35214. vertexData.indices.push(indices[index]);
  35215. }
  35216. }
  35217. var updatable = false;
  35218. var stopChecking = false;
  35219. var kind;
  35220. for (kind in this._vertexBuffers) {
  35221. // using slice() to make a copy of the array and not just reference it
  35222. var data = this.getVerticesData(kind);
  35223. if (data instanceof Float32Array) {
  35224. vertexData.set(new Float32Array(data), kind);
  35225. }
  35226. else {
  35227. vertexData.set(data.slice(0), kind);
  35228. }
  35229. if (!stopChecking) {
  35230. var vb = this.getVertexBuffer(kind);
  35231. if (vb) {
  35232. updatable = vb.isUpdatable();
  35233. stopChecking = !updatable;
  35234. }
  35235. }
  35236. }
  35237. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35238. geometry.delayLoadState = this.delayLoadState;
  35239. geometry.delayLoadingFile = this.delayLoadingFile;
  35240. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35241. for (kind in this._delayInfo) {
  35242. geometry._delayInfo = geometry._delayInfo || [];
  35243. geometry._delayInfo.push(kind);
  35244. }
  35245. // Bounding info
  35246. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35247. return geometry;
  35248. };
  35249. /**
  35250. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35251. * @return a JSON representation of the current geometry data (without the vertices data)
  35252. */
  35253. Geometry.prototype.serialize = function () {
  35254. var serializationObject = {};
  35255. serializationObject.id = this.id;
  35256. serializationObject.updatable = this._updatable;
  35257. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35258. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35259. }
  35260. return serializationObject;
  35261. };
  35262. Geometry.prototype.toNumberArray = function (origin) {
  35263. if (Array.isArray(origin)) {
  35264. return origin;
  35265. }
  35266. else {
  35267. return Array.prototype.slice.call(origin);
  35268. }
  35269. };
  35270. /**
  35271. * Serialize all vertices data into a JSON oject
  35272. * @returns a JSON representation of the current geometry data
  35273. */
  35274. Geometry.prototype.serializeVerticeData = function () {
  35275. var serializationObject = this.serialize();
  35276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35277. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35278. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35279. serializationObject.positions._updatable = true;
  35280. }
  35281. }
  35282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35283. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35284. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35285. serializationObject.normals._updatable = true;
  35286. }
  35287. }
  35288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35289. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35290. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35291. serializationObject.tangets._updatable = true;
  35292. }
  35293. }
  35294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35295. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35296. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35297. serializationObject.uvs._updatable = true;
  35298. }
  35299. }
  35300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35301. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35302. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35303. serializationObject.uv2s._updatable = true;
  35304. }
  35305. }
  35306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35307. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35308. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35309. serializationObject.uv3s._updatable = true;
  35310. }
  35311. }
  35312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35313. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35314. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35315. serializationObject.uv4s._updatable = true;
  35316. }
  35317. }
  35318. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35319. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35320. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35321. serializationObject.uv5s._updatable = true;
  35322. }
  35323. }
  35324. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35325. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35326. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35327. serializationObject.uv6s._updatable = true;
  35328. }
  35329. }
  35330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35331. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35332. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35333. serializationObject.colors._updatable = true;
  35334. }
  35335. }
  35336. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35337. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35338. serializationObject.matricesIndices._isExpanded = true;
  35339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35340. serializationObject.matricesIndices._updatable = true;
  35341. }
  35342. }
  35343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35344. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35345. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35346. serializationObject.matricesWeights._updatable = true;
  35347. }
  35348. }
  35349. serializationObject.indices = this.toNumberArray(this.getIndices());
  35350. return serializationObject;
  35351. };
  35352. // Statics
  35353. /**
  35354. * Extracts a clone of a mesh geometry
  35355. * @param mesh defines the source mesh
  35356. * @param id defines the unique ID of the new geometry object
  35357. * @returns the new geometry object
  35358. */
  35359. Geometry.ExtractFromMesh = function (mesh, id) {
  35360. var geometry = mesh._geometry;
  35361. if (!geometry) {
  35362. return null;
  35363. }
  35364. return geometry.copy(id);
  35365. };
  35366. /**
  35367. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35368. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35369. * Be aware Math.random() could cause collisions, but:
  35370. * "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"
  35371. * @returns a string containing a new GUID
  35372. */
  35373. Geometry.RandomId = function () {
  35374. return BABYLON.Tools.RandomId();
  35375. };
  35376. /** @ignore */
  35377. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35378. var scene = mesh.getScene();
  35379. // Geometry
  35380. var geometryId = parsedGeometry.geometryId;
  35381. if (geometryId) {
  35382. var geometry = scene.getGeometryByID(geometryId);
  35383. if (geometry) {
  35384. geometry.applyToMesh(mesh);
  35385. }
  35386. }
  35387. else if (parsedGeometry instanceof ArrayBuffer) {
  35388. var binaryInfo = mesh._binaryInfo;
  35389. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35390. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35391. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35392. }
  35393. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35394. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35395. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35396. }
  35397. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35398. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35399. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35400. }
  35401. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35402. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35403. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35404. }
  35405. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35406. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35407. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35408. }
  35409. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35410. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35411. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35412. }
  35413. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35414. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35415. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35416. }
  35417. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35418. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35419. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35420. }
  35421. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35422. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35423. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35424. }
  35425. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35426. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35427. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35428. }
  35429. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35430. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35431. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35432. }
  35433. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35434. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35436. }
  35437. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35438. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35439. mesh.setIndices(indicesData, null);
  35440. }
  35441. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35442. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35443. mesh.subMeshes = [];
  35444. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35445. var materialIndex = subMeshesData[(i * 5) + 0];
  35446. var verticesStart = subMeshesData[(i * 5) + 1];
  35447. var verticesCount = subMeshesData[(i * 5) + 2];
  35448. var indexStart = subMeshesData[(i * 5) + 3];
  35449. var indexCount = subMeshesData[(i * 5) + 4];
  35450. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35451. }
  35452. }
  35453. }
  35454. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35455. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35456. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35457. if (parsedGeometry.tangents) {
  35458. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35459. }
  35460. if (parsedGeometry.uvs) {
  35461. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35462. }
  35463. if (parsedGeometry.uvs2) {
  35464. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35465. }
  35466. if (parsedGeometry.uvs3) {
  35467. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35468. }
  35469. if (parsedGeometry.uvs4) {
  35470. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35471. }
  35472. if (parsedGeometry.uvs5) {
  35473. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35474. }
  35475. if (parsedGeometry.uvs6) {
  35476. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35477. }
  35478. if (parsedGeometry.colors) {
  35479. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35480. }
  35481. if (parsedGeometry.matricesIndices) {
  35482. if (!parsedGeometry.matricesIndices._isExpanded) {
  35483. var floatIndices = [];
  35484. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35485. var matricesIndex = parsedGeometry.matricesIndices[i];
  35486. floatIndices.push(matricesIndex & 0x000000FF);
  35487. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35488. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35489. floatIndices.push(matricesIndex >> 24);
  35490. }
  35491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35492. }
  35493. else {
  35494. delete parsedGeometry.matricesIndices._isExpanded;
  35495. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35496. }
  35497. }
  35498. if (parsedGeometry.matricesIndicesExtra) {
  35499. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35500. var floatIndices = [];
  35501. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35502. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35503. floatIndices.push(matricesIndex & 0x000000FF);
  35504. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35505. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35506. floatIndices.push(matricesIndex >> 24);
  35507. }
  35508. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35509. }
  35510. else {
  35511. delete parsedGeometry.matricesIndices._isExpanded;
  35512. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35513. }
  35514. }
  35515. if (parsedGeometry.matricesWeights) {
  35516. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35517. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35518. }
  35519. if (parsedGeometry.matricesWeightsExtra) {
  35520. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35521. }
  35522. mesh.setIndices(parsedGeometry.indices, null);
  35523. }
  35524. // SubMeshes
  35525. if (parsedGeometry.subMeshes) {
  35526. mesh.subMeshes = [];
  35527. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35528. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35529. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35530. }
  35531. }
  35532. // Flat shading
  35533. if (mesh._shouldGenerateFlatShading) {
  35534. mesh.convertToFlatShadedMesh();
  35535. delete mesh._shouldGenerateFlatShading;
  35536. }
  35537. // Update
  35538. mesh.computeWorldMatrix(true);
  35539. // Octree
  35540. var sceneOctree = scene.selectionOctree;
  35541. if (sceneOctree !== undefined && sceneOctree !== null) {
  35542. sceneOctree.addMesh(mesh);
  35543. }
  35544. };
  35545. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35546. var epsilon = 1e-3;
  35547. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35548. return;
  35549. }
  35550. var noInfluenceBoneIndex = 0.0;
  35551. if (parsedGeometry.skeletonId > -1) {
  35552. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35553. if (!skeleton) {
  35554. return;
  35555. }
  35556. noInfluenceBoneIndex = skeleton.bones.length;
  35557. }
  35558. else {
  35559. return;
  35560. }
  35561. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35562. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35563. var matricesWeights = parsedGeometry.matricesWeights;
  35564. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35565. var influencers = parsedGeometry.numBoneInfluencer;
  35566. var size = matricesWeights.length;
  35567. for (var i = 0; i < size; i += 4) {
  35568. var weight = 0.0;
  35569. var firstZeroWeight = -1;
  35570. for (var j = 0; j < 4; j++) {
  35571. var w = matricesWeights[i + j];
  35572. weight += w;
  35573. if (w < epsilon && firstZeroWeight < 0) {
  35574. firstZeroWeight = j;
  35575. }
  35576. }
  35577. if (matricesWeightsExtra) {
  35578. for (var j = 0; j < 4; j++) {
  35579. var w = matricesWeightsExtra[i + j];
  35580. weight += w;
  35581. if (w < epsilon && firstZeroWeight < 0) {
  35582. firstZeroWeight = j + 4;
  35583. }
  35584. }
  35585. }
  35586. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35587. firstZeroWeight = influencers - 1;
  35588. }
  35589. if (weight > epsilon) {
  35590. var mweight = 1.0 / weight;
  35591. for (var j = 0; j < 4; j++) {
  35592. matricesWeights[i + j] *= mweight;
  35593. }
  35594. if (matricesWeightsExtra) {
  35595. for (var j = 0; j < 4; j++) {
  35596. matricesWeightsExtra[i + j] *= mweight;
  35597. }
  35598. }
  35599. }
  35600. else {
  35601. if (firstZeroWeight >= 4) {
  35602. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35603. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35604. }
  35605. else {
  35606. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35607. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35608. }
  35609. }
  35610. }
  35611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35612. if (parsedGeometry.matricesWeightsExtra) {
  35613. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35614. }
  35615. };
  35616. /**
  35617. * Create a new geometry from persisted data (Using .babylon file format)
  35618. * @param parsedVertexData defines the persisted data
  35619. * @param scene defines the hosting scene
  35620. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35621. * @returns the new geometry object
  35622. */
  35623. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35624. if (scene.getGeometryByID(parsedVertexData.id)) {
  35625. return null; // null since geometry could be something else than a box...
  35626. }
  35627. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35628. if (BABYLON.Tags) {
  35629. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35630. }
  35631. if (parsedVertexData.delayLoadingFile) {
  35632. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35633. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35634. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35635. geometry._delayInfo = [];
  35636. if (parsedVertexData.hasUVs) {
  35637. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35638. }
  35639. if (parsedVertexData.hasUVs2) {
  35640. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35641. }
  35642. if (parsedVertexData.hasUVs3) {
  35643. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35644. }
  35645. if (parsedVertexData.hasUVs4) {
  35646. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35647. }
  35648. if (parsedVertexData.hasUVs5) {
  35649. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35650. }
  35651. if (parsedVertexData.hasUVs6) {
  35652. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35653. }
  35654. if (parsedVertexData.hasColors) {
  35655. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35656. }
  35657. if (parsedVertexData.hasMatricesIndices) {
  35658. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35659. }
  35660. if (parsedVertexData.hasMatricesWeights) {
  35661. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35662. }
  35663. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35664. }
  35665. else {
  35666. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35667. }
  35668. scene.pushGeometry(geometry, true);
  35669. return geometry;
  35670. };
  35671. return Geometry;
  35672. }());
  35673. BABYLON.Geometry = Geometry;
  35674. // Primitives
  35675. /// Abstract class
  35676. /**
  35677. * Abstract class used to provide common services for all typed geometries
  35678. */
  35679. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35680. __extends(_PrimitiveGeometry, _super);
  35681. /**
  35682. * Creates a new typed geometry
  35683. * @param id defines the unique ID of the geometry
  35684. * @param scene defines the hosting scene
  35685. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35686. * @param mesh defines the hosting mesh (can be null)
  35687. */
  35688. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35689. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35690. if (mesh === void 0) { mesh = null; }
  35691. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35692. _this._canBeRegenerated = _canBeRegenerated;
  35693. _this._beingRegenerated = true;
  35694. _this.regenerate();
  35695. _this._beingRegenerated = false;
  35696. return _this;
  35697. }
  35698. /**
  35699. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35700. * @returns true if the geometry can be regenerated
  35701. */
  35702. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35703. return this._canBeRegenerated;
  35704. };
  35705. /**
  35706. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35707. */
  35708. _PrimitiveGeometry.prototype.regenerate = function () {
  35709. if (!this._canBeRegenerated) {
  35710. return;
  35711. }
  35712. this._beingRegenerated = true;
  35713. this.setAllVerticesData(this._regenerateVertexData(), false);
  35714. this._beingRegenerated = false;
  35715. };
  35716. /**
  35717. * Clone the geometry
  35718. * @param id defines the unique ID of the new geometry
  35719. * @returns the new geometry
  35720. */
  35721. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35722. return _super.prototype.copy.call(this, id);
  35723. };
  35724. // overrides
  35725. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35726. if (!this._beingRegenerated) {
  35727. return;
  35728. }
  35729. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35730. };
  35731. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35732. if (!this._beingRegenerated) {
  35733. return;
  35734. }
  35735. _super.prototype.setVerticesData.call(this, kind, data, false);
  35736. };
  35737. // to override
  35738. /** @ignore */
  35739. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35740. throw new Error("Abstract method");
  35741. };
  35742. _PrimitiveGeometry.prototype.copy = function (id) {
  35743. throw new Error("Must be overriden in sub-classes.");
  35744. };
  35745. _PrimitiveGeometry.prototype.serialize = function () {
  35746. var serializationObject = _super.prototype.serialize.call(this);
  35747. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35748. return serializationObject;
  35749. };
  35750. return _PrimitiveGeometry;
  35751. }(Geometry));
  35752. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35753. /**
  35754. * Creates a ribbon geometry
  35755. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35756. */
  35757. var RibbonGeometry = /** @class */ (function (_super) {
  35758. __extends(RibbonGeometry, _super);
  35759. /**
  35760. * Creates a ribbon geometry
  35761. * @param id defines the unique ID of the geometry
  35762. * @param scene defines the hosting scene
  35763. * @param pathArray defines the array of paths to use
  35764. * @param closeArray defines if the last path and the first path must be joined
  35765. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35766. * @param offset defines the offset between points
  35767. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35768. * @param mesh defines the hosting mesh (can be null)
  35769. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35770. */
  35771. function RibbonGeometry(id, scene,
  35772. /**
  35773. * Defines the array of paths to use
  35774. */
  35775. pathArray,
  35776. /**
  35777. * Defines if the last and first points of each path in your pathArray must be joined
  35778. */
  35779. closeArray,
  35780. /**
  35781. * Defines if the last and first points of each path in your pathArray must be joined
  35782. */
  35783. closePath,
  35784. /**
  35785. * Defines the offset between points
  35786. */
  35787. offset, canBeRegenerated, mesh,
  35788. /**
  35789. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35790. */
  35791. side) {
  35792. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35793. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35794. _this.pathArray = pathArray;
  35795. _this.closeArray = closeArray;
  35796. _this.closePath = closePath;
  35797. _this.offset = offset;
  35798. _this.side = side;
  35799. return _this;
  35800. }
  35801. /** @ignore */
  35802. RibbonGeometry.prototype._regenerateVertexData = function () {
  35803. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35804. };
  35805. RibbonGeometry.prototype.copy = function (id) {
  35806. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35807. };
  35808. return RibbonGeometry;
  35809. }(_PrimitiveGeometry));
  35810. BABYLON.RibbonGeometry = RibbonGeometry;
  35811. /**
  35812. * Creates a box geometry
  35813. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35814. */
  35815. var BoxGeometry = /** @class */ (function (_super) {
  35816. __extends(BoxGeometry, _super);
  35817. /**
  35818. * Creates a box geometry
  35819. * @param id defines the unique ID of the geometry
  35820. * @param scene defines the hosting scene
  35821. * @param size defines the zise of the box (width, height and depth are the same)
  35822. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35823. * @param mesh defines the hosting mesh (can be null)
  35824. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35825. */
  35826. function BoxGeometry(id, scene,
  35827. /**
  35828. * Defines the zise of the box (width, height and depth are the same)
  35829. */
  35830. size, canBeRegenerated, mesh,
  35831. /**
  35832. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35833. */
  35834. side) {
  35835. if (mesh === void 0) { mesh = null; }
  35836. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35837. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35838. _this.size = size;
  35839. _this.side = side;
  35840. return _this;
  35841. }
  35842. BoxGeometry.prototype._regenerateVertexData = function () {
  35843. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35844. };
  35845. BoxGeometry.prototype.copy = function (id) {
  35846. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35847. };
  35848. BoxGeometry.prototype.serialize = function () {
  35849. var serializationObject = _super.prototype.serialize.call(this);
  35850. serializationObject.size = this.size;
  35851. return serializationObject;
  35852. };
  35853. BoxGeometry.Parse = function (parsedBox, scene) {
  35854. if (scene.getGeometryByID(parsedBox.id)) {
  35855. return null; // null since geometry could be something else than a box...
  35856. }
  35857. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35858. if (BABYLON.Tags) {
  35859. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35860. }
  35861. scene.pushGeometry(box, true);
  35862. return box;
  35863. };
  35864. return BoxGeometry;
  35865. }(_PrimitiveGeometry));
  35866. BABYLON.BoxGeometry = BoxGeometry;
  35867. /**
  35868. * Creates a sphere geometry
  35869. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35870. */
  35871. var SphereGeometry = /** @class */ (function (_super) {
  35872. __extends(SphereGeometry, _super);
  35873. /**
  35874. * Create a new sphere geometry
  35875. * @param id defines the unique ID of the geometry
  35876. * @param scene defines the hosting scene
  35877. * @param segments defines the number of segments to use to create the sphere
  35878. * @param diameter defines the diameter of the sphere
  35879. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35880. * @param mesh defines the hosting mesh (can be null)
  35881. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35882. */
  35883. function SphereGeometry(id, scene,
  35884. /**
  35885. * Defines the number of segments to use to create the sphere
  35886. */
  35887. segments,
  35888. /**
  35889. * Defines the diameter of the sphere
  35890. */
  35891. diameter, canBeRegenerated, mesh,
  35892. /**
  35893. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35894. */
  35895. side) {
  35896. if (mesh === void 0) { mesh = null; }
  35897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35898. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35899. _this.segments = segments;
  35900. _this.diameter = diameter;
  35901. _this.side = side;
  35902. return _this;
  35903. }
  35904. SphereGeometry.prototype._regenerateVertexData = function () {
  35905. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35906. };
  35907. SphereGeometry.prototype.copy = function (id) {
  35908. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35909. };
  35910. SphereGeometry.prototype.serialize = function () {
  35911. var serializationObject = _super.prototype.serialize.call(this);
  35912. serializationObject.segments = this.segments;
  35913. serializationObject.diameter = this.diameter;
  35914. return serializationObject;
  35915. };
  35916. SphereGeometry.Parse = function (parsedSphere, scene) {
  35917. if (scene.getGeometryByID(parsedSphere.id)) {
  35918. return null; // null since geometry could be something else than a sphere...
  35919. }
  35920. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35921. if (BABYLON.Tags) {
  35922. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35923. }
  35924. scene.pushGeometry(sphere, true);
  35925. return sphere;
  35926. };
  35927. return SphereGeometry;
  35928. }(_PrimitiveGeometry));
  35929. BABYLON.SphereGeometry = SphereGeometry;
  35930. /**
  35931. * Creates a disc geometry
  35932. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35933. */
  35934. var DiscGeometry = /** @class */ (function (_super) {
  35935. __extends(DiscGeometry, _super);
  35936. /**
  35937. * Creates a new disc geometry
  35938. * @param id defines the unique ID of the geometry
  35939. * @param scene defines the hosting scene
  35940. * @param radius defines the radius of the disc
  35941. * @param tessellation defines the tesselation factor to apply to the disc
  35942. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35943. * @param mesh defines the hosting mesh (can be null)
  35944. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35945. */
  35946. function DiscGeometry(id, scene,
  35947. /**
  35948. * Defines the radius of the disc
  35949. */
  35950. radius,
  35951. /**
  35952. * Defines the tesselation factor to apply to the disc
  35953. */
  35954. tessellation, canBeRegenerated, mesh,
  35955. /**
  35956. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35957. */
  35958. side) {
  35959. if (mesh === void 0) { mesh = null; }
  35960. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35961. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35962. _this.radius = radius;
  35963. _this.tessellation = tessellation;
  35964. _this.side = side;
  35965. return _this;
  35966. }
  35967. DiscGeometry.prototype._regenerateVertexData = function () {
  35968. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35969. };
  35970. DiscGeometry.prototype.copy = function (id) {
  35971. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35972. };
  35973. return DiscGeometry;
  35974. }(_PrimitiveGeometry));
  35975. BABYLON.DiscGeometry = DiscGeometry;
  35976. /**
  35977. * Creates a new cylinder geometry
  35978. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35979. */
  35980. var CylinderGeometry = /** @class */ (function (_super) {
  35981. __extends(CylinderGeometry, _super);
  35982. /**
  35983. * Creates a new cylinder geometry
  35984. * @param id defines the unique ID of the geometry
  35985. * @param scene defines the hosting scene
  35986. * @param height defines the height of the cylinder
  35987. * @param diameterTop defines the diameter of the cylinder's top cap
  35988. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35989. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35990. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35991. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35992. * @param mesh defines the hosting mesh (can be null)
  35993. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35994. */
  35995. function CylinderGeometry(id, scene,
  35996. /**
  35997. * Defines the height of the cylinder
  35998. */
  35999. height,
  36000. /**
  36001. * Defines the diameter of the cylinder's top cap
  36002. */
  36003. diameterTop,
  36004. /**
  36005. * Defines the diameter of the cylinder's bottom cap
  36006. */
  36007. diameterBottom,
  36008. /**
  36009. * Defines the tessellation factor to apply to the cylinder
  36010. */
  36011. tessellation,
  36012. /**
  36013. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36014. */
  36015. subdivisions, canBeRegenerated, mesh,
  36016. /**
  36017. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36018. */
  36019. side) {
  36020. if (subdivisions === void 0) { subdivisions = 1; }
  36021. if (mesh === void 0) { mesh = null; }
  36022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36024. _this.height = height;
  36025. _this.diameterTop = diameterTop;
  36026. _this.diameterBottom = diameterBottom;
  36027. _this.tessellation = tessellation;
  36028. _this.subdivisions = subdivisions;
  36029. _this.side = side;
  36030. return _this;
  36031. }
  36032. CylinderGeometry.prototype._regenerateVertexData = function () {
  36033. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36034. };
  36035. CylinderGeometry.prototype.copy = function (id) {
  36036. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36037. };
  36038. CylinderGeometry.prototype.serialize = function () {
  36039. var serializationObject = _super.prototype.serialize.call(this);
  36040. serializationObject.height = this.height;
  36041. serializationObject.diameterTop = this.diameterTop;
  36042. serializationObject.diameterBottom = this.diameterBottom;
  36043. serializationObject.tessellation = this.tessellation;
  36044. return serializationObject;
  36045. };
  36046. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36047. if (scene.getGeometryByID(parsedCylinder.id)) {
  36048. return null; // null since geometry could be something else than a cylinder...
  36049. }
  36050. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36051. if (BABYLON.Tags) {
  36052. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36053. }
  36054. scene.pushGeometry(cylinder, true);
  36055. return cylinder;
  36056. };
  36057. return CylinderGeometry;
  36058. }(_PrimitiveGeometry));
  36059. BABYLON.CylinderGeometry = CylinderGeometry;
  36060. /**
  36061. * Creates a new torus geometry
  36062. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36063. */
  36064. var TorusGeometry = /** @class */ (function (_super) {
  36065. __extends(TorusGeometry, _super);
  36066. /**
  36067. * Creates a new torus geometry
  36068. * @param id defines the unique ID of the geometry
  36069. * @param scene defines the hosting scene
  36070. * @param diameter defines the diameter of the torus
  36071. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36072. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36073. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36074. * @param mesh defines the hosting mesh (can be null)
  36075. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36076. */
  36077. function TorusGeometry(id, scene,
  36078. /**
  36079. * Defines the diameter of the torus
  36080. */
  36081. diameter,
  36082. /**
  36083. * Defines the thickness of the torus (ie. internal diameter)
  36084. */
  36085. thickness,
  36086. /**
  36087. * Defines the tesselation factor to apply to the torus
  36088. */
  36089. tessellation, canBeRegenerated, mesh,
  36090. /**
  36091. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36092. */
  36093. side) {
  36094. if (mesh === void 0) { mesh = null; }
  36095. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36096. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36097. _this.diameter = diameter;
  36098. _this.thickness = thickness;
  36099. _this.tessellation = tessellation;
  36100. _this.side = side;
  36101. return _this;
  36102. }
  36103. TorusGeometry.prototype._regenerateVertexData = function () {
  36104. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36105. };
  36106. TorusGeometry.prototype.copy = function (id) {
  36107. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36108. };
  36109. TorusGeometry.prototype.serialize = function () {
  36110. var serializationObject = _super.prototype.serialize.call(this);
  36111. serializationObject.diameter = this.diameter;
  36112. serializationObject.thickness = this.thickness;
  36113. serializationObject.tessellation = this.tessellation;
  36114. return serializationObject;
  36115. };
  36116. TorusGeometry.Parse = function (parsedTorus, scene) {
  36117. if (scene.getGeometryByID(parsedTorus.id)) {
  36118. return null; // null since geometry could be something else than a torus...
  36119. }
  36120. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36121. if (BABYLON.Tags) {
  36122. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36123. }
  36124. scene.pushGeometry(torus, true);
  36125. return torus;
  36126. };
  36127. return TorusGeometry;
  36128. }(_PrimitiveGeometry));
  36129. BABYLON.TorusGeometry = TorusGeometry;
  36130. /**
  36131. * Creates a new ground geometry
  36132. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36133. */
  36134. var GroundGeometry = /** @class */ (function (_super) {
  36135. __extends(GroundGeometry, _super);
  36136. /**
  36137. * Creates a new ground geometry
  36138. * @param id defines the unique ID of the geometry
  36139. * @param scene defines the hosting scene
  36140. * @param width defines the width of the ground
  36141. * @param height defines the height of the ground
  36142. * @param subdivisions defines the subdivisions to apply to the ground
  36143. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36144. * @param mesh defines the hosting mesh (can be null)
  36145. */
  36146. function GroundGeometry(id, scene,
  36147. /**
  36148. * Defines the width of the ground
  36149. */
  36150. width,
  36151. /**
  36152. * Defines the height of the ground
  36153. */
  36154. height,
  36155. /**
  36156. * Defines the subdivisions to apply to the ground
  36157. */
  36158. subdivisions, canBeRegenerated, mesh) {
  36159. if (mesh === void 0) { mesh = null; }
  36160. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36161. _this.width = width;
  36162. _this.height = height;
  36163. _this.subdivisions = subdivisions;
  36164. return _this;
  36165. }
  36166. GroundGeometry.prototype._regenerateVertexData = function () {
  36167. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36168. };
  36169. GroundGeometry.prototype.copy = function (id) {
  36170. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36171. };
  36172. GroundGeometry.prototype.serialize = function () {
  36173. var serializationObject = _super.prototype.serialize.call(this);
  36174. serializationObject.width = this.width;
  36175. serializationObject.height = this.height;
  36176. serializationObject.subdivisions = this.subdivisions;
  36177. return serializationObject;
  36178. };
  36179. GroundGeometry.Parse = function (parsedGround, scene) {
  36180. if (scene.getGeometryByID(parsedGround.id)) {
  36181. return null; // null since geometry could be something else than a ground...
  36182. }
  36183. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36184. if (BABYLON.Tags) {
  36185. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36186. }
  36187. scene.pushGeometry(ground, true);
  36188. return ground;
  36189. };
  36190. return GroundGeometry;
  36191. }(_PrimitiveGeometry));
  36192. BABYLON.GroundGeometry = GroundGeometry;
  36193. /**
  36194. * Creates a tiled ground geometry
  36195. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36196. */
  36197. var TiledGroundGeometry = /** @class */ (function (_super) {
  36198. __extends(TiledGroundGeometry, _super);
  36199. /**
  36200. * Creates a tiled ground geometry
  36201. * @param id defines the unique ID of the geometry
  36202. * @param scene defines the hosting scene
  36203. * @param xmin defines the minimum value on X axis
  36204. * @param zmin defines the minimum value on Z axis
  36205. * @param xmax defines the maximum value on X axis
  36206. * @param zmax defines the maximum value on Z axis
  36207. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36208. * @param precision defines the precision to use when computing the tiles
  36209. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36210. * @param mesh defines the hosting mesh (can be null)
  36211. */
  36212. function TiledGroundGeometry(id, scene,
  36213. /**
  36214. * Defines the minimum value on X axis
  36215. */
  36216. xmin,
  36217. /**
  36218. * Defines the minimum value on Z axis
  36219. */
  36220. zmin,
  36221. /**
  36222. * Defines the maximum value on X axis
  36223. */
  36224. xmax,
  36225. /**
  36226. * Defines the maximum value on Z axis
  36227. */
  36228. zmax,
  36229. /**
  36230. * Defines the subdivisions to apply to the ground
  36231. */
  36232. subdivisions,
  36233. /**
  36234. * Defines the precision to use when computing the tiles
  36235. */
  36236. precision, canBeRegenerated, mesh) {
  36237. if (mesh === void 0) { mesh = null; }
  36238. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36239. _this.xmin = xmin;
  36240. _this.zmin = zmin;
  36241. _this.xmax = xmax;
  36242. _this.zmax = zmax;
  36243. _this.subdivisions = subdivisions;
  36244. _this.precision = precision;
  36245. return _this;
  36246. }
  36247. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36248. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36249. };
  36250. TiledGroundGeometry.prototype.copy = function (id) {
  36251. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36252. };
  36253. return TiledGroundGeometry;
  36254. }(_PrimitiveGeometry));
  36255. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36256. /**
  36257. * Creates a plane geometry
  36258. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36259. */
  36260. var PlaneGeometry = /** @class */ (function (_super) {
  36261. __extends(PlaneGeometry, _super);
  36262. /**
  36263. * Creates a plane geometry
  36264. * @param id defines the unique ID of the geometry
  36265. * @param scene defines the hosting scene
  36266. * @param size defines the size of the plane (width === height)
  36267. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36268. * @param mesh defines the hosting mesh (can be null)
  36269. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36270. */
  36271. function PlaneGeometry(id, scene,
  36272. /**
  36273. * Defines the size of the plane (width === height)
  36274. */
  36275. size, canBeRegenerated, mesh,
  36276. /**
  36277. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36278. */
  36279. side) {
  36280. if (mesh === void 0) { mesh = null; }
  36281. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36282. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36283. _this.size = size;
  36284. _this.side = side;
  36285. return _this;
  36286. }
  36287. PlaneGeometry.prototype._regenerateVertexData = function () {
  36288. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36289. };
  36290. PlaneGeometry.prototype.copy = function (id) {
  36291. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36292. };
  36293. PlaneGeometry.prototype.serialize = function () {
  36294. var serializationObject = _super.prototype.serialize.call(this);
  36295. serializationObject.size = this.size;
  36296. return serializationObject;
  36297. };
  36298. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36299. if (scene.getGeometryByID(parsedPlane.id)) {
  36300. return null; // null since geometry could be something else than a ground...
  36301. }
  36302. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36303. if (BABYLON.Tags) {
  36304. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36305. }
  36306. scene.pushGeometry(plane, true);
  36307. return plane;
  36308. };
  36309. return PlaneGeometry;
  36310. }(_PrimitiveGeometry));
  36311. BABYLON.PlaneGeometry = PlaneGeometry;
  36312. /**
  36313. * Creates a torus knot geometry
  36314. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36315. */
  36316. var TorusKnotGeometry = /** @class */ (function (_super) {
  36317. __extends(TorusKnotGeometry, _super);
  36318. /**
  36319. * Creates a torus knot geometry
  36320. * @param id defines the unique ID of the geometry
  36321. * @param scene defines the hosting scene
  36322. * @param radius defines the radius of the torus knot
  36323. * @param tube defines the thickness of the torus knot tube
  36324. * @param radialSegments defines the number of radial segments
  36325. * @param tubularSegments defines the number of tubular segments
  36326. * @param p defines the first number of windings
  36327. * @param q defines the second number of windings
  36328. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36329. * @param mesh defines the hosting mesh (can be null)
  36330. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36331. */
  36332. function TorusKnotGeometry(id, scene,
  36333. /**
  36334. * Defines the radius of the torus knot
  36335. */
  36336. radius,
  36337. /**
  36338. * Defines the thickness of the torus knot tube
  36339. */
  36340. tube,
  36341. /**
  36342. * Defines the number of radial segments
  36343. */
  36344. radialSegments,
  36345. /**
  36346. * Defines the number of tubular segments
  36347. */
  36348. tubularSegments,
  36349. /**
  36350. * Defines the first number of windings
  36351. */
  36352. p,
  36353. /**
  36354. * Defines the second number of windings
  36355. */
  36356. q, canBeRegenerated, mesh,
  36357. /**
  36358. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36359. */
  36360. side) {
  36361. if (mesh === void 0) { mesh = null; }
  36362. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36363. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36364. _this.radius = radius;
  36365. _this.tube = tube;
  36366. _this.radialSegments = radialSegments;
  36367. _this.tubularSegments = tubularSegments;
  36368. _this.p = p;
  36369. _this.q = q;
  36370. _this.side = side;
  36371. return _this;
  36372. }
  36373. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36374. 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 });
  36375. };
  36376. TorusKnotGeometry.prototype.copy = function (id) {
  36377. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36378. };
  36379. TorusKnotGeometry.prototype.serialize = function () {
  36380. var serializationObject = _super.prototype.serialize.call(this);
  36381. serializationObject.radius = this.radius;
  36382. serializationObject.tube = this.tube;
  36383. serializationObject.radialSegments = this.radialSegments;
  36384. serializationObject.tubularSegments = this.tubularSegments;
  36385. serializationObject.p = this.p;
  36386. serializationObject.q = this.q;
  36387. return serializationObject;
  36388. };
  36389. ;
  36390. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36391. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36392. return null; // null since geometry could be something else than a ground...
  36393. }
  36394. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36395. if (BABYLON.Tags) {
  36396. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36397. }
  36398. scene.pushGeometry(torusKnot, true);
  36399. return torusKnot;
  36400. };
  36401. return TorusKnotGeometry;
  36402. }(_PrimitiveGeometry));
  36403. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36404. //}
  36405. })(BABYLON || (BABYLON = {}));
  36406. //# sourceMappingURL=babylon.geometry.js.map
  36407. var BABYLON;
  36408. (function (BABYLON) {
  36409. /**
  36410. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36411. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36412. */
  36413. var PostProcessManager = /** @class */ (function () {
  36414. /**
  36415. * Creates a new instance of @see PostProcess
  36416. * @param scene The scene that the post process is associated with.
  36417. */
  36418. function PostProcessManager(scene) {
  36419. this._vertexBuffers = {};
  36420. this._scene = scene;
  36421. }
  36422. PostProcessManager.prototype._prepareBuffers = function () {
  36423. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36424. return;
  36425. }
  36426. // VBO
  36427. var vertices = [];
  36428. vertices.push(1, 1);
  36429. vertices.push(-1, 1);
  36430. vertices.push(-1, -1);
  36431. vertices.push(1, -1);
  36432. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36433. this._buildIndexBuffer();
  36434. };
  36435. PostProcessManager.prototype._buildIndexBuffer = function () {
  36436. // Indices
  36437. var indices = [];
  36438. indices.push(0);
  36439. indices.push(1);
  36440. indices.push(2);
  36441. indices.push(0);
  36442. indices.push(2);
  36443. indices.push(3);
  36444. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36445. };
  36446. /**
  36447. * Rebuilds the vertex buffers of the manager.
  36448. */
  36449. PostProcessManager.prototype._rebuild = function () {
  36450. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36451. if (!vb) {
  36452. return;
  36453. }
  36454. vb._rebuild();
  36455. this._buildIndexBuffer();
  36456. };
  36457. // Methods
  36458. /**
  36459. * Prepares a frame to be run through a post process.
  36460. * @param sourceTexture The input texture to the post procesess. (default: null)
  36461. * @param postProcesses An array of post processes to be run. (default: null)
  36462. * @returns True if the post processes were able to be run.
  36463. */
  36464. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36465. if (sourceTexture === void 0) { sourceTexture = null; }
  36466. if (postProcesses === void 0) { postProcesses = null; }
  36467. var camera = this._scene.activeCamera;
  36468. if (!camera) {
  36469. return false;
  36470. }
  36471. var postProcesses = postProcesses || camera._postProcesses;
  36472. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36473. return false;
  36474. }
  36475. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36476. return true;
  36477. };
  36478. /**
  36479. * Manually render a set of post processes to a texture.
  36480. * @param postProcesses An array of post processes to be run.
  36481. * @param targetTexture The target texture to render to.
  36482. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36483. */
  36484. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36485. if (targetTexture === void 0) { targetTexture = null; }
  36486. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36487. var engine = this._scene.getEngine();
  36488. for (var index = 0; index < postProcesses.length; index++) {
  36489. if (index < postProcesses.length - 1) {
  36490. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36491. }
  36492. else {
  36493. if (targetTexture) {
  36494. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36495. }
  36496. else {
  36497. engine.restoreDefaultFramebuffer();
  36498. }
  36499. }
  36500. var pp = postProcesses[index];
  36501. var effect = pp.apply();
  36502. if (effect) {
  36503. pp.onBeforeRenderObservable.notifyObservers(effect);
  36504. // VBOs
  36505. this._prepareBuffers();
  36506. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36507. // Draw order
  36508. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36509. pp.onAfterRenderObservable.notifyObservers(effect);
  36510. }
  36511. }
  36512. // Restore depth buffer
  36513. engine.setDepthBuffer(true);
  36514. engine.setDepthWrite(true);
  36515. };
  36516. /**
  36517. * Finalize the result of the output of the postprocesses.
  36518. * @param doNotPresent If true the result will not be displayed to the screen.
  36519. * @param targetTexture The target texture to render to.
  36520. * @param faceIndex The index of the face to bind the target texture to.
  36521. * @param postProcesses The array of post processes to render.
  36522. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36523. */
  36524. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36525. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36526. var camera = this._scene.activeCamera;
  36527. if (!camera) {
  36528. return;
  36529. }
  36530. postProcesses = postProcesses || camera._postProcesses;
  36531. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36532. return;
  36533. }
  36534. var engine = this._scene.getEngine();
  36535. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36536. if (index < len - 1) {
  36537. postProcesses[index + 1].activate(camera, targetTexture);
  36538. }
  36539. else {
  36540. if (targetTexture) {
  36541. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36542. }
  36543. else {
  36544. engine.restoreDefaultFramebuffer();
  36545. }
  36546. }
  36547. if (doNotPresent) {
  36548. break;
  36549. }
  36550. var pp = postProcesses[index];
  36551. var effect = pp.apply();
  36552. if (effect) {
  36553. pp.onBeforeRenderObservable.notifyObservers(effect);
  36554. // VBOs
  36555. this._prepareBuffers();
  36556. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36557. // Draw order
  36558. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36559. pp.onAfterRenderObservable.notifyObservers(effect);
  36560. }
  36561. }
  36562. // Restore states
  36563. engine.setDepthBuffer(true);
  36564. engine.setDepthWrite(true);
  36565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36566. };
  36567. /**
  36568. * Disposes of the post process manager.
  36569. */
  36570. PostProcessManager.prototype.dispose = function () {
  36571. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36572. if (buffer) {
  36573. buffer.dispose();
  36574. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36575. }
  36576. if (this._indexBuffer) {
  36577. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36578. this._indexBuffer = null;
  36579. }
  36580. };
  36581. return PostProcessManager;
  36582. }());
  36583. BABYLON.PostProcessManager = PostProcessManager;
  36584. })(BABYLON || (BABYLON = {}));
  36585. //# sourceMappingURL=babylon.postProcessManager.js.map
  36586. var BABYLON;
  36587. (function (BABYLON) {
  36588. /**
  36589. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36590. */
  36591. var PerformanceMonitor = /** @class */ (function () {
  36592. /**
  36593. * constructor
  36594. * @param frameSampleSize The number of samples required to saturate the sliding window
  36595. */
  36596. function PerformanceMonitor(frameSampleSize) {
  36597. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36598. this._enabled = true;
  36599. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36600. }
  36601. /**
  36602. * Samples current frame
  36603. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36604. */
  36605. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36606. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36607. if (!this._enabled)
  36608. return;
  36609. if (this._lastFrameTimeMs != null) {
  36610. var dt = timeMs - this._lastFrameTimeMs;
  36611. this._rollingFrameTime.add(dt);
  36612. }
  36613. this._lastFrameTimeMs = timeMs;
  36614. };
  36615. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36616. /**
  36617. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36618. * @return Average frame time in milliseconds
  36619. */
  36620. get: function () {
  36621. return this._rollingFrameTime.average;
  36622. },
  36623. enumerable: true,
  36624. configurable: true
  36625. });
  36626. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36627. /**
  36628. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36629. * @return Frame time variance in milliseconds squared
  36630. */
  36631. get: function () {
  36632. return this._rollingFrameTime.variance;
  36633. },
  36634. enumerable: true,
  36635. configurable: true
  36636. });
  36637. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36638. /**
  36639. * Returns the frame time of the most recent frame
  36640. * @return Frame time in milliseconds
  36641. */
  36642. get: function () {
  36643. return this._rollingFrameTime.history(0);
  36644. },
  36645. enumerable: true,
  36646. configurable: true
  36647. });
  36648. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36649. /**
  36650. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36651. * @return Framerate in frames per second
  36652. */
  36653. get: function () {
  36654. return 1000.0 / this._rollingFrameTime.average;
  36655. },
  36656. enumerable: true,
  36657. configurable: true
  36658. });
  36659. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36660. /**
  36661. * Returns the average framerate in frames per second using the most recent frame time
  36662. * @return Framerate in frames per second
  36663. */
  36664. get: function () {
  36665. var history = this._rollingFrameTime.history(0);
  36666. if (history === 0) {
  36667. return 0;
  36668. }
  36669. return 1000.0 / history;
  36670. },
  36671. enumerable: true,
  36672. configurable: true
  36673. });
  36674. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36675. /**
  36676. * Returns true if enough samples have been taken to completely fill the sliding window
  36677. * @return true if saturated
  36678. */
  36679. get: function () {
  36680. return this._rollingFrameTime.isSaturated();
  36681. },
  36682. enumerable: true,
  36683. configurable: true
  36684. });
  36685. /**
  36686. * Enables contributions to the sliding window sample set
  36687. */
  36688. PerformanceMonitor.prototype.enable = function () {
  36689. this._enabled = true;
  36690. };
  36691. /**
  36692. * Disables contributions to the sliding window sample set
  36693. * Samples will not be interpolated over the disabled period
  36694. */
  36695. PerformanceMonitor.prototype.disable = function () {
  36696. this._enabled = false;
  36697. //clear last sample to avoid interpolating over the disabled period when next enabled
  36698. this._lastFrameTimeMs = null;
  36699. };
  36700. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36701. /**
  36702. * Returns true if sampling is enabled
  36703. * @return true if enabled
  36704. */
  36705. get: function () {
  36706. return this._enabled;
  36707. },
  36708. enumerable: true,
  36709. configurable: true
  36710. });
  36711. /**
  36712. * Resets performance monitor
  36713. */
  36714. PerformanceMonitor.prototype.reset = function () {
  36715. //clear last sample to avoid interpolating over the disabled period when next enabled
  36716. this._lastFrameTimeMs = null;
  36717. //wipe record
  36718. this._rollingFrameTime.reset();
  36719. };
  36720. return PerformanceMonitor;
  36721. }());
  36722. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36723. /**
  36724. * RollingAverage
  36725. *
  36726. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36727. */
  36728. var RollingAverage = /** @class */ (function () {
  36729. /**
  36730. * constructor
  36731. * @param length The number of samples required to saturate the sliding window
  36732. */
  36733. function RollingAverage(length) {
  36734. this._samples = new Array(length);
  36735. this.reset();
  36736. }
  36737. /**
  36738. * Adds a sample to the sample set
  36739. * @param v The sample value
  36740. */
  36741. RollingAverage.prototype.add = function (v) {
  36742. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36743. var delta;
  36744. //we need to check if we've already wrapped round
  36745. if (this.isSaturated()) {
  36746. //remove bottom of stack from mean
  36747. var bottomValue = this._samples[this._pos];
  36748. delta = bottomValue - this.average;
  36749. this.average -= delta / (this._sampleCount - 1);
  36750. this._m2 -= delta * (bottomValue - this.average);
  36751. }
  36752. else {
  36753. this._sampleCount++;
  36754. }
  36755. //add new value to mean
  36756. delta = v - this.average;
  36757. this.average += delta / (this._sampleCount);
  36758. this._m2 += delta * (v - this.average);
  36759. //set the new variance
  36760. this.variance = this._m2 / (this._sampleCount - 1);
  36761. this._samples[this._pos] = v;
  36762. this._pos++;
  36763. this._pos %= this._samples.length; //positive wrap around
  36764. };
  36765. /**
  36766. * Returns previously added values or null if outside of history or outside the sliding window domain
  36767. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36768. * @return Value previously recorded with add() or null if outside of range
  36769. */
  36770. RollingAverage.prototype.history = function (i) {
  36771. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36772. return 0;
  36773. }
  36774. var i0 = this._wrapPosition(this._pos - 1.0);
  36775. return this._samples[this._wrapPosition(i0 - i)];
  36776. };
  36777. /**
  36778. * Returns true if enough samples have been taken to completely fill the sliding window
  36779. * @return true if sample-set saturated
  36780. */
  36781. RollingAverage.prototype.isSaturated = function () {
  36782. return this._sampleCount >= this._samples.length;
  36783. };
  36784. /**
  36785. * Resets the rolling average (equivalent to 0 samples taken so far)
  36786. */
  36787. RollingAverage.prototype.reset = function () {
  36788. this.average = 0;
  36789. this.variance = 0;
  36790. this._sampleCount = 0;
  36791. this._pos = 0;
  36792. this._m2 = 0;
  36793. };
  36794. /**
  36795. * Wraps a value around the sample range boundaries
  36796. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36797. * @return Wrapped position in sample range
  36798. */
  36799. RollingAverage.prototype._wrapPosition = function (i) {
  36800. var max = this._samples.length;
  36801. return ((i % max) + max) % max;
  36802. };
  36803. return RollingAverage;
  36804. }());
  36805. BABYLON.RollingAverage = RollingAverage;
  36806. })(BABYLON || (BABYLON = {}));
  36807. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36808. var BABYLON;
  36809. (function (BABYLON) {
  36810. /**
  36811. * This groups together the common properties used for image processing either in direct forward pass
  36812. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36813. * or not.
  36814. */
  36815. var ImageProcessingConfiguration = /** @class */ (function () {
  36816. function ImageProcessingConfiguration() {
  36817. /**
  36818. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36819. */
  36820. this.colorCurves = new BABYLON.ColorCurves();
  36821. this._colorCurvesEnabled = false;
  36822. this._colorGradingEnabled = false;
  36823. this._colorGradingWithGreenDepth = true;
  36824. this._colorGradingBGR = true;
  36825. this._exposure = 1.0;
  36826. this._toneMappingEnabled = false;
  36827. this._contrast = 1.0;
  36828. /**
  36829. * Vignette stretch size.
  36830. */
  36831. this.vignetteStretch = 0;
  36832. /**
  36833. * Vignette centre X Offset.
  36834. */
  36835. this.vignetteCentreX = 0;
  36836. /**
  36837. * Vignette centre Y Offset.
  36838. */
  36839. this.vignetteCentreY = 0;
  36840. /**
  36841. * Vignette weight or intensity of the vignette effect.
  36842. */
  36843. this.vignetteWeight = 1.5;
  36844. /**
  36845. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36846. * if vignetteEnabled is set to true.
  36847. */
  36848. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36849. /**
  36850. * Camera field of view used by the Vignette effect.
  36851. */
  36852. this.vignetteCameraFov = 0.5;
  36853. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36854. this._vignetteEnabled = false;
  36855. this._applyByPostProcess = false;
  36856. this._isEnabled = true;
  36857. /**
  36858. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36859. * @type {BABYLON.Observable}
  36860. */
  36861. this.onUpdateParameters = new BABYLON.Observable();
  36862. }
  36863. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36864. /**
  36865. * Gets wether the color curves effect is enabled.
  36866. */
  36867. get: function () {
  36868. return this._colorCurvesEnabled;
  36869. },
  36870. /**
  36871. * Sets wether the color curves effect is enabled.
  36872. */
  36873. set: function (value) {
  36874. if (this._colorCurvesEnabled === value) {
  36875. return;
  36876. }
  36877. this._colorCurvesEnabled = value;
  36878. this._updateParameters();
  36879. },
  36880. enumerable: true,
  36881. configurable: true
  36882. });
  36883. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36884. /**
  36885. * Gets wether the color grading effect is enabled.
  36886. */
  36887. get: function () {
  36888. return this._colorGradingEnabled;
  36889. },
  36890. /**
  36891. * Sets wether the color grading effect is enabled.
  36892. */
  36893. set: function (value) {
  36894. if (this._colorGradingEnabled === value) {
  36895. return;
  36896. }
  36897. this._colorGradingEnabled = value;
  36898. this._updateParameters();
  36899. },
  36900. enumerable: true,
  36901. configurable: true
  36902. });
  36903. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36904. /**
  36905. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36906. */
  36907. get: function () {
  36908. return this._colorGradingWithGreenDepth;
  36909. },
  36910. /**
  36911. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36912. */
  36913. set: function (value) {
  36914. if (this._colorGradingWithGreenDepth === value) {
  36915. return;
  36916. }
  36917. this._colorGradingWithGreenDepth = value;
  36918. this._updateParameters();
  36919. },
  36920. enumerable: true,
  36921. configurable: true
  36922. });
  36923. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36924. /**
  36925. * Gets wether the color grading texture contains BGR values.
  36926. */
  36927. get: function () {
  36928. return this._colorGradingBGR;
  36929. },
  36930. /**
  36931. * Sets wether the color grading texture contains BGR values.
  36932. */
  36933. set: function (value) {
  36934. if (this._colorGradingBGR === value) {
  36935. return;
  36936. }
  36937. this._colorGradingBGR = value;
  36938. this._updateParameters();
  36939. },
  36940. enumerable: true,
  36941. configurable: true
  36942. });
  36943. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36944. /**
  36945. * Gets the Exposure used in the effect.
  36946. */
  36947. get: function () {
  36948. return this._exposure;
  36949. },
  36950. /**
  36951. * Sets the Exposure used in the effect.
  36952. */
  36953. set: function (value) {
  36954. if (this._exposure === value) {
  36955. return;
  36956. }
  36957. this._exposure = value;
  36958. this._updateParameters();
  36959. },
  36960. enumerable: true,
  36961. configurable: true
  36962. });
  36963. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36964. /**
  36965. * Gets wether the tone mapping effect is enabled.
  36966. */
  36967. get: function () {
  36968. return this._toneMappingEnabled;
  36969. },
  36970. /**
  36971. * Sets wether the tone mapping effect is enabled.
  36972. */
  36973. set: function (value) {
  36974. if (this._toneMappingEnabled === value) {
  36975. return;
  36976. }
  36977. this._toneMappingEnabled = value;
  36978. this._updateParameters();
  36979. },
  36980. enumerable: true,
  36981. configurable: true
  36982. });
  36983. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36984. /**
  36985. * Gets the contrast used in the effect.
  36986. */
  36987. get: function () {
  36988. return this._contrast;
  36989. },
  36990. /**
  36991. * Sets the contrast used in the effect.
  36992. */
  36993. set: function (value) {
  36994. if (this._contrast === value) {
  36995. return;
  36996. }
  36997. this._contrast = value;
  36998. this._updateParameters();
  36999. },
  37000. enumerable: true,
  37001. configurable: true
  37002. });
  37003. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37004. /**
  37005. * Gets the vignette blend mode allowing different kind of effect.
  37006. */
  37007. get: function () {
  37008. return this._vignetteBlendMode;
  37009. },
  37010. /**
  37011. * Sets the vignette blend mode allowing different kind of effect.
  37012. */
  37013. set: function (value) {
  37014. if (this._vignetteBlendMode === value) {
  37015. return;
  37016. }
  37017. this._vignetteBlendMode = value;
  37018. this._updateParameters();
  37019. },
  37020. enumerable: true,
  37021. configurable: true
  37022. });
  37023. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37024. /**
  37025. * Gets wether the vignette effect is enabled.
  37026. */
  37027. get: function () {
  37028. return this._vignetteEnabled;
  37029. },
  37030. /**
  37031. * Sets wether the vignette effect is enabled.
  37032. */
  37033. set: function (value) {
  37034. if (this._vignetteEnabled === value) {
  37035. return;
  37036. }
  37037. this._vignetteEnabled = value;
  37038. this._updateParameters();
  37039. },
  37040. enumerable: true,
  37041. configurable: true
  37042. });
  37043. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37044. /**
  37045. * Gets wether the image processing is applied through a post process or not.
  37046. */
  37047. get: function () {
  37048. return this._applyByPostProcess;
  37049. },
  37050. /**
  37051. * Sets wether the image processing is applied through a post process or not.
  37052. */
  37053. set: function (value) {
  37054. if (this._applyByPostProcess === value) {
  37055. return;
  37056. }
  37057. this._applyByPostProcess = value;
  37058. this._updateParameters();
  37059. },
  37060. enumerable: true,
  37061. configurable: true
  37062. });
  37063. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37064. /**
  37065. * Gets wether the image processing is enabled or not.
  37066. */
  37067. get: function () {
  37068. return this._isEnabled;
  37069. },
  37070. /**
  37071. * Sets wether the image processing is enabled or not.
  37072. */
  37073. set: function (value) {
  37074. if (this._isEnabled === value) {
  37075. return;
  37076. }
  37077. this._isEnabled = value;
  37078. this._updateParameters();
  37079. },
  37080. enumerable: true,
  37081. configurable: true
  37082. });
  37083. /**
  37084. * Method called each time the image processing information changes requires to recompile the effect.
  37085. */
  37086. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37087. this.onUpdateParameters.notifyObservers(this);
  37088. };
  37089. ImageProcessingConfiguration.prototype.getClassName = function () {
  37090. return "ImageProcessingConfiguration";
  37091. };
  37092. /**
  37093. * Prepare the list of uniforms associated with the Image Processing effects.
  37094. * @param uniformsList The list of uniforms used in the effect
  37095. * @param defines the list of defines currently in use
  37096. */
  37097. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37098. if (defines.EXPOSURE) {
  37099. uniforms.push("exposureLinear");
  37100. }
  37101. if (defines.CONTRAST) {
  37102. uniforms.push("contrast");
  37103. }
  37104. if (defines.COLORGRADING) {
  37105. uniforms.push("colorTransformSettings");
  37106. }
  37107. if (defines.VIGNETTE) {
  37108. uniforms.push("vInverseScreenSize");
  37109. uniforms.push("vignetteSettings1");
  37110. uniforms.push("vignetteSettings2");
  37111. }
  37112. if (defines.COLORCURVES) {
  37113. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37114. }
  37115. };
  37116. /**
  37117. * Prepare the list of samplers associated with the Image Processing effects.
  37118. * @param uniformsList The list of uniforms used in the effect
  37119. * @param defines the list of defines currently in use
  37120. */
  37121. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37122. if (defines.COLORGRADING) {
  37123. samplersList.push("txColorTransform");
  37124. }
  37125. };
  37126. /**
  37127. * Prepare the list of defines associated to the shader.
  37128. * @param defines the list of defines to complete
  37129. */
  37130. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37131. if (forPostProcess === void 0) { forPostProcess = false; }
  37132. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37133. defines.VIGNETTE = false;
  37134. defines.TONEMAPPING = false;
  37135. defines.CONTRAST = false;
  37136. defines.EXPOSURE = false;
  37137. defines.COLORCURVES = false;
  37138. defines.COLORGRADING = false;
  37139. defines.COLORGRADING3D = false;
  37140. defines.IMAGEPROCESSING = false;
  37141. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37142. return;
  37143. }
  37144. defines.VIGNETTE = this.vignetteEnabled;
  37145. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37146. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37147. defines.TONEMAPPING = this.toneMappingEnabled;
  37148. defines.CONTRAST = (this.contrast !== 1.0);
  37149. defines.EXPOSURE = (this.exposure !== 1.0);
  37150. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37151. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37152. if (defines.COLORGRADING) {
  37153. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37154. }
  37155. else {
  37156. defines.COLORGRADING3D = false;
  37157. }
  37158. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37159. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37160. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37161. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37162. };
  37163. /**
  37164. * Returns true if all the image processing information are ready.
  37165. */
  37166. ImageProcessingConfiguration.prototype.isReady = function () {
  37167. // Color Grading texure can not be none blocking.
  37168. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37169. };
  37170. /**
  37171. * Binds the image processing to the shader.
  37172. * @param effect The effect to bind to
  37173. */
  37174. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37175. if (aspectRatio === void 0) { aspectRatio = 1; }
  37176. // Color Curves
  37177. if (this._colorCurvesEnabled && this.colorCurves) {
  37178. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37179. }
  37180. // Vignette
  37181. if (this._vignetteEnabled) {
  37182. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37183. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37184. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37185. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37186. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37187. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37188. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37189. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37190. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37191. var vignettePower = -2.0 * this.vignetteWeight;
  37192. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37193. }
  37194. // Exposure
  37195. effect.setFloat("exposureLinear", this.exposure);
  37196. // Contrast
  37197. effect.setFloat("contrast", this.contrast);
  37198. // Color transform settings
  37199. if (this.colorGradingTexture) {
  37200. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37201. var textureSize = this.colorGradingTexture.getSize().height;
  37202. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37203. 0.5 / textureSize, // textureOffset
  37204. textureSize, // textureSize
  37205. this.colorGradingTexture.level // weight
  37206. );
  37207. }
  37208. };
  37209. /**
  37210. * Clones the current image processing instance.
  37211. * @return The cloned image processing
  37212. */
  37213. ImageProcessingConfiguration.prototype.clone = function () {
  37214. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37215. };
  37216. /**
  37217. * Serializes the current image processing instance to a json representation.
  37218. * @return a JSON representation
  37219. */
  37220. ImageProcessingConfiguration.prototype.serialize = function () {
  37221. return BABYLON.SerializationHelper.Serialize(this);
  37222. };
  37223. /**
  37224. * Parses the image processing from a json representation.
  37225. * @param source the JSON source to parse
  37226. * @return The parsed image processing
  37227. */
  37228. ImageProcessingConfiguration.Parse = function (source) {
  37229. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37230. };
  37231. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37232. /**
  37233. * Used to apply the vignette as a mix with the pixel color.
  37234. */
  37235. get: function () {
  37236. return this._VIGNETTEMODE_MULTIPLY;
  37237. },
  37238. enumerable: true,
  37239. configurable: true
  37240. });
  37241. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37242. /**
  37243. * Used to apply the vignette as a replacement of the pixel color.
  37244. */
  37245. get: function () {
  37246. return this._VIGNETTEMODE_OPAQUE;
  37247. },
  37248. enumerable: true,
  37249. configurable: true
  37250. });
  37251. // Static constants associated to the image processing.
  37252. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37253. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37254. __decorate([
  37255. BABYLON.serializeAsColorCurves()
  37256. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37257. __decorate([
  37258. BABYLON.serialize()
  37259. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37260. __decorate([
  37261. BABYLON.serializeAsTexture()
  37262. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37263. __decorate([
  37264. BABYLON.serialize()
  37265. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37266. __decorate([
  37267. BABYLON.serialize()
  37268. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37269. __decorate([
  37270. BABYLON.serialize()
  37271. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37272. __decorate([
  37273. BABYLON.serialize()
  37274. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37275. __decorate([
  37276. BABYLON.serialize()
  37277. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37278. __decorate([
  37279. BABYLON.serialize()
  37280. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37281. __decorate([
  37282. BABYLON.serialize()
  37283. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37284. __decorate([
  37285. BABYLON.serialize()
  37286. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37287. __decorate([
  37288. BABYLON.serialize()
  37289. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37290. __decorate([
  37291. BABYLON.serialize()
  37292. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37293. __decorate([
  37294. BABYLON.serializeAsColor4()
  37295. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37296. __decorate([
  37297. BABYLON.serialize()
  37298. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37299. __decorate([
  37300. BABYLON.serialize()
  37301. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37302. __decorate([
  37303. BABYLON.serialize()
  37304. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37305. __decorate([
  37306. BABYLON.serialize()
  37307. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37308. __decorate([
  37309. BABYLON.serialize()
  37310. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37311. return ImageProcessingConfiguration;
  37312. }());
  37313. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37314. })(BABYLON || (BABYLON = {}));
  37315. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37316. var BABYLON;
  37317. (function (BABYLON) {
  37318. /**
  37319. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37320. * It can help converting any input color in a desired output one. This can then be used to create effects
  37321. * from sepia, black and white to sixties or futuristic rendering...
  37322. *
  37323. * The only supported format is currently 3dl.
  37324. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37325. */
  37326. var ColorGradingTexture = /** @class */ (function (_super) {
  37327. __extends(ColorGradingTexture, _super);
  37328. /**
  37329. * Instantiates a ColorGradingTexture from the following parameters.
  37330. *
  37331. * @param url The location of the color gradind data (currently only supporting 3dl)
  37332. * @param scene The scene the texture will be used in
  37333. */
  37334. function ColorGradingTexture(url, scene) {
  37335. var _this = _super.call(this, scene) || this;
  37336. if (!url) {
  37337. return _this;
  37338. }
  37339. _this._engine = scene.getEngine();
  37340. _this._textureMatrix = BABYLON.Matrix.Identity();
  37341. _this.name = url;
  37342. _this.url = url;
  37343. _this.hasAlpha = false;
  37344. _this.isCube = false;
  37345. _this.is3D = _this._engine.webGLVersion > 1;
  37346. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37347. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37348. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37349. _this.anisotropicFilteringLevel = 1;
  37350. _this._texture = _this._getFromCache(url, true);
  37351. if (!_this._texture) {
  37352. if (!scene.useDelayedTextureLoading) {
  37353. _this.loadTexture();
  37354. }
  37355. else {
  37356. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37357. }
  37358. }
  37359. return _this;
  37360. }
  37361. /**
  37362. * Returns the texture matrix used in most of the material.
  37363. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37364. */
  37365. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37366. return this._textureMatrix;
  37367. };
  37368. /**
  37369. * Occurs when the file being loaded is a .3dl LUT file.
  37370. */
  37371. ColorGradingTexture.prototype.load3dlTexture = function () {
  37372. var engine = this._engine;
  37373. var texture;
  37374. if (engine.webGLVersion === 1) {
  37375. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37376. }
  37377. else {
  37378. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37379. }
  37380. this._texture = texture;
  37381. var callback = function (text) {
  37382. if (typeof text !== "string") {
  37383. return;
  37384. }
  37385. var data = null;
  37386. var tempData = null;
  37387. var line;
  37388. var lines = text.split('\n');
  37389. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37390. var maxColor = 0;
  37391. for (var i = 0; i < lines.length; i++) {
  37392. line = lines[i];
  37393. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37394. continue;
  37395. if (line.indexOf('#') === 0)
  37396. continue;
  37397. var words = line.split(" ");
  37398. if (size === 0) {
  37399. // Number of space + one
  37400. size = words.length;
  37401. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37402. tempData = new Float32Array(size * size * size * 4);
  37403. continue;
  37404. }
  37405. if (size != 0) {
  37406. var r = Math.max(parseInt(words[0]), 0);
  37407. var g = Math.max(parseInt(words[1]), 0);
  37408. var b = Math.max(parseInt(words[2]), 0);
  37409. maxColor = Math.max(r, maxColor);
  37410. maxColor = Math.max(g, maxColor);
  37411. maxColor = Math.max(b, maxColor);
  37412. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37413. if (tempData) {
  37414. tempData[pixelStorageIndex + 0] = r;
  37415. tempData[pixelStorageIndex + 1] = g;
  37416. tempData[pixelStorageIndex + 2] = b;
  37417. }
  37418. pixelIndexSlice++;
  37419. if (pixelIndexSlice % size == 0) {
  37420. pixelIndexH++;
  37421. pixelIndexSlice = 0;
  37422. if (pixelIndexH % size == 0) {
  37423. pixelIndexW++;
  37424. pixelIndexH = 0;
  37425. }
  37426. }
  37427. }
  37428. }
  37429. if (tempData && data) {
  37430. for (var i = 0; i < tempData.length; i++) {
  37431. if (i > 0 && (i + 1) % 4 === 0) {
  37432. data[i] = 255;
  37433. }
  37434. else {
  37435. var value = tempData[i];
  37436. data[i] = (value / maxColor * 255);
  37437. }
  37438. }
  37439. }
  37440. if (texture.is3D) {
  37441. texture.updateSize(size, size, size);
  37442. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37443. }
  37444. else {
  37445. texture.updateSize(size * size, size);
  37446. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37447. }
  37448. };
  37449. var scene = this.getScene();
  37450. if (scene) {
  37451. scene._loadFile(this.url, callback);
  37452. }
  37453. else {
  37454. this._engine._loadFile(this.url, callback);
  37455. }
  37456. return this._texture;
  37457. };
  37458. /**
  37459. * Starts the loading process of the texture.
  37460. */
  37461. ColorGradingTexture.prototype.loadTexture = function () {
  37462. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37463. this.load3dlTexture();
  37464. }
  37465. };
  37466. /**
  37467. * Clones the color gradind texture.
  37468. */
  37469. ColorGradingTexture.prototype.clone = function () {
  37470. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37471. // Base texture
  37472. newTexture.level = this.level;
  37473. return newTexture;
  37474. };
  37475. /**
  37476. * Called during delayed load for textures.
  37477. */
  37478. ColorGradingTexture.prototype.delayLoad = function () {
  37479. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37480. return;
  37481. }
  37482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37483. this._texture = this._getFromCache(this.url, true);
  37484. if (!this._texture) {
  37485. this.loadTexture();
  37486. }
  37487. };
  37488. /**
  37489. * Parses a color grading texture serialized by Babylon.
  37490. * @param parsedTexture The texture information being parsedTexture
  37491. * @param scene The scene to load the texture in
  37492. * @param rootUrl The root url of the data assets to load
  37493. * @return A color gradind texture
  37494. */
  37495. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37496. var texture = null;
  37497. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37498. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37499. texture.name = parsedTexture.name;
  37500. texture.level = parsedTexture.level;
  37501. }
  37502. return texture;
  37503. };
  37504. /**
  37505. * Serializes the LUT texture to json format.
  37506. */
  37507. ColorGradingTexture.prototype.serialize = function () {
  37508. if (!this.name) {
  37509. return null;
  37510. }
  37511. var serializationObject = {};
  37512. serializationObject.name = this.name;
  37513. serializationObject.level = this.level;
  37514. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37515. return serializationObject;
  37516. };
  37517. /**
  37518. * Empty line regex stored for GC.
  37519. */
  37520. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37521. return ColorGradingTexture;
  37522. }(BABYLON.BaseTexture));
  37523. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37524. })(BABYLON || (BABYLON = {}));
  37525. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37526. var BABYLON;
  37527. (function (BABYLON) {
  37528. /**
  37529. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37530. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37531. * 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;
  37532. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37533. */
  37534. var ColorCurves = /** @class */ (function () {
  37535. function ColorCurves() {
  37536. this._dirty = true;
  37537. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37538. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37539. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37540. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37541. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37542. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37543. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37544. this._globalHue = 30;
  37545. this._globalDensity = 0;
  37546. this._globalSaturation = 0;
  37547. this._globalExposure = 0;
  37548. this._highlightsHue = 30;
  37549. this._highlightsDensity = 0;
  37550. this._highlightsSaturation = 0;
  37551. this._highlightsExposure = 0;
  37552. this._midtonesHue = 30;
  37553. this._midtonesDensity = 0;
  37554. this._midtonesSaturation = 0;
  37555. this._midtonesExposure = 0;
  37556. this._shadowsHue = 30;
  37557. this._shadowsDensity = 0;
  37558. this._shadowsSaturation = 0;
  37559. this._shadowsExposure = 0;
  37560. }
  37561. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37562. /**
  37563. * Gets the global Hue value.
  37564. * 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).
  37565. */
  37566. get: function () {
  37567. return this._globalHue;
  37568. },
  37569. /**
  37570. * Sets the global Hue value.
  37571. * 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).
  37572. */
  37573. set: function (value) {
  37574. this._globalHue = value;
  37575. this._dirty = true;
  37576. },
  37577. enumerable: true,
  37578. configurable: true
  37579. });
  37580. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37581. /**
  37582. * Gets the global Density value.
  37583. * 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.
  37584. * Values less than zero provide a filter of opposite hue.
  37585. */
  37586. get: function () {
  37587. return this._globalDensity;
  37588. },
  37589. /**
  37590. * Sets the global Density value.
  37591. * 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.
  37592. * Values less than zero provide a filter of opposite hue.
  37593. */
  37594. set: function (value) {
  37595. this._globalDensity = value;
  37596. this._dirty = true;
  37597. },
  37598. enumerable: true,
  37599. configurable: true
  37600. });
  37601. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37602. /**
  37603. * Gets the global Saturation value.
  37604. * 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.
  37605. */
  37606. get: function () {
  37607. return this._globalSaturation;
  37608. },
  37609. /**
  37610. * Sets the global Saturation value.
  37611. * 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.
  37612. */
  37613. set: function (value) {
  37614. this._globalSaturation = value;
  37615. this._dirty = true;
  37616. },
  37617. enumerable: true,
  37618. configurable: true
  37619. });
  37620. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37621. /**
  37622. * Gets the highlights Hue value.
  37623. * 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).
  37624. */
  37625. get: function () {
  37626. return this._highlightsHue;
  37627. },
  37628. /**
  37629. * Sets the highlights Hue value.
  37630. * 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).
  37631. */
  37632. set: function (value) {
  37633. this._highlightsHue = value;
  37634. this._dirty = true;
  37635. },
  37636. enumerable: true,
  37637. configurable: true
  37638. });
  37639. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37640. /**
  37641. * Gets the highlights Density value.
  37642. * 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.
  37643. * Values less than zero provide a filter of opposite hue.
  37644. */
  37645. get: function () {
  37646. return this._highlightsDensity;
  37647. },
  37648. /**
  37649. * Sets the highlights Density value.
  37650. * 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.
  37651. * Values less than zero provide a filter of opposite hue.
  37652. */
  37653. set: function (value) {
  37654. this._highlightsDensity = value;
  37655. this._dirty = true;
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37661. /**
  37662. * Gets the highlights Saturation value.
  37663. * 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.
  37664. */
  37665. get: function () {
  37666. return this._highlightsSaturation;
  37667. },
  37668. /**
  37669. * Sets the highlights Saturation value.
  37670. * 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.
  37671. */
  37672. set: function (value) {
  37673. this._highlightsSaturation = value;
  37674. this._dirty = true;
  37675. },
  37676. enumerable: true,
  37677. configurable: true
  37678. });
  37679. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37680. /**
  37681. * Gets the highlights Exposure value.
  37682. * 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.
  37683. */
  37684. get: function () {
  37685. return this._highlightsExposure;
  37686. },
  37687. /**
  37688. * Sets the highlights Exposure value.
  37689. * 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.
  37690. */
  37691. set: function (value) {
  37692. this._highlightsExposure = value;
  37693. this._dirty = true;
  37694. },
  37695. enumerable: true,
  37696. configurable: true
  37697. });
  37698. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37699. /**
  37700. * Gets the midtones Hue value.
  37701. * 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).
  37702. */
  37703. get: function () {
  37704. return this._midtonesHue;
  37705. },
  37706. /**
  37707. * Sets the midtones Hue value.
  37708. * 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).
  37709. */
  37710. set: function (value) {
  37711. this._midtonesHue = value;
  37712. this._dirty = true;
  37713. },
  37714. enumerable: true,
  37715. configurable: true
  37716. });
  37717. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37718. /**
  37719. * Gets the midtones Density value.
  37720. * 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.
  37721. * Values less than zero provide a filter of opposite hue.
  37722. */
  37723. get: function () {
  37724. return this._midtonesDensity;
  37725. },
  37726. /**
  37727. * Sets the midtones Density value.
  37728. * 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.
  37729. * Values less than zero provide a filter of opposite hue.
  37730. */
  37731. set: function (value) {
  37732. this._midtonesDensity = value;
  37733. this._dirty = true;
  37734. },
  37735. enumerable: true,
  37736. configurable: true
  37737. });
  37738. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37739. /**
  37740. * Gets the midtones Saturation value.
  37741. * 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.
  37742. */
  37743. get: function () {
  37744. return this._midtonesSaturation;
  37745. },
  37746. /**
  37747. * Sets the midtones Saturation value.
  37748. * 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.
  37749. */
  37750. set: function (value) {
  37751. this._midtonesSaturation = value;
  37752. this._dirty = true;
  37753. },
  37754. enumerable: true,
  37755. configurable: true
  37756. });
  37757. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37758. /**
  37759. * Gets the midtones Exposure 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 exposure and negative values decrease exposure.
  37761. */
  37762. get: function () {
  37763. return this._midtonesExposure;
  37764. },
  37765. /**
  37766. * Sets the midtones Exposure value.
  37767. * 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.
  37768. */
  37769. set: function (value) {
  37770. this._midtonesExposure = value;
  37771. this._dirty = true;
  37772. },
  37773. enumerable: true,
  37774. configurable: true
  37775. });
  37776. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37777. /**
  37778. * Gets the shadows Hue value.
  37779. * 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).
  37780. */
  37781. get: function () {
  37782. return this._shadowsHue;
  37783. },
  37784. /**
  37785. * Sets the shadows Hue value.
  37786. * 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).
  37787. */
  37788. set: function (value) {
  37789. this._shadowsHue = value;
  37790. this._dirty = true;
  37791. },
  37792. enumerable: true,
  37793. configurable: true
  37794. });
  37795. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37796. /**
  37797. * Gets the shadows Density value.
  37798. * 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.
  37799. * Values less than zero provide a filter of opposite hue.
  37800. */
  37801. get: function () {
  37802. return this._shadowsDensity;
  37803. },
  37804. /**
  37805. * Sets the shadows Density value.
  37806. * 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.
  37807. * Values less than zero provide a filter of opposite hue.
  37808. */
  37809. set: function (value) {
  37810. this._shadowsDensity = value;
  37811. this._dirty = true;
  37812. },
  37813. enumerable: true,
  37814. configurable: true
  37815. });
  37816. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37817. /**
  37818. * Gets the shadows Saturation value.
  37819. * 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.
  37820. */
  37821. get: function () {
  37822. return this._shadowsSaturation;
  37823. },
  37824. /**
  37825. * Sets the shadows Saturation value.
  37826. * 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.
  37827. */
  37828. set: function (value) {
  37829. this._shadowsSaturation = value;
  37830. this._dirty = true;
  37831. },
  37832. enumerable: true,
  37833. configurable: true
  37834. });
  37835. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37836. /**
  37837. * Gets the shadows Exposure 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 exposure and negative values decrease exposure.
  37839. */
  37840. get: function () {
  37841. return this._shadowsExposure;
  37842. },
  37843. /**
  37844. * Sets the shadows Exposure value.
  37845. * 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.
  37846. */
  37847. set: function (value) {
  37848. this._shadowsExposure = value;
  37849. this._dirty = true;
  37850. },
  37851. enumerable: true,
  37852. configurable: true
  37853. });
  37854. ColorCurves.prototype.getClassName = function () {
  37855. return "ColorCurves";
  37856. };
  37857. /**
  37858. * Binds the color curves to the shader.
  37859. * @param colorCurves The color curve to bind
  37860. * @param effect The effect to bind to
  37861. */
  37862. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37863. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37864. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37865. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37866. if (colorCurves._dirty) {
  37867. colorCurves._dirty = false;
  37868. // Fill in global info.
  37869. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37870. // Compute highlights info.
  37871. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37872. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37873. // Compute midtones info.
  37874. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37875. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37876. // Compute shadows info.
  37877. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37878. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37879. // Compute deltas (neutral is midtones).
  37880. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37881. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37882. }
  37883. if (effect) {
  37884. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37885. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37886. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37887. }
  37888. };
  37889. /**
  37890. * Prepare the list of uniforms associated with the ColorCurves effects.
  37891. * @param uniformsList The list of uniforms used in the effect
  37892. */
  37893. ColorCurves.PrepareUniforms = function (uniformsList) {
  37894. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37895. };
  37896. /**
  37897. * Returns color grading data based on a hue, density, saturation and exposure value.
  37898. * @param filterHue The hue of the color filter.
  37899. * @param filterDensity The density of the color filter.
  37900. * @param saturation The saturation.
  37901. * @param exposure The exposure.
  37902. * @param result The result data container.
  37903. */
  37904. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37905. if (hue == null) {
  37906. return;
  37907. }
  37908. hue = ColorCurves.clamp(hue, 0, 360);
  37909. density = ColorCurves.clamp(density, -100, 100);
  37910. saturation = ColorCurves.clamp(saturation, -100, 100);
  37911. exposure = ColorCurves.clamp(exposure, -100, 100);
  37912. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37913. // so that the maximum filter density is only 50% control. This provides fine control
  37914. // for small values and reasonable range.
  37915. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37916. density *= 0.5;
  37917. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37918. if (density < 0) {
  37919. density *= -1;
  37920. hue = (hue + 180) % 360;
  37921. }
  37922. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37923. result.scaleToRef(2, result);
  37924. result.a = 1 + 0.01 * saturation;
  37925. };
  37926. /**
  37927. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37928. * @param value The input slider value in range [-100,100].
  37929. * @returns Adjusted value.
  37930. */
  37931. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37932. value /= 100;
  37933. var x = Math.abs(value);
  37934. x = Math.pow(x, 2);
  37935. if (value < 0) {
  37936. x *= -1;
  37937. }
  37938. x *= 100;
  37939. return x;
  37940. };
  37941. /**
  37942. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37943. * @param hue The hue (H) input.
  37944. * @param saturation The saturation (S) input.
  37945. * @param brightness The brightness (B) input.
  37946. * @result An RGBA color represented as Vector4.
  37947. */
  37948. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37949. var h = ColorCurves.clamp(hue, 0, 360);
  37950. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37951. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37952. if (s === 0) {
  37953. result.r = v;
  37954. result.g = v;
  37955. result.b = v;
  37956. }
  37957. else {
  37958. // sector 0 to 5
  37959. h /= 60;
  37960. var i = Math.floor(h);
  37961. // fractional part of h
  37962. var f = h - i;
  37963. var p = v * (1 - s);
  37964. var q = v * (1 - s * f);
  37965. var t = v * (1 - s * (1 - f));
  37966. switch (i) {
  37967. case 0:
  37968. result.r = v;
  37969. result.g = t;
  37970. result.b = p;
  37971. break;
  37972. case 1:
  37973. result.r = q;
  37974. result.g = v;
  37975. result.b = p;
  37976. break;
  37977. case 2:
  37978. result.r = p;
  37979. result.g = v;
  37980. result.b = t;
  37981. break;
  37982. case 3:
  37983. result.r = p;
  37984. result.g = q;
  37985. result.b = v;
  37986. break;
  37987. case 4:
  37988. result.r = t;
  37989. result.g = p;
  37990. result.b = v;
  37991. break;
  37992. default:// case 5:
  37993. result.r = v;
  37994. result.g = p;
  37995. result.b = q;
  37996. break;
  37997. }
  37998. }
  37999. result.a = 1;
  38000. };
  38001. /**
  38002. * Returns a value clamped between min and max
  38003. * @param value The value to clamp
  38004. * @param min The minimum of value
  38005. * @param max The maximum of value
  38006. * @returns The clamped value.
  38007. */
  38008. ColorCurves.clamp = function (value, min, max) {
  38009. return Math.min(Math.max(value, min), max);
  38010. };
  38011. /**
  38012. * Clones the current color curve instance.
  38013. * @return The cloned curves
  38014. */
  38015. ColorCurves.prototype.clone = function () {
  38016. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38017. };
  38018. /**
  38019. * Serializes the current color curve instance to a json representation.
  38020. * @return a JSON representation
  38021. */
  38022. ColorCurves.prototype.serialize = function () {
  38023. return BABYLON.SerializationHelper.Serialize(this);
  38024. };
  38025. /**
  38026. * Parses the color curve from a json representation.
  38027. * @param source the JSON source to parse
  38028. * @return The parsed curves
  38029. */
  38030. ColorCurves.Parse = function (source) {
  38031. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38032. };
  38033. __decorate([
  38034. BABYLON.serialize()
  38035. ], ColorCurves.prototype, "_globalHue", void 0);
  38036. __decorate([
  38037. BABYLON.serialize()
  38038. ], ColorCurves.prototype, "_globalDensity", void 0);
  38039. __decorate([
  38040. BABYLON.serialize()
  38041. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38042. __decorate([
  38043. BABYLON.serialize()
  38044. ], ColorCurves.prototype, "_globalExposure", void 0);
  38045. __decorate([
  38046. BABYLON.serialize()
  38047. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38048. __decorate([
  38049. BABYLON.serialize()
  38050. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38051. __decorate([
  38052. BABYLON.serialize()
  38053. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38054. __decorate([
  38055. BABYLON.serialize()
  38056. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38057. __decorate([
  38058. BABYLON.serialize()
  38059. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38060. __decorate([
  38061. BABYLON.serialize()
  38062. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38063. __decorate([
  38064. BABYLON.serialize()
  38065. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38066. __decorate([
  38067. BABYLON.serialize()
  38068. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38069. return ColorCurves;
  38070. }());
  38071. BABYLON.ColorCurves = ColorCurves;
  38072. })(BABYLON || (BABYLON = {}));
  38073. //# sourceMappingURL=babylon.colorCurves.js.map
  38074. //# sourceMappingURL=babylon.behavior.js.map
  38075. var BABYLON;
  38076. (function (BABYLON) {
  38077. /**
  38078. * "Static Class" containing the most commonly used helper while dealing with material for
  38079. * rendering purpose.
  38080. *
  38081. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38082. *
  38083. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38084. */
  38085. var MaterialHelper = /** @class */ (function () {
  38086. function MaterialHelper() {
  38087. }
  38088. /**
  38089. * Bind the current view position to an effect.
  38090. * @param effect The effect to be bound
  38091. * @param scene The scene the eyes position is used from
  38092. */
  38093. MaterialHelper.BindEyePosition = function (effect, scene) {
  38094. if (scene._forcedViewPosition) {
  38095. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38096. return;
  38097. }
  38098. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38099. };
  38100. /**
  38101. * Helps preparing the defines values about the UVs in used in the effect.
  38102. * UVs are shared as much as we can accross chanels in the shaders.
  38103. * @param texture The texture we are preparing the UVs for
  38104. * @param defines The defines to update
  38105. * @param key The chanel key "diffuse", "specular"... used in the shader
  38106. */
  38107. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38108. defines._needUVs = true;
  38109. defines[key] = true;
  38110. if (texture.getTextureMatrix().isIdentity(true)) {
  38111. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38112. if (texture.coordinatesIndex === 0) {
  38113. defines["MAINUV1"] = true;
  38114. }
  38115. else {
  38116. defines["MAINUV2"] = true;
  38117. }
  38118. }
  38119. else {
  38120. defines[key + "DIRECTUV"] = 0;
  38121. }
  38122. };
  38123. /**
  38124. * Binds a texture matrix value to its corrsponding uniform
  38125. * @param texture The texture to bind the matrix for
  38126. * @param uniformBuffer The uniform buffer receivin the data
  38127. * @param key The chanel key "diffuse", "specular"... used in the shader
  38128. */
  38129. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38130. var matrix = texture.getTextureMatrix();
  38131. if (!matrix.isIdentity(true)) {
  38132. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38133. }
  38134. };
  38135. /**
  38136. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38137. * @param mesh defines the current mesh
  38138. * @param scene defines the current scene
  38139. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38140. * @param pointsCloud defines if point cloud rendering has to be turned on
  38141. * @param fogEnabled defines if fog has to be turned on
  38142. * @param alphaTest defines if alpha testing has to be turned on
  38143. * @param defines defines the current list of defines
  38144. */
  38145. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38146. if (defines._areMiscDirty) {
  38147. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38148. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38149. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38150. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38151. defines["ALPHATEST"] = alphaTest;
  38152. }
  38153. };
  38154. /**
  38155. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38156. * @param scene defines the current scene
  38157. * @param engine defines the current engine
  38158. * @param defines specifies the list of active defines
  38159. * @param useInstances defines if instances have to be turned on
  38160. * @param useClipPlane defines if clip plane have to be turned on
  38161. */
  38162. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38163. if (useClipPlane === void 0) { useClipPlane = null; }
  38164. var changed = false;
  38165. if (useClipPlane == null) {
  38166. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38167. }
  38168. if (defines["CLIPPLANE"] !== useClipPlane) {
  38169. defines["CLIPPLANE"] = useClipPlane;
  38170. changed = true;
  38171. }
  38172. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38173. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38174. changed = true;
  38175. }
  38176. if (defines["INSTANCES"] !== useInstances) {
  38177. defines["INSTANCES"] = useInstances;
  38178. changed = true;
  38179. }
  38180. if (changed) {
  38181. defines.markAsUnprocessed();
  38182. }
  38183. };
  38184. /**
  38185. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38186. * @param mesh The mesh containing the geometry data we will draw
  38187. * @param defines The defines to update
  38188. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38189. * @param useBones Precise whether bones should be used or not (override mesh info)
  38190. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38191. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38192. * @returns false if defines are considered not dirty and have not been checked
  38193. */
  38194. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38195. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38196. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38197. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38198. return false;
  38199. }
  38200. defines._normals = defines._needNormals;
  38201. defines._uvs = defines._needUVs;
  38202. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38203. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38204. defines["TANGENT"] = true;
  38205. }
  38206. if (defines._needUVs) {
  38207. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38208. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38209. }
  38210. else {
  38211. defines["UV1"] = false;
  38212. defines["UV2"] = false;
  38213. }
  38214. if (useVertexColor) {
  38215. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38216. defines["VERTEXCOLOR"] = hasVertexColors;
  38217. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38218. }
  38219. if (useBones) {
  38220. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38221. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38222. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38223. }
  38224. else {
  38225. defines["NUM_BONE_INFLUENCERS"] = 0;
  38226. defines["BonesPerMesh"] = 0;
  38227. }
  38228. }
  38229. if (useMorphTargets) {
  38230. var manager = mesh.morphTargetManager;
  38231. if (manager) {
  38232. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38233. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38234. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38235. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38236. }
  38237. else {
  38238. defines["MORPHTARGETS_TANGENT"] = false;
  38239. defines["MORPHTARGETS_NORMAL"] = false;
  38240. defines["MORPHTARGETS"] = false;
  38241. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38242. }
  38243. }
  38244. return true;
  38245. };
  38246. /**
  38247. * Prepares the defines related to the light information passed in parameter
  38248. * @param scene The scene we are intending to draw
  38249. * @param mesh The mesh the effect is compiling for
  38250. * @param defines The defines to update
  38251. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38252. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38253. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38254. * @returns true if normals will be required for the rest of the effect
  38255. */
  38256. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38257. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38258. if (disableLighting === void 0) { disableLighting = false; }
  38259. if (!defines._areLightsDirty) {
  38260. return defines._needNormals;
  38261. }
  38262. var lightIndex = 0;
  38263. var needNormals = false;
  38264. var needRebuild = false;
  38265. var lightmapMode = false;
  38266. var shadowEnabled = false;
  38267. var specularEnabled = false;
  38268. if (scene.lightsEnabled && !disableLighting) {
  38269. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38270. var light = _a[_i];
  38271. needNormals = true;
  38272. if (defines["LIGHT" + lightIndex] === undefined) {
  38273. needRebuild = true;
  38274. }
  38275. defines["LIGHT" + lightIndex] = true;
  38276. defines["SPOTLIGHT" + lightIndex] = false;
  38277. defines["HEMILIGHT" + lightIndex] = false;
  38278. defines["POINTLIGHT" + lightIndex] = false;
  38279. defines["DIRLIGHT" + lightIndex] = false;
  38280. var type;
  38281. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38282. type = "SPOTLIGHT" + lightIndex;
  38283. var spotLight = light;
  38284. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38285. }
  38286. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38287. type = "HEMILIGHT" + lightIndex;
  38288. }
  38289. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38290. type = "POINTLIGHT" + lightIndex;
  38291. }
  38292. else {
  38293. type = "DIRLIGHT" + lightIndex;
  38294. }
  38295. defines[type] = true;
  38296. // Specular
  38297. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38298. specularEnabled = true;
  38299. }
  38300. // Shadows
  38301. defines["SHADOW" + lightIndex] = false;
  38302. defines["SHADOWPCF" + lightIndex] = false;
  38303. defines["SHADOWESM" + lightIndex] = false;
  38304. defines["SHADOWCUBE" + lightIndex] = false;
  38305. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38306. var shadowGenerator = light.getShadowGenerator();
  38307. if (shadowGenerator) {
  38308. shadowEnabled = true;
  38309. shadowGenerator.prepareDefines(defines, lightIndex);
  38310. }
  38311. }
  38312. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38313. lightmapMode = true;
  38314. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38315. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38316. }
  38317. else {
  38318. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38319. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38320. }
  38321. lightIndex++;
  38322. if (lightIndex === maxSimultaneousLights)
  38323. break;
  38324. }
  38325. }
  38326. defines["SPECULARTERM"] = specularEnabled;
  38327. defines["SHADOWS"] = shadowEnabled;
  38328. // Resetting all other lights if any
  38329. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38330. if (defines["LIGHT" + index] !== undefined) {
  38331. defines["LIGHT" + index] = false;
  38332. defines["HEMILIGHT" + lightIndex] = false;
  38333. defines["POINTLIGHT" + lightIndex] = false;
  38334. defines["DIRLIGHT" + lightIndex] = false;
  38335. defines["SPOTLIGHT" + lightIndex] = false;
  38336. defines["SHADOW" + lightIndex] = false;
  38337. }
  38338. }
  38339. var caps = scene.getEngine().getCaps();
  38340. if (defines["SHADOWFLOAT"] === undefined) {
  38341. needRebuild = true;
  38342. }
  38343. defines["SHADOWFLOAT"] = shadowEnabled &&
  38344. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38345. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38346. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38347. if (needRebuild) {
  38348. defines.rebuild();
  38349. }
  38350. return needNormals;
  38351. };
  38352. /**
  38353. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38354. * that won t be acctive due to defines being turned off.
  38355. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38356. * @param samplersList The samplers list
  38357. * @param defines The defines helping in the list generation
  38358. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38359. */
  38360. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38361. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38362. var uniformsList;
  38363. var uniformBuffersList = null;
  38364. if (uniformsListOrOptions.uniformsNames) {
  38365. var options = uniformsListOrOptions;
  38366. uniformsList = options.uniformsNames;
  38367. uniformBuffersList = options.uniformBuffersNames;
  38368. samplersList = options.samplers;
  38369. defines = options.defines;
  38370. maxSimultaneousLights = options.maxSimultaneousLights;
  38371. }
  38372. else {
  38373. uniformsList = uniformsListOrOptions;
  38374. if (!samplersList) {
  38375. samplersList = [];
  38376. }
  38377. }
  38378. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38379. if (!defines["LIGHT" + lightIndex]) {
  38380. break;
  38381. }
  38382. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38383. if (uniformBuffersList) {
  38384. uniformBuffersList.push("Light" + lightIndex);
  38385. }
  38386. samplersList.push("shadowSampler" + lightIndex);
  38387. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38388. samplersList.push("projectionLightSampler" + lightIndex);
  38389. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38390. }
  38391. }
  38392. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38393. uniformsList.push("morphTargetInfluences");
  38394. }
  38395. };
  38396. /**
  38397. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38398. * @param defines The defines to update while falling back
  38399. * @param fallbacks The authorized effect fallbacks
  38400. * @param maxSimultaneousLights The maximum number of lights allowed
  38401. * @param rank the current rank of the Effect
  38402. * @returns The newly affected rank
  38403. */
  38404. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38405. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38406. if (rank === void 0) { rank = 0; }
  38407. var lightFallbackRank = 0;
  38408. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38409. if (!defines["LIGHT" + lightIndex]) {
  38410. break;
  38411. }
  38412. if (lightIndex > 0) {
  38413. lightFallbackRank = rank + lightIndex;
  38414. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38415. }
  38416. if (!defines["SHADOWS"]) {
  38417. if (defines["SHADOW" + lightIndex]) {
  38418. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38419. }
  38420. if (defines["SHADOWPCF" + lightIndex]) {
  38421. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38422. }
  38423. if (defines["SHADOWESM" + lightIndex]) {
  38424. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38425. }
  38426. }
  38427. }
  38428. return lightFallbackRank++;
  38429. };
  38430. /**
  38431. * Prepares the list of attributes required for morph targets according to the effect defines.
  38432. * @param attribs The current list of supported attribs
  38433. * @param mesh The mesh to prepare the morph targets attributes for
  38434. * @param defines The current Defines of the effect
  38435. */
  38436. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38437. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38438. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38439. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38440. var manager = mesh.morphTargetManager;
  38441. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38442. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38443. for (var index = 0; index < influencers; index++) {
  38444. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38445. if (normal) {
  38446. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38447. }
  38448. if (tangent) {
  38449. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38450. }
  38451. if (attribs.length > maxAttributesCount) {
  38452. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38453. }
  38454. }
  38455. }
  38456. };
  38457. /**
  38458. * Prepares the list of attributes required for bones according to the effect defines.
  38459. * @param attribs The current list of supported attribs
  38460. * @param mesh The mesh to prepare the bones attributes for
  38461. * @param defines The current Defines of the effect
  38462. * @param fallbacks The current efffect fallback strategy
  38463. */
  38464. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38465. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38466. fallbacks.addCPUSkinningFallback(0, mesh);
  38467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38469. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38470. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38471. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38472. }
  38473. }
  38474. };
  38475. /**
  38476. * Prepares the list of attributes required for instances according to the effect defines.
  38477. * @param attribs The current list of supported attribs
  38478. * @param defines The current Defines of the effect
  38479. */
  38480. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38481. if (defines["INSTANCES"]) {
  38482. attribs.push("world0");
  38483. attribs.push("world1");
  38484. attribs.push("world2");
  38485. attribs.push("world3");
  38486. }
  38487. };
  38488. /**
  38489. * Binds the light shadow information to the effect for the given mesh.
  38490. * @param light The light containing the generator
  38491. * @param scene The scene the lights belongs to
  38492. * @param mesh The mesh we are binding the information to render
  38493. * @param lightIndex The light index in the effect used to render the mesh
  38494. * @param effect The effect we are binding the data to
  38495. */
  38496. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38497. if (light.shadowEnabled && mesh.receiveShadows) {
  38498. var shadowGenerator = light.getShadowGenerator();
  38499. if (shadowGenerator) {
  38500. shadowGenerator.bindShadowLight(lightIndex, effect);
  38501. }
  38502. }
  38503. };
  38504. /**
  38505. * Binds the light information to the effect.
  38506. * @param light The light containing the generator
  38507. * @param effect The effect we are binding the data to
  38508. * @param lightIndex The light index in the effect used to render
  38509. */
  38510. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38511. light.transferToEffect(effect, lightIndex + "");
  38512. };
  38513. /**
  38514. * Binds the lights information from the scene to the effect for the given mesh.
  38515. * @param scene The scene the lights belongs to
  38516. * @param mesh The mesh we are binding the information to render
  38517. * @param effect The effect we are binding the data to
  38518. * @param defines The generated defines for the effect
  38519. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38520. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38521. */
  38522. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38523. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38524. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38525. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38526. for (var i = 0; i < len; i++) {
  38527. var light = mesh._lightSources[i];
  38528. var iAsString = i.toString();
  38529. var scaledIntensity = light.getScaledIntensity();
  38530. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38531. MaterialHelper.BindLightProperties(light, effect, i);
  38532. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38533. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38534. if (defines["SPECULARTERM"]) {
  38535. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38536. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38537. }
  38538. // Shadows
  38539. if (scene.shadowsEnabled) {
  38540. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38541. }
  38542. light._uniformBuffer.update();
  38543. }
  38544. };
  38545. /**
  38546. * Binds the fog information from the scene to the effect for the given mesh.
  38547. * @param scene The scene the lights belongs to
  38548. * @param mesh The mesh we are binding the information to render
  38549. * @param effect The effect we are binding the data to
  38550. */
  38551. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38552. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38553. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38554. effect.setColor3("vFogColor", scene.fogColor);
  38555. }
  38556. };
  38557. /**
  38558. * Binds the bones information from the mesh to the effect.
  38559. * @param mesh The mesh we are binding the information to render
  38560. * @param effect The effect we are binding the data to
  38561. */
  38562. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38563. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38564. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38565. if (matrices && effect) {
  38566. effect.setMatrices("mBones", matrices);
  38567. }
  38568. }
  38569. };
  38570. /**
  38571. * Binds the morph targets information from the mesh to the effect.
  38572. * @param abstractMesh The mesh we are binding the information to render
  38573. * @param effect The effect we are binding the data to
  38574. */
  38575. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38576. var manager = abstractMesh.morphTargetManager;
  38577. if (!abstractMesh || !manager) {
  38578. return;
  38579. }
  38580. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38581. };
  38582. /**
  38583. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38584. * @param defines The generated defines used in the effect
  38585. * @param effect The effect we are binding the data to
  38586. * @param scene The scene we are willing to render with logarithmic scale for
  38587. */
  38588. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38589. if (defines["LOGARITHMICDEPTH"]) {
  38590. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38591. }
  38592. };
  38593. /**
  38594. * Binds the clip plane information from the scene to the effect.
  38595. * @param scene The scene the clip plane information are extracted from
  38596. * @param effect The effect we are binding the data to
  38597. */
  38598. MaterialHelper.BindClipPlane = function (effect, scene) {
  38599. if (scene.clipPlane) {
  38600. var clipPlane = scene.clipPlane;
  38601. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38602. }
  38603. };
  38604. return MaterialHelper;
  38605. }());
  38606. BABYLON.MaterialHelper = MaterialHelper;
  38607. })(BABYLON || (BABYLON = {}));
  38608. //# sourceMappingURL=babylon.materialHelper.js.map
  38609. var BABYLON;
  38610. (function (BABYLON) {
  38611. var PushMaterial = /** @class */ (function (_super) {
  38612. __extends(PushMaterial, _super);
  38613. function PushMaterial(name, scene) {
  38614. var _this = _super.call(this, name, scene) || this;
  38615. _this._normalMatrix = new BABYLON.Matrix();
  38616. _this.storeEffectOnSubMeshes = true;
  38617. return _this;
  38618. }
  38619. PushMaterial.prototype.getEffect = function () {
  38620. return this._activeEffect;
  38621. };
  38622. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38623. if (!mesh) {
  38624. return false;
  38625. }
  38626. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38627. return true;
  38628. }
  38629. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38630. };
  38631. /**
  38632. * Binds the given world matrix to the active effect
  38633. *
  38634. * @param world the matrix to bind
  38635. */
  38636. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38637. this._activeEffect.setMatrix("world", world);
  38638. };
  38639. /**
  38640. * Binds the given normal matrix to the active effect
  38641. *
  38642. * @param normalMatrix the matrix to bind
  38643. */
  38644. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38645. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38646. };
  38647. PushMaterial.prototype.bind = function (world, mesh) {
  38648. if (!mesh) {
  38649. return;
  38650. }
  38651. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38652. };
  38653. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38654. if (effect === void 0) { effect = null; }
  38655. _super.prototype._afterBind.call(this, mesh);
  38656. this.getScene()._cachedEffect = effect;
  38657. };
  38658. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38659. if (visibility === void 0) { visibility = 1; }
  38660. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38661. };
  38662. return PushMaterial;
  38663. }(BABYLON.Material));
  38664. BABYLON.PushMaterial = PushMaterial;
  38665. })(BABYLON || (BABYLON = {}));
  38666. //# sourceMappingURL=babylon.pushMaterial.js.map
  38667. var BABYLON;
  38668. (function (BABYLON) {
  38669. /** @ignore */
  38670. var StandardMaterialDefines = /** @class */ (function (_super) {
  38671. __extends(StandardMaterialDefines, _super);
  38672. function StandardMaterialDefines() {
  38673. var _this = _super.call(this) || this;
  38674. _this.MAINUV1 = false;
  38675. _this.MAINUV2 = false;
  38676. _this.DIFFUSE = false;
  38677. _this.DIFFUSEDIRECTUV = 0;
  38678. _this.AMBIENT = false;
  38679. _this.AMBIENTDIRECTUV = 0;
  38680. _this.OPACITY = false;
  38681. _this.OPACITYDIRECTUV = 0;
  38682. _this.OPACITYRGB = false;
  38683. _this.REFLECTION = false;
  38684. _this.EMISSIVE = false;
  38685. _this.EMISSIVEDIRECTUV = 0;
  38686. _this.SPECULAR = false;
  38687. _this.SPECULARDIRECTUV = 0;
  38688. _this.BUMP = false;
  38689. _this.BUMPDIRECTUV = 0;
  38690. _this.PARALLAX = false;
  38691. _this.PARALLAXOCCLUSION = false;
  38692. _this.SPECULAROVERALPHA = false;
  38693. _this.CLIPPLANE = false;
  38694. _this.ALPHATEST = false;
  38695. _this.DEPTHPREPASS = false;
  38696. _this.ALPHAFROMDIFFUSE = false;
  38697. _this.POINTSIZE = false;
  38698. _this.FOG = false;
  38699. _this.SPECULARTERM = false;
  38700. _this.DIFFUSEFRESNEL = false;
  38701. _this.OPACITYFRESNEL = false;
  38702. _this.REFLECTIONFRESNEL = false;
  38703. _this.REFRACTIONFRESNEL = false;
  38704. _this.EMISSIVEFRESNEL = false;
  38705. _this.FRESNEL = false;
  38706. _this.NORMAL = false;
  38707. _this.UV1 = false;
  38708. _this.UV2 = false;
  38709. _this.VERTEXCOLOR = false;
  38710. _this.VERTEXALPHA = false;
  38711. _this.NUM_BONE_INFLUENCERS = 0;
  38712. _this.BonesPerMesh = 0;
  38713. _this.INSTANCES = false;
  38714. _this.GLOSSINESS = false;
  38715. _this.ROUGHNESS = false;
  38716. _this.EMISSIVEASILLUMINATION = false;
  38717. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38718. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38719. _this.LIGHTMAP = false;
  38720. _this.LIGHTMAPDIRECTUV = 0;
  38721. _this.OBJECTSPACE_NORMALMAP = false;
  38722. _this.USELIGHTMAPASSHADOWMAP = false;
  38723. _this.REFLECTIONMAP_3D = false;
  38724. _this.REFLECTIONMAP_SPHERICAL = false;
  38725. _this.REFLECTIONMAP_PLANAR = false;
  38726. _this.REFLECTIONMAP_CUBIC = false;
  38727. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38728. _this.REFLECTIONMAP_PROJECTION = false;
  38729. _this.REFLECTIONMAP_SKYBOX = false;
  38730. _this.REFLECTIONMAP_EXPLICIT = false;
  38731. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38732. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38733. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38734. _this.INVERTCUBICMAP = false;
  38735. _this.LOGARITHMICDEPTH = false;
  38736. _this.REFRACTION = false;
  38737. _this.REFRACTIONMAP_3D = false;
  38738. _this.REFLECTIONOVERALPHA = false;
  38739. _this.TWOSIDEDLIGHTING = false;
  38740. _this.SHADOWFLOAT = false;
  38741. _this.MORPHTARGETS = false;
  38742. _this.MORPHTARGETS_NORMAL = false;
  38743. _this.MORPHTARGETS_TANGENT = false;
  38744. _this.NUM_MORPH_INFLUENCERS = 0;
  38745. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38746. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38747. _this.IMAGEPROCESSING = false;
  38748. _this.VIGNETTE = false;
  38749. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38750. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38751. _this.TONEMAPPING = false;
  38752. _this.CONTRAST = false;
  38753. _this.COLORCURVES = false;
  38754. _this.COLORGRADING = false;
  38755. _this.COLORGRADING3D = false;
  38756. _this.SAMPLER3DGREENDEPTH = false;
  38757. _this.SAMPLER3DBGRMAP = false;
  38758. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38759. _this.EXPOSURE = false;
  38760. _this.rebuild();
  38761. return _this;
  38762. }
  38763. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38764. var modes = [
  38765. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38766. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38767. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38768. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38769. ];
  38770. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38771. var mode = modes_1[_i];
  38772. this[mode] = (mode === modeToEnable);
  38773. }
  38774. };
  38775. return StandardMaterialDefines;
  38776. }(BABYLON.MaterialDefines));
  38777. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38778. var StandardMaterial = /** @class */ (function (_super) {
  38779. __extends(StandardMaterial, _super);
  38780. function StandardMaterial(name, scene) {
  38781. var _this = _super.call(this, name, scene) || this;
  38782. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38783. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38784. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38785. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38786. _this.specularPower = 64;
  38787. _this._useAlphaFromDiffuseTexture = false;
  38788. _this._useEmissiveAsIllumination = false;
  38789. _this._linkEmissiveWithDiffuse = false;
  38790. _this._useSpecularOverAlpha = false;
  38791. _this._useReflectionOverAlpha = false;
  38792. _this._disableLighting = false;
  38793. _this._useObjectSpaceNormalMap = false;
  38794. _this._useParallax = false;
  38795. _this._useParallaxOcclusion = false;
  38796. _this.parallaxScaleBias = 0.05;
  38797. _this._roughness = 0;
  38798. _this.indexOfRefraction = 0.98;
  38799. _this.invertRefractionY = true;
  38800. _this._useLightmapAsShadowmap = false;
  38801. _this._useReflectionFresnelFromSpecular = false;
  38802. _this._useGlossinessFromSpecularMapAlpha = false;
  38803. _this._maxSimultaneousLights = 4;
  38804. /**
  38805. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38806. */
  38807. _this._invertNormalMapX = false;
  38808. /**
  38809. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38810. */
  38811. _this._invertNormalMapY = false;
  38812. /**
  38813. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38814. */
  38815. _this._twoSidedLighting = false;
  38816. _this._renderTargets = new BABYLON.SmartArray(16);
  38817. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38818. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38819. // Setup the default processing configuration to the scene.
  38820. _this._attachImageProcessingConfiguration(null);
  38821. _this.getRenderTargetTextures = function () {
  38822. _this._renderTargets.reset();
  38823. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38824. _this._renderTargets.push(_this._reflectionTexture);
  38825. }
  38826. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38827. _this._renderTargets.push(_this._refractionTexture);
  38828. }
  38829. return _this._renderTargets;
  38830. };
  38831. return _this;
  38832. }
  38833. ;
  38834. ;
  38835. ;
  38836. ;
  38837. ;
  38838. ;
  38839. ;
  38840. ;
  38841. ;
  38842. ;
  38843. ;
  38844. ;
  38845. ;
  38846. ;
  38847. ;
  38848. ;
  38849. ;
  38850. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38851. /**
  38852. * Gets the image processing configuration used either in this material.
  38853. */
  38854. get: function () {
  38855. return this._imageProcessingConfiguration;
  38856. },
  38857. /**
  38858. * Sets the Default image processing configuration used either in the this material.
  38859. *
  38860. * If sets to null, the scene one is in use.
  38861. */
  38862. set: function (value) {
  38863. this._attachImageProcessingConfiguration(value);
  38864. // Ensure the effect will be rebuilt.
  38865. this._markAllSubMeshesAsTexturesDirty();
  38866. },
  38867. enumerable: true,
  38868. configurable: true
  38869. });
  38870. /**
  38871. * Attaches a new image processing configuration to the Standard Material.
  38872. * @param configuration
  38873. */
  38874. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38875. var _this = this;
  38876. if (configuration === this._imageProcessingConfiguration) {
  38877. return;
  38878. }
  38879. // Detaches observer.
  38880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38882. }
  38883. // Pick the scene configuration if needed.
  38884. if (!configuration) {
  38885. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38886. }
  38887. else {
  38888. this._imageProcessingConfiguration = configuration;
  38889. }
  38890. // Attaches observer.
  38891. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38892. _this._markAllSubMeshesAsImageProcessingDirty();
  38893. });
  38894. };
  38895. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38896. /**
  38897. * Gets wether the color curves effect is enabled.
  38898. */
  38899. get: function () {
  38900. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38901. },
  38902. /**
  38903. * Sets wether the color curves effect is enabled.
  38904. */
  38905. set: function (value) {
  38906. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38907. },
  38908. enumerable: true,
  38909. configurable: true
  38910. });
  38911. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38912. /**
  38913. * Gets wether the color grading effect is enabled.
  38914. */
  38915. get: function () {
  38916. return this.imageProcessingConfiguration.colorGradingEnabled;
  38917. },
  38918. /**
  38919. * Gets wether the color grading effect is enabled.
  38920. */
  38921. set: function (value) {
  38922. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38923. },
  38924. enumerable: true,
  38925. configurable: true
  38926. });
  38927. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38928. /**
  38929. * Gets wether tonemapping is enabled or not.
  38930. */
  38931. get: function () {
  38932. return this._imageProcessingConfiguration.toneMappingEnabled;
  38933. },
  38934. /**
  38935. * Sets wether tonemapping is enabled or not
  38936. */
  38937. set: function (value) {
  38938. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. ;
  38944. ;
  38945. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38946. /**
  38947. * The camera exposure used on this material.
  38948. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38949. * This corresponds to a photographic exposure.
  38950. */
  38951. get: function () {
  38952. return this._imageProcessingConfiguration.exposure;
  38953. },
  38954. /**
  38955. * The camera exposure used on this material.
  38956. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38957. * This corresponds to a photographic exposure.
  38958. */
  38959. set: function (value) {
  38960. this._imageProcessingConfiguration.exposure = value;
  38961. },
  38962. enumerable: true,
  38963. configurable: true
  38964. });
  38965. ;
  38966. ;
  38967. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38968. /**
  38969. * Gets The camera contrast used on this material.
  38970. */
  38971. get: function () {
  38972. return this._imageProcessingConfiguration.contrast;
  38973. },
  38974. /**
  38975. * Sets The camera contrast used on this material.
  38976. */
  38977. set: function (value) {
  38978. this._imageProcessingConfiguration.contrast = value;
  38979. },
  38980. enumerable: true,
  38981. configurable: true
  38982. });
  38983. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38984. /**
  38985. * Gets the Color Grading 2D Lookup Texture.
  38986. */
  38987. get: function () {
  38988. return this._imageProcessingConfiguration.colorGradingTexture;
  38989. },
  38990. /**
  38991. * Sets the Color Grading 2D Lookup Texture.
  38992. */
  38993. set: function (value) {
  38994. this._imageProcessingConfiguration.colorGradingTexture = value;
  38995. },
  38996. enumerable: true,
  38997. configurable: true
  38998. });
  38999. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39000. /**
  39001. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39002. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39003. * 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;
  39004. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39005. */
  39006. get: function () {
  39007. return this._imageProcessingConfiguration.colorCurves;
  39008. },
  39009. /**
  39010. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39011. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39012. * 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;
  39013. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39014. */
  39015. set: function (value) {
  39016. this._imageProcessingConfiguration.colorCurves = value;
  39017. },
  39018. enumerable: true,
  39019. configurable: true
  39020. });
  39021. StandardMaterial.prototype.getClassName = function () {
  39022. return "StandardMaterial";
  39023. };
  39024. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39025. get: function () {
  39026. return this._useLogarithmicDepth;
  39027. },
  39028. set: function (value) {
  39029. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39030. this._markAllSubMeshesAsMiscDirty();
  39031. },
  39032. enumerable: true,
  39033. configurable: true
  39034. });
  39035. StandardMaterial.prototype.needAlphaBlending = function () {
  39036. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39037. };
  39038. StandardMaterial.prototype.needAlphaTesting = function () {
  39039. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39040. };
  39041. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39042. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39043. };
  39044. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39045. return this._diffuseTexture;
  39046. };
  39047. /**
  39048. * Child classes can use it to update shaders
  39049. */
  39050. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39051. if (useInstances === void 0) { useInstances = false; }
  39052. if (subMesh.effect && this.isFrozen) {
  39053. if (this._wasPreviouslyReady && subMesh.effect) {
  39054. return true;
  39055. }
  39056. }
  39057. if (!subMesh._materialDefines) {
  39058. subMesh._materialDefines = new StandardMaterialDefines();
  39059. }
  39060. var scene = this.getScene();
  39061. var defines = subMesh._materialDefines;
  39062. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39063. if (defines._renderId === scene.getRenderId()) {
  39064. return true;
  39065. }
  39066. }
  39067. var engine = scene.getEngine();
  39068. // Lights
  39069. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39070. // Textures
  39071. if (defines._areTexturesDirty) {
  39072. defines._needUVs = false;
  39073. defines.MAINUV1 = false;
  39074. defines.MAINUV2 = false;
  39075. if (scene.texturesEnabled) {
  39076. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39077. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39078. return false;
  39079. }
  39080. else {
  39081. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39082. }
  39083. }
  39084. else {
  39085. defines.DIFFUSE = false;
  39086. }
  39087. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39088. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39089. return false;
  39090. }
  39091. else {
  39092. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39093. }
  39094. }
  39095. else {
  39096. defines.AMBIENT = false;
  39097. }
  39098. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39099. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39100. return false;
  39101. }
  39102. else {
  39103. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39104. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39105. }
  39106. }
  39107. else {
  39108. defines.OPACITY = false;
  39109. }
  39110. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39111. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39112. return false;
  39113. }
  39114. else {
  39115. defines._needNormals = true;
  39116. defines.REFLECTION = true;
  39117. defines.ROUGHNESS = (this._roughness > 0);
  39118. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39119. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39120. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39121. switch (this._reflectionTexture.coordinatesMode) {
  39122. case BABYLON.Texture.CUBIC_MODE:
  39123. case BABYLON.Texture.INVCUBIC_MODE:
  39124. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39125. break;
  39126. case BABYLON.Texture.EXPLICIT_MODE:
  39127. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39128. break;
  39129. case BABYLON.Texture.PLANAR_MODE:
  39130. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39131. break;
  39132. case BABYLON.Texture.PROJECTION_MODE:
  39133. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39134. break;
  39135. case BABYLON.Texture.SKYBOX_MODE:
  39136. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39137. break;
  39138. case BABYLON.Texture.SPHERICAL_MODE:
  39139. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39140. break;
  39141. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39142. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39143. break;
  39144. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39145. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39146. break;
  39147. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39148. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39149. break;
  39150. }
  39151. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39152. }
  39153. }
  39154. else {
  39155. defines.REFLECTION = false;
  39156. }
  39157. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39158. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39159. return false;
  39160. }
  39161. else {
  39162. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39163. }
  39164. }
  39165. else {
  39166. defines.EMISSIVE = false;
  39167. }
  39168. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39169. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39170. return false;
  39171. }
  39172. else {
  39173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39174. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39175. }
  39176. }
  39177. else {
  39178. defines.LIGHTMAP = false;
  39179. }
  39180. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39181. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39182. return false;
  39183. }
  39184. else {
  39185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39186. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39187. }
  39188. }
  39189. else {
  39190. defines.SPECULAR = false;
  39191. }
  39192. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39193. // Bump texure can not be not blocking.
  39194. if (!this._bumpTexture.isReady()) {
  39195. return false;
  39196. }
  39197. else {
  39198. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39199. defines.PARALLAX = this._useParallax;
  39200. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39201. }
  39202. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39203. }
  39204. else {
  39205. defines.BUMP = false;
  39206. }
  39207. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39208. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39209. return false;
  39210. }
  39211. else {
  39212. defines._needUVs = true;
  39213. defines.REFRACTION = true;
  39214. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39215. }
  39216. }
  39217. else {
  39218. defines.REFRACTION = false;
  39219. }
  39220. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39221. }
  39222. else {
  39223. defines.DIFFUSE = false;
  39224. defines.AMBIENT = false;
  39225. defines.OPACITY = false;
  39226. defines.REFLECTION = false;
  39227. defines.EMISSIVE = false;
  39228. defines.LIGHTMAP = false;
  39229. defines.BUMP = false;
  39230. defines.REFRACTION = false;
  39231. }
  39232. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39233. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39234. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39235. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39236. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39237. }
  39238. if (defines._areImageProcessingDirty) {
  39239. if (!this._imageProcessingConfiguration.isReady()) {
  39240. return false;
  39241. }
  39242. this._imageProcessingConfiguration.prepareDefines(defines);
  39243. }
  39244. if (defines._areFresnelDirty) {
  39245. if (StandardMaterial.FresnelEnabled) {
  39246. // Fresnel
  39247. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39248. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39249. this._reflectionFresnelParameters) {
  39250. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39251. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39252. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39253. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39254. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39255. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39256. defines._needNormals = true;
  39257. defines.FRESNEL = true;
  39258. }
  39259. }
  39260. else {
  39261. defines.FRESNEL = false;
  39262. }
  39263. }
  39264. // Misc.
  39265. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39266. // Attribs
  39267. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39268. // Values that need to be evaluated on every frame
  39269. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39270. // Get correct effect
  39271. if (defines.isDirty) {
  39272. defines.markAsProcessed();
  39273. scene.resetCachedMaterial();
  39274. // Fallbacks
  39275. var fallbacks = new BABYLON.EffectFallbacks();
  39276. if (defines.REFLECTION) {
  39277. fallbacks.addFallback(0, "REFLECTION");
  39278. }
  39279. if (defines.SPECULAR) {
  39280. fallbacks.addFallback(0, "SPECULAR");
  39281. }
  39282. if (defines.BUMP) {
  39283. fallbacks.addFallback(0, "BUMP");
  39284. }
  39285. if (defines.PARALLAX) {
  39286. fallbacks.addFallback(1, "PARALLAX");
  39287. }
  39288. if (defines.PARALLAXOCCLUSION) {
  39289. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39290. }
  39291. if (defines.SPECULAROVERALPHA) {
  39292. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39293. }
  39294. if (defines.FOG) {
  39295. fallbacks.addFallback(1, "FOG");
  39296. }
  39297. if (defines.POINTSIZE) {
  39298. fallbacks.addFallback(0, "POINTSIZE");
  39299. }
  39300. if (defines.LOGARITHMICDEPTH) {
  39301. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39302. }
  39303. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39304. if (defines.SPECULARTERM) {
  39305. fallbacks.addFallback(0, "SPECULARTERM");
  39306. }
  39307. if (defines.DIFFUSEFRESNEL) {
  39308. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39309. }
  39310. if (defines.OPACITYFRESNEL) {
  39311. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39312. }
  39313. if (defines.REFLECTIONFRESNEL) {
  39314. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39315. }
  39316. if (defines.EMISSIVEFRESNEL) {
  39317. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39318. }
  39319. if (defines.FRESNEL) {
  39320. fallbacks.addFallback(4, "FRESNEL");
  39321. }
  39322. //Attributes
  39323. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39324. if (defines.NORMAL) {
  39325. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39326. }
  39327. if (defines.UV1) {
  39328. attribs.push(BABYLON.VertexBuffer.UVKind);
  39329. }
  39330. if (defines.UV2) {
  39331. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39332. }
  39333. if (defines.VERTEXCOLOR) {
  39334. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39335. }
  39336. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39337. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39338. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39339. var shaderName = "default";
  39340. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39341. "vFogInfos", "vFogColor", "pointSize",
  39342. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39343. "mBones",
  39344. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39345. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39346. "vReflectionPosition", "vReflectionSize",
  39347. "logarithmicDepthConstant", "vTangentSpaceParams"
  39348. ];
  39349. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39350. var uniformBuffers = ["Material", "Scene"];
  39351. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39352. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39353. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39354. uniformsNames: uniforms,
  39355. uniformBuffersNames: uniformBuffers,
  39356. samplers: samplers,
  39357. defines: defines,
  39358. maxSimultaneousLights: this._maxSimultaneousLights
  39359. });
  39360. if (this.customShaderNameResolve) {
  39361. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39362. }
  39363. var join = defines.toString();
  39364. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39365. attributes: attribs,
  39366. uniformsNames: uniforms,
  39367. uniformBuffersNames: uniformBuffers,
  39368. samplers: samplers,
  39369. defines: join,
  39370. fallbacks: fallbacks,
  39371. onCompiled: this.onCompiled,
  39372. onError: this.onError,
  39373. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39374. }, engine), defines);
  39375. this.buildUniformLayout();
  39376. }
  39377. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39378. return false;
  39379. }
  39380. defines._renderId = scene.getRenderId();
  39381. this._wasPreviouslyReady = true;
  39382. return true;
  39383. };
  39384. StandardMaterial.prototype.buildUniformLayout = function () {
  39385. // Order is important !
  39386. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39387. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39388. this._uniformBuffer.addUniform("opacityParts", 4);
  39389. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39390. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39391. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39392. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39393. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39394. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39395. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39396. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39397. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39398. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39399. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39400. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39401. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39402. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39403. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39404. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39405. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39406. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39407. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39408. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39409. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39410. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39411. this._uniformBuffer.addUniform("specularMatrix", 16);
  39412. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39413. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39414. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39415. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39416. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39417. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39418. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39419. this._uniformBuffer.addUniform("pointSize", 1);
  39420. this._uniformBuffer.create();
  39421. };
  39422. StandardMaterial.prototype.unbind = function () {
  39423. if (this._activeEffect) {
  39424. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39425. this._activeEffect.setTexture("reflection2DSampler", null);
  39426. }
  39427. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39428. this._activeEffect.setTexture("refraction2DSampler", null);
  39429. }
  39430. }
  39431. _super.prototype.unbind.call(this);
  39432. };
  39433. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39434. var scene = this.getScene();
  39435. var defines = subMesh._materialDefines;
  39436. if (!defines) {
  39437. return;
  39438. }
  39439. var effect = subMesh.effect;
  39440. if (!effect) {
  39441. return;
  39442. }
  39443. this._activeEffect = effect;
  39444. // Matrices
  39445. this.bindOnlyWorldMatrix(world);
  39446. // Normal Matrix
  39447. if (defines.OBJECTSPACE_NORMALMAP) {
  39448. world.toNormalMatrix(this._normalMatrix);
  39449. this.bindOnlyNormalMatrix(this._normalMatrix);
  39450. }
  39451. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39452. // Bones
  39453. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39454. if (mustRebind) {
  39455. this._uniformBuffer.bindToEffect(effect, "Material");
  39456. this.bindViewProjection(effect);
  39457. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39458. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39459. // Fresnel
  39460. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39461. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39462. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39463. }
  39464. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39465. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39466. }
  39467. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39468. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39469. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39470. }
  39471. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39472. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39473. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39474. }
  39475. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39476. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39477. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39478. }
  39479. }
  39480. // Textures
  39481. if (scene.texturesEnabled) {
  39482. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39483. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39484. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39485. }
  39486. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39487. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39488. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39489. }
  39490. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39491. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39492. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39493. }
  39494. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39495. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39496. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39497. if (this._reflectionTexture.boundingBoxSize) {
  39498. var cubeTexture = this._reflectionTexture;
  39499. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39500. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39501. }
  39502. }
  39503. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39504. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39505. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39506. }
  39507. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39508. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39509. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39510. }
  39511. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39512. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39513. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39514. }
  39515. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39516. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39517. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39518. if (scene._mirroredCameraPosition) {
  39519. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39520. }
  39521. else {
  39522. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39523. }
  39524. }
  39525. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39526. var depth = 1.0;
  39527. if (!this._refractionTexture.isCube) {
  39528. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39529. if (this._refractionTexture.depth) {
  39530. depth = this._refractionTexture.depth;
  39531. }
  39532. }
  39533. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39534. }
  39535. }
  39536. // Point size
  39537. if (this.pointsCloud) {
  39538. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39539. }
  39540. if (defines.SPECULARTERM) {
  39541. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39542. }
  39543. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39544. // Diffuse
  39545. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39546. }
  39547. // Textures
  39548. if (scene.texturesEnabled) {
  39549. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39550. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39551. }
  39552. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39553. effect.setTexture("ambientSampler", this._ambientTexture);
  39554. }
  39555. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39556. effect.setTexture("opacitySampler", this._opacityTexture);
  39557. }
  39558. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39559. if (this._reflectionTexture.isCube) {
  39560. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39561. }
  39562. else {
  39563. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39564. }
  39565. }
  39566. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39567. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39568. }
  39569. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39570. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39571. }
  39572. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39573. effect.setTexture("specularSampler", this._specularTexture);
  39574. }
  39575. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39576. effect.setTexture("bumpSampler", this._bumpTexture);
  39577. }
  39578. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39579. var depth = 1.0;
  39580. if (this._refractionTexture.isCube) {
  39581. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39582. }
  39583. else {
  39584. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39585. }
  39586. }
  39587. }
  39588. // Clip plane
  39589. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39590. // Colors
  39591. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39592. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39593. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39594. }
  39595. if (mustRebind || !this.isFrozen) {
  39596. // Lights
  39597. if (scene.lightsEnabled && !this._disableLighting) {
  39598. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39599. }
  39600. // View
  39601. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39602. this.bindView(effect);
  39603. }
  39604. // Fog
  39605. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39606. // Morph targets
  39607. if (defines.NUM_MORPH_INFLUENCERS) {
  39608. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39609. }
  39610. // Log. depth
  39611. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39612. // image processing
  39613. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39614. this._imageProcessingConfiguration.bind(this._activeEffect);
  39615. }
  39616. }
  39617. this._uniformBuffer.update();
  39618. this._afterBind(mesh, this._activeEffect);
  39619. };
  39620. StandardMaterial.prototype.getAnimatables = function () {
  39621. var results = [];
  39622. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39623. results.push(this._diffuseTexture);
  39624. }
  39625. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39626. results.push(this._ambientTexture);
  39627. }
  39628. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39629. results.push(this._opacityTexture);
  39630. }
  39631. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39632. results.push(this._reflectionTexture);
  39633. }
  39634. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39635. results.push(this._emissiveTexture);
  39636. }
  39637. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39638. results.push(this._specularTexture);
  39639. }
  39640. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39641. results.push(this._bumpTexture);
  39642. }
  39643. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39644. results.push(this._lightmapTexture);
  39645. }
  39646. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39647. results.push(this._refractionTexture);
  39648. }
  39649. return results;
  39650. };
  39651. StandardMaterial.prototype.getActiveTextures = function () {
  39652. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39653. if (this._diffuseTexture) {
  39654. activeTextures.push(this._diffuseTexture);
  39655. }
  39656. if (this._ambientTexture) {
  39657. activeTextures.push(this._ambientTexture);
  39658. }
  39659. if (this._opacityTexture) {
  39660. activeTextures.push(this._opacityTexture);
  39661. }
  39662. if (this._reflectionTexture) {
  39663. activeTextures.push(this._reflectionTexture);
  39664. }
  39665. if (this._emissiveTexture) {
  39666. activeTextures.push(this._emissiveTexture);
  39667. }
  39668. if (this._specularTexture) {
  39669. activeTextures.push(this._specularTexture);
  39670. }
  39671. if (this._bumpTexture) {
  39672. activeTextures.push(this._bumpTexture);
  39673. }
  39674. if (this._lightmapTexture) {
  39675. activeTextures.push(this._lightmapTexture);
  39676. }
  39677. if (this._refractionTexture) {
  39678. activeTextures.push(this._refractionTexture);
  39679. }
  39680. return activeTextures;
  39681. };
  39682. StandardMaterial.prototype.hasTexture = function (texture) {
  39683. if (_super.prototype.hasTexture.call(this, texture)) {
  39684. return true;
  39685. }
  39686. if (this._diffuseTexture === texture) {
  39687. return true;
  39688. }
  39689. if (this._ambientTexture === texture) {
  39690. return true;
  39691. }
  39692. if (this._opacityTexture === texture) {
  39693. return true;
  39694. }
  39695. if (this._reflectionTexture === texture) {
  39696. return true;
  39697. }
  39698. if (this._emissiveTexture === texture) {
  39699. return true;
  39700. }
  39701. if (this._specularTexture === texture) {
  39702. return true;
  39703. }
  39704. if (this._bumpTexture === texture) {
  39705. return true;
  39706. }
  39707. if (this._lightmapTexture === texture) {
  39708. return true;
  39709. }
  39710. if (this._refractionTexture === texture) {
  39711. return true;
  39712. }
  39713. return false;
  39714. };
  39715. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39716. if (forceDisposeTextures) {
  39717. if (this._diffuseTexture) {
  39718. this._diffuseTexture.dispose();
  39719. }
  39720. if (this._ambientTexture) {
  39721. this._ambientTexture.dispose();
  39722. }
  39723. if (this._opacityTexture) {
  39724. this._opacityTexture.dispose();
  39725. }
  39726. if (this._reflectionTexture) {
  39727. this._reflectionTexture.dispose();
  39728. }
  39729. if (this._emissiveTexture) {
  39730. this._emissiveTexture.dispose();
  39731. }
  39732. if (this._specularTexture) {
  39733. this._specularTexture.dispose();
  39734. }
  39735. if (this._bumpTexture) {
  39736. this._bumpTexture.dispose();
  39737. }
  39738. if (this._lightmapTexture) {
  39739. this._lightmapTexture.dispose();
  39740. }
  39741. if (this._refractionTexture) {
  39742. this._refractionTexture.dispose();
  39743. }
  39744. }
  39745. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39746. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39747. }
  39748. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39749. };
  39750. StandardMaterial.prototype.clone = function (name) {
  39751. var _this = this;
  39752. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39753. result.name = name;
  39754. result.id = name;
  39755. return result;
  39756. };
  39757. StandardMaterial.prototype.serialize = function () {
  39758. return BABYLON.SerializationHelper.Serialize(this);
  39759. };
  39760. // Statics
  39761. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39762. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39763. };
  39764. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39765. get: function () {
  39766. return StandardMaterial._DiffuseTextureEnabled;
  39767. },
  39768. set: function (value) {
  39769. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39770. return;
  39771. }
  39772. StandardMaterial._DiffuseTextureEnabled = value;
  39773. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39774. },
  39775. enumerable: true,
  39776. configurable: true
  39777. });
  39778. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39779. get: function () {
  39780. return StandardMaterial._AmbientTextureEnabled;
  39781. },
  39782. set: function (value) {
  39783. if (StandardMaterial._AmbientTextureEnabled === value) {
  39784. return;
  39785. }
  39786. StandardMaterial._AmbientTextureEnabled = value;
  39787. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39788. },
  39789. enumerable: true,
  39790. configurable: true
  39791. });
  39792. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39793. get: function () {
  39794. return StandardMaterial._OpacityTextureEnabled;
  39795. },
  39796. set: function (value) {
  39797. if (StandardMaterial._OpacityTextureEnabled === value) {
  39798. return;
  39799. }
  39800. StandardMaterial._OpacityTextureEnabled = value;
  39801. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39802. },
  39803. enumerable: true,
  39804. configurable: true
  39805. });
  39806. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39807. get: function () {
  39808. return StandardMaterial._ReflectionTextureEnabled;
  39809. },
  39810. set: function (value) {
  39811. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39812. return;
  39813. }
  39814. StandardMaterial._ReflectionTextureEnabled = value;
  39815. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39816. },
  39817. enumerable: true,
  39818. configurable: true
  39819. });
  39820. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39821. get: function () {
  39822. return StandardMaterial._EmissiveTextureEnabled;
  39823. },
  39824. set: function (value) {
  39825. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39826. return;
  39827. }
  39828. StandardMaterial._EmissiveTextureEnabled = value;
  39829. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39830. },
  39831. enumerable: true,
  39832. configurable: true
  39833. });
  39834. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39835. get: function () {
  39836. return StandardMaterial._SpecularTextureEnabled;
  39837. },
  39838. set: function (value) {
  39839. if (StandardMaterial._SpecularTextureEnabled === value) {
  39840. return;
  39841. }
  39842. StandardMaterial._SpecularTextureEnabled = value;
  39843. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39844. },
  39845. enumerable: true,
  39846. configurable: true
  39847. });
  39848. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39849. get: function () {
  39850. return StandardMaterial._BumpTextureEnabled;
  39851. },
  39852. set: function (value) {
  39853. if (StandardMaterial._BumpTextureEnabled === value) {
  39854. return;
  39855. }
  39856. StandardMaterial._BumpTextureEnabled = value;
  39857. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39858. },
  39859. enumerable: true,
  39860. configurable: true
  39861. });
  39862. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39863. get: function () {
  39864. return StandardMaterial._LightmapTextureEnabled;
  39865. },
  39866. set: function (value) {
  39867. if (StandardMaterial._LightmapTextureEnabled === value) {
  39868. return;
  39869. }
  39870. StandardMaterial._LightmapTextureEnabled = value;
  39871. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39872. },
  39873. enumerable: true,
  39874. configurable: true
  39875. });
  39876. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39877. get: function () {
  39878. return StandardMaterial._RefractionTextureEnabled;
  39879. },
  39880. set: function (value) {
  39881. if (StandardMaterial._RefractionTextureEnabled === value) {
  39882. return;
  39883. }
  39884. StandardMaterial._RefractionTextureEnabled = value;
  39885. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39886. },
  39887. enumerable: true,
  39888. configurable: true
  39889. });
  39890. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39891. get: function () {
  39892. return StandardMaterial._ColorGradingTextureEnabled;
  39893. },
  39894. set: function (value) {
  39895. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39896. return;
  39897. }
  39898. StandardMaterial._ColorGradingTextureEnabled = value;
  39899. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39900. },
  39901. enumerable: true,
  39902. configurable: true
  39903. });
  39904. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39905. get: function () {
  39906. return StandardMaterial._FresnelEnabled;
  39907. },
  39908. set: function (value) {
  39909. if (StandardMaterial._FresnelEnabled === value) {
  39910. return;
  39911. }
  39912. StandardMaterial._FresnelEnabled = value;
  39913. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39914. },
  39915. enumerable: true,
  39916. configurable: true
  39917. });
  39918. // Flags used to enable or disable a type of texture for all Standard Materials
  39919. StandardMaterial._DiffuseTextureEnabled = true;
  39920. StandardMaterial._AmbientTextureEnabled = true;
  39921. StandardMaterial._OpacityTextureEnabled = true;
  39922. StandardMaterial._ReflectionTextureEnabled = true;
  39923. StandardMaterial._EmissiveTextureEnabled = true;
  39924. StandardMaterial._SpecularTextureEnabled = true;
  39925. StandardMaterial._BumpTextureEnabled = true;
  39926. StandardMaterial._LightmapTextureEnabled = true;
  39927. StandardMaterial._RefractionTextureEnabled = true;
  39928. StandardMaterial._ColorGradingTextureEnabled = true;
  39929. StandardMaterial._FresnelEnabled = true;
  39930. __decorate([
  39931. BABYLON.serializeAsTexture("diffuseTexture")
  39932. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39933. __decorate([
  39934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39935. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39936. __decorate([
  39937. BABYLON.serializeAsTexture("ambientTexture")
  39938. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39939. __decorate([
  39940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39941. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39942. __decorate([
  39943. BABYLON.serializeAsTexture("opacityTexture")
  39944. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39945. __decorate([
  39946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39947. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39948. __decorate([
  39949. BABYLON.serializeAsTexture("reflectionTexture")
  39950. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39951. __decorate([
  39952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39953. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39954. __decorate([
  39955. BABYLON.serializeAsTexture("emissiveTexture")
  39956. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39957. __decorate([
  39958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39959. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39960. __decorate([
  39961. BABYLON.serializeAsTexture("specularTexture")
  39962. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39963. __decorate([
  39964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39965. ], StandardMaterial.prototype, "specularTexture", void 0);
  39966. __decorate([
  39967. BABYLON.serializeAsTexture("bumpTexture")
  39968. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39969. __decorate([
  39970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39971. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39972. __decorate([
  39973. BABYLON.serializeAsTexture("lightmapTexture")
  39974. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39975. __decorate([
  39976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39977. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39978. __decorate([
  39979. BABYLON.serializeAsTexture("refractionTexture")
  39980. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39981. __decorate([
  39982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39983. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39984. __decorate([
  39985. BABYLON.serializeAsColor3("ambient")
  39986. ], StandardMaterial.prototype, "ambientColor", void 0);
  39987. __decorate([
  39988. BABYLON.serializeAsColor3("diffuse")
  39989. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39990. __decorate([
  39991. BABYLON.serializeAsColor3("specular")
  39992. ], StandardMaterial.prototype, "specularColor", void 0);
  39993. __decorate([
  39994. BABYLON.serializeAsColor3("emissive")
  39995. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39996. __decorate([
  39997. BABYLON.serialize()
  39998. ], StandardMaterial.prototype, "specularPower", void 0);
  39999. __decorate([
  40000. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40001. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40002. __decorate([
  40003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40004. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40005. __decorate([
  40006. BABYLON.serialize("useEmissiveAsIllumination")
  40007. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40008. __decorate([
  40009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40010. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40011. __decorate([
  40012. BABYLON.serialize("linkEmissiveWithDiffuse")
  40013. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40014. __decorate([
  40015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40016. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40017. __decorate([
  40018. BABYLON.serialize("useSpecularOverAlpha")
  40019. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40020. __decorate([
  40021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40022. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40023. __decorate([
  40024. BABYLON.serialize("useReflectionOverAlpha")
  40025. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40026. __decorate([
  40027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40028. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40029. __decorate([
  40030. BABYLON.serialize("disableLighting")
  40031. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40032. __decorate([
  40033. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40034. ], StandardMaterial.prototype, "disableLighting", void 0);
  40035. __decorate([
  40036. BABYLON.serialize("useObjectSpaceNormalMap")
  40037. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40038. __decorate([
  40039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40040. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40041. __decorate([
  40042. BABYLON.serialize("useParallax")
  40043. ], StandardMaterial.prototype, "_useParallax", void 0);
  40044. __decorate([
  40045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40046. ], StandardMaterial.prototype, "useParallax", void 0);
  40047. __decorate([
  40048. BABYLON.serialize("useParallaxOcclusion")
  40049. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40050. __decorate([
  40051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40052. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40053. __decorate([
  40054. BABYLON.serialize()
  40055. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40056. __decorate([
  40057. BABYLON.serialize("roughness")
  40058. ], StandardMaterial.prototype, "_roughness", void 0);
  40059. __decorate([
  40060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40061. ], StandardMaterial.prototype, "roughness", void 0);
  40062. __decorate([
  40063. BABYLON.serialize()
  40064. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40065. __decorate([
  40066. BABYLON.serialize()
  40067. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40068. __decorate([
  40069. BABYLON.serialize("useLightmapAsShadowmap")
  40070. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40071. __decorate([
  40072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40073. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40074. __decorate([
  40075. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40076. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40077. __decorate([
  40078. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40079. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40080. __decorate([
  40081. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40082. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40083. __decorate([
  40084. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40085. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40086. __decorate([
  40087. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40088. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40089. __decorate([
  40090. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40091. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40092. __decorate([
  40093. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40094. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40095. __decorate([
  40096. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40097. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40098. __decorate([
  40099. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40100. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40101. __decorate([
  40102. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40103. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40104. __decorate([
  40105. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40106. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40107. __decorate([
  40108. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40109. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40110. __decorate([
  40111. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40112. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40113. __decorate([
  40114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40115. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40116. __decorate([
  40117. BABYLON.serialize("maxSimultaneousLights")
  40118. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40119. __decorate([
  40120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40121. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40122. __decorate([
  40123. BABYLON.serialize("invertNormalMapX")
  40124. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40125. __decorate([
  40126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40127. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40128. __decorate([
  40129. BABYLON.serialize("invertNormalMapY")
  40130. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40131. __decorate([
  40132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40133. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40134. __decorate([
  40135. BABYLON.serialize("twoSidedLighting")
  40136. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40137. __decorate([
  40138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40139. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40140. __decorate([
  40141. BABYLON.serialize()
  40142. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40143. return StandardMaterial;
  40144. }(BABYLON.PushMaterial));
  40145. BABYLON.StandardMaterial = StandardMaterial;
  40146. })(BABYLON || (BABYLON = {}));
  40147. //# sourceMappingURL=babylon.standardMaterial.js.map
  40148. var BABYLON;
  40149. (function (BABYLON) {
  40150. /**
  40151. * Manages the defines for the PBR Material.
  40152. */
  40153. var PBRMaterialDefines = /** @class */ (function (_super) {
  40154. __extends(PBRMaterialDefines, _super);
  40155. /**
  40156. * Initializes the PBR Material defines.
  40157. */
  40158. function PBRMaterialDefines() {
  40159. var _this = _super.call(this) || this;
  40160. _this.PBR = true;
  40161. _this.MAINUV1 = false;
  40162. _this.MAINUV2 = false;
  40163. _this.UV1 = false;
  40164. _this.UV2 = false;
  40165. _this.ALBEDO = false;
  40166. _this.ALBEDODIRECTUV = 0;
  40167. _this.VERTEXCOLOR = false;
  40168. _this.AMBIENT = false;
  40169. _this.AMBIENTDIRECTUV = 0;
  40170. _this.AMBIENTINGRAYSCALE = false;
  40171. _this.OPACITY = false;
  40172. _this.VERTEXALPHA = false;
  40173. _this.OPACITYDIRECTUV = 0;
  40174. _this.OPACITYRGB = false;
  40175. _this.ALPHATEST = false;
  40176. _this.DEPTHPREPASS = false;
  40177. _this.ALPHABLEND = false;
  40178. _this.ALPHAFROMALBEDO = false;
  40179. _this.ALPHATESTVALUE = 0.5;
  40180. _this.SPECULAROVERALPHA = false;
  40181. _this.RADIANCEOVERALPHA = false;
  40182. _this.ALPHAFRESNEL = false;
  40183. _this.LINEARALPHAFRESNEL = false;
  40184. _this.PREMULTIPLYALPHA = false;
  40185. _this.EMISSIVE = false;
  40186. _this.EMISSIVEDIRECTUV = 0;
  40187. _this.REFLECTIVITY = false;
  40188. _this.REFLECTIVITYDIRECTUV = 0;
  40189. _this.SPECULARTERM = false;
  40190. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40191. _this.MICROSURFACEAUTOMATIC = false;
  40192. _this.LODBASEDMICROSFURACE = false;
  40193. _this.MICROSURFACEMAP = false;
  40194. _this.MICROSURFACEMAPDIRECTUV = 0;
  40195. _this.METALLICWORKFLOW = false;
  40196. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40197. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40198. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40199. _this.AOSTOREINMETALMAPRED = false;
  40200. _this.ENVIRONMENTBRDF = false;
  40201. _this.NORMAL = false;
  40202. _this.TANGENT = false;
  40203. _this.BUMP = false;
  40204. _this.BUMPDIRECTUV = 0;
  40205. _this.OBJECTSPACE_NORMALMAP = false;
  40206. _this.PARALLAX = false;
  40207. _this.PARALLAXOCCLUSION = false;
  40208. _this.NORMALXYSCALE = true;
  40209. _this.LIGHTMAP = false;
  40210. _this.LIGHTMAPDIRECTUV = 0;
  40211. _this.USELIGHTMAPASSHADOWMAP = false;
  40212. _this.REFLECTION = false;
  40213. _this.REFLECTIONMAP_3D = false;
  40214. _this.REFLECTIONMAP_SPHERICAL = false;
  40215. _this.REFLECTIONMAP_PLANAR = false;
  40216. _this.REFLECTIONMAP_CUBIC = false;
  40217. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40218. _this.REFLECTIONMAP_PROJECTION = false;
  40219. _this.REFLECTIONMAP_SKYBOX = false;
  40220. _this.REFLECTIONMAP_EXPLICIT = false;
  40221. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40222. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40223. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40224. _this.INVERTCUBICMAP = false;
  40225. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40226. _this.USESPHERICALINVERTEX = false;
  40227. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40228. _this.LODINREFLECTIONALPHA = false;
  40229. _this.GAMMAREFLECTION = false;
  40230. _this.RADIANCEOCCLUSION = false;
  40231. _this.HORIZONOCCLUSION = false;
  40232. _this.REFRACTION = false;
  40233. _this.REFRACTIONMAP_3D = false;
  40234. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40235. _this.LODINREFRACTIONALPHA = false;
  40236. _this.GAMMAREFRACTION = false;
  40237. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40238. _this.INSTANCES = false;
  40239. _this.NUM_BONE_INFLUENCERS = 0;
  40240. _this.BonesPerMesh = 0;
  40241. _this.NONUNIFORMSCALING = false;
  40242. _this.MORPHTARGETS = false;
  40243. _this.MORPHTARGETS_NORMAL = false;
  40244. _this.MORPHTARGETS_TANGENT = false;
  40245. _this.NUM_MORPH_INFLUENCERS = 0;
  40246. _this.IMAGEPROCESSING = false;
  40247. _this.VIGNETTE = false;
  40248. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40249. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40250. _this.TONEMAPPING = false;
  40251. _this.CONTRAST = false;
  40252. _this.COLORCURVES = false;
  40253. _this.COLORGRADING = false;
  40254. _this.COLORGRADING3D = false;
  40255. _this.SAMPLER3DGREENDEPTH = false;
  40256. _this.SAMPLER3DBGRMAP = false;
  40257. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40258. _this.EXPOSURE = false;
  40259. _this.USEPHYSICALLIGHTFALLOFF = false;
  40260. _this.TWOSIDEDLIGHTING = false;
  40261. _this.SHADOWFLOAT = false;
  40262. _this.CLIPPLANE = false;
  40263. _this.POINTSIZE = false;
  40264. _this.FOG = false;
  40265. _this.LOGARITHMICDEPTH = false;
  40266. _this.FORCENORMALFORWARD = false;
  40267. _this.rebuild();
  40268. return _this;
  40269. }
  40270. /**
  40271. * Resets the PBR Material defines.
  40272. */
  40273. PBRMaterialDefines.prototype.reset = function () {
  40274. _super.prototype.reset.call(this);
  40275. this.ALPHATESTVALUE = 0.5;
  40276. this.PBR = true;
  40277. };
  40278. return PBRMaterialDefines;
  40279. }(BABYLON.MaterialDefines));
  40280. /**
  40281. * The Physically based material base class of BJS.
  40282. *
  40283. * This offers the main features of a standard PBR material.
  40284. * For more information, please refer to the documentation :
  40285. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40286. */
  40287. var PBRBaseMaterial = /** @class */ (function (_super) {
  40288. __extends(PBRBaseMaterial, _super);
  40289. /**
  40290. * Instantiates a new PBRMaterial instance.
  40291. *
  40292. * @param name The material name
  40293. * @param scene The scene the material will be use in.
  40294. */
  40295. function PBRBaseMaterial(name, scene) {
  40296. var _this = _super.call(this, name, scene) || this;
  40297. /**
  40298. * Intensity of the direct lights e.g. the four lights available in your scene.
  40299. * This impacts both the direct diffuse and specular highlights.
  40300. */
  40301. _this._directIntensity = 1.0;
  40302. /**
  40303. * Intensity of the emissive part of the material.
  40304. * This helps controlling the emissive effect without modifying the emissive color.
  40305. */
  40306. _this._emissiveIntensity = 1.0;
  40307. /**
  40308. * Intensity of the environment e.g. how much the environment will light the object
  40309. * either through harmonics for rough material or through the refelction for shiny ones.
  40310. */
  40311. _this._environmentIntensity = 1.0;
  40312. /**
  40313. * This is a special control allowing the reduction of the specular highlights coming from the
  40314. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40315. */
  40316. _this._specularIntensity = 1.0;
  40317. /**
  40318. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40319. */
  40320. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40321. /**
  40322. * Debug Control allowing disabling the bump map on this material.
  40323. */
  40324. _this._disableBumpMap = false;
  40325. /**
  40326. * AKA Occlusion Texture Intensity in other nomenclature.
  40327. */
  40328. _this._ambientTextureStrength = 1.0;
  40329. /**
  40330. * The color of a material in ambient lighting.
  40331. */
  40332. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40333. /**
  40334. * AKA Diffuse Color in other nomenclature.
  40335. */
  40336. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40337. /**
  40338. * AKA Specular Color in other nomenclature.
  40339. */
  40340. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40341. /**
  40342. * The color applied when light is reflected from a material.
  40343. */
  40344. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40345. /**
  40346. * The color applied when light is emitted from a material.
  40347. */
  40348. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40349. /**
  40350. * AKA Glossiness in other nomenclature.
  40351. */
  40352. _this._microSurface = 0.9;
  40353. /**
  40354. * source material index of refraction (IOR)' / 'destination material IOR.
  40355. */
  40356. _this._indexOfRefraction = 0.66;
  40357. /**
  40358. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40359. */
  40360. _this._invertRefractionY = false;
  40361. /**
  40362. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40363. * Materials half opaque for instance using refraction could benefit from this control.
  40364. */
  40365. _this._linkRefractionWithTransparency = false;
  40366. /**
  40367. * Specifies that the material will use the light map as a show map.
  40368. */
  40369. _this._useLightmapAsShadowmap = false;
  40370. /**
  40371. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40372. * makes the reflect vector face the model (under horizon).
  40373. */
  40374. _this._useHorizonOcclusion = true;
  40375. /**
  40376. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40377. * too much the area relying on ambient texture to define their ambient occlusion.
  40378. */
  40379. _this._useRadianceOcclusion = true;
  40380. /**
  40381. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40382. */
  40383. _this._useAlphaFromAlbedoTexture = false;
  40384. /**
  40385. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40386. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40387. */
  40388. _this._useSpecularOverAlpha = true;
  40389. /**
  40390. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40391. */
  40392. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40393. /**
  40394. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40395. */
  40396. _this._useRoughnessFromMetallicTextureAlpha = true;
  40397. /**
  40398. * Specifies if the metallic texture contains the roughness information in its green channel.
  40399. */
  40400. _this._useRoughnessFromMetallicTextureGreen = false;
  40401. /**
  40402. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40403. */
  40404. _this._useMetallnessFromMetallicTextureBlue = false;
  40405. /**
  40406. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40407. */
  40408. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40409. /**
  40410. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40411. */
  40412. _this._useAmbientInGrayScale = false;
  40413. /**
  40414. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40415. * The material will try to infer what glossiness each pixel should be.
  40416. */
  40417. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40418. /**
  40419. * BJS is using an harcoded light falloff based on a manually sets up range.
  40420. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40421. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40422. */
  40423. _this._usePhysicalLightFalloff = true;
  40424. /**
  40425. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40426. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40427. */
  40428. _this._useRadianceOverAlpha = true;
  40429. /**
  40430. * Allows using an object space normal map (instead of tangent space).
  40431. */
  40432. _this._useObjectSpaceNormalMap = false;
  40433. /**
  40434. * Allows using the bump map in parallax mode.
  40435. */
  40436. _this._useParallax = false;
  40437. /**
  40438. * Allows using the bump map in parallax occlusion mode.
  40439. */
  40440. _this._useParallaxOcclusion = false;
  40441. /**
  40442. * Controls the scale bias of the parallax mode.
  40443. */
  40444. _this._parallaxScaleBias = 0.05;
  40445. /**
  40446. * If sets to true, disables all the lights affecting the material.
  40447. */
  40448. _this._disableLighting = false;
  40449. /**
  40450. * Number of Simultaneous lights allowed on the material.
  40451. */
  40452. _this._maxSimultaneousLights = 4;
  40453. /**
  40454. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40455. */
  40456. _this._invertNormalMapX = false;
  40457. /**
  40458. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40459. */
  40460. _this._invertNormalMapY = false;
  40461. /**
  40462. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40463. */
  40464. _this._twoSidedLighting = false;
  40465. /**
  40466. * Defines the alpha limits in alpha test mode.
  40467. */
  40468. _this._alphaCutOff = 0.4;
  40469. /**
  40470. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40471. */
  40472. _this._forceAlphaTest = false;
  40473. /**
  40474. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40475. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40476. */
  40477. _this._useAlphaFresnel = false;
  40478. /**
  40479. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40480. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40481. */
  40482. _this._useLinearAlphaFresnel = false;
  40483. /**
  40484. * The transparency mode of the material.
  40485. */
  40486. _this._transparencyMode = null;
  40487. /**
  40488. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40489. * from cos thetav and roughness:
  40490. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40491. */
  40492. _this._environmentBRDFTexture = null;
  40493. /**
  40494. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40495. */
  40496. _this._forceIrradianceInFragment = false;
  40497. /**
  40498. * Force normal to face away from face.
  40499. */
  40500. _this._forceNormalForward = false;
  40501. /**
  40502. * Force metallic workflow.
  40503. */
  40504. _this._forceMetallicWorkflow = false;
  40505. /**
  40506. * Stores the available render targets.
  40507. */
  40508. _this._renderTargets = new BABYLON.SmartArray(16);
  40509. /**
  40510. * Sets the global ambient color for the material used in lighting calculations.
  40511. */
  40512. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40513. // Setup the default processing configuration to the scene.
  40514. _this._attachImageProcessingConfiguration(null);
  40515. _this.getRenderTargetTextures = function () {
  40516. _this._renderTargets.reset();
  40517. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40518. _this._renderTargets.push(_this._reflectionTexture);
  40519. }
  40520. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40521. _this._renderTargets.push(_this._refractionTexture);
  40522. }
  40523. return _this._renderTargets;
  40524. };
  40525. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40526. return _this;
  40527. }
  40528. /**
  40529. * Attaches a new image processing configuration to the PBR Material.
  40530. * @param configuration
  40531. */
  40532. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40533. var _this = this;
  40534. if (configuration === this._imageProcessingConfiguration) {
  40535. return;
  40536. }
  40537. // Detaches observer.
  40538. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40539. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40540. }
  40541. // Pick the scene configuration if needed.
  40542. if (!configuration) {
  40543. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40544. }
  40545. else {
  40546. this._imageProcessingConfiguration = configuration;
  40547. }
  40548. // Attaches observer.
  40549. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40550. _this._markAllSubMeshesAsImageProcessingDirty();
  40551. });
  40552. };
  40553. /**
  40554. * Gets the name of the material class.
  40555. */
  40556. PBRBaseMaterial.prototype.getClassName = function () {
  40557. return "PBRBaseMaterial";
  40558. };
  40559. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40560. /**
  40561. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40562. */
  40563. get: function () {
  40564. return this._useLogarithmicDepth;
  40565. },
  40566. /**
  40567. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40568. */
  40569. set: function (value) {
  40570. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40571. },
  40572. enumerable: true,
  40573. configurable: true
  40574. });
  40575. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40576. /**
  40577. * Gets the current transparency mode.
  40578. */
  40579. get: function () {
  40580. return this._transparencyMode;
  40581. },
  40582. /**
  40583. * Sets the transparency mode of the material.
  40584. */
  40585. set: function (value) {
  40586. if (this._transparencyMode === value) {
  40587. return;
  40588. }
  40589. this._transparencyMode = value;
  40590. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40591. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40597. /**
  40598. * Returns true if alpha blending should be disabled.
  40599. */
  40600. get: function () {
  40601. return (this._linkRefractionWithTransparency ||
  40602. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40603. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40604. },
  40605. enumerable: true,
  40606. configurable: true
  40607. });
  40608. /**
  40609. * Specifies whether or not this material should be rendered in alpha blend mode.
  40610. */
  40611. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40612. if (this._disableAlphaBlending) {
  40613. return false;
  40614. }
  40615. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40616. };
  40617. /**
  40618. * Specifies if the mesh will require alpha blending.
  40619. * @param mesh - BJS mesh.
  40620. */
  40621. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40622. if (this._disableAlphaBlending) {
  40623. return false;
  40624. }
  40625. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40626. };
  40627. /**
  40628. * Specifies whether or not this material should be rendered in alpha test mode.
  40629. */
  40630. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40631. if (this._forceAlphaTest) {
  40632. return true;
  40633. }
  40634. if (this._linkRefractionWithTransparency) {
  40635. return false;
  40636. }
  40637. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40638. };
  40639. /**
  40640. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40641. */
  40642. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40643. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40644. };
  40645. /**
  40646. * Gets the texture used for the alpha test.
  40647. */
  40648. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40649. return this._albedoTexture;
  40650. };
  40651. /**
  40652. * Specifies that the submesh is ready to be used.
  40653. * @param mesh - BJS mesh.
  40654. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40655. * @param useInstances - Specifies that instances should be used.
  40656. * @returns - boolean indicating that the submesh is ready or not.
  40657. */
  40658. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40659. if (subMesh.effect && this.isFrozen) {
  40660. if (this._wasPreviouslyReady) {
  40661. return true;
  40662. }
  40663. }
  40664. if (!subMesh._materialDefines) {
  40665. subMesh._materialDefines = new PBRMaterialDefines();
  40666. }
  40667. var defines = subMesh._materialDefines;
  40668. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40669. if (defines._renderId === this.getScene().getRenderId()) {
  40670. return true;
  40671. }
  40672. }
  40673. var scene = this.getScene();
  40674. var engine = scene.getEngine();
  40675. if (defines._areTexturesDirty) {
  40676. if (scene.texturesEnabled) {
  40677. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40678. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40679. return false;
  40680. }
  40681. }
  40682. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40683. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40684. return false;
  40685. }
  40686. }
  40687. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40688. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40689. return false;
  40690. }
  40691. }
  40692. var reflectionTexture = this._getReflectionTexture();
  40693. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40694. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40695. return false;
  40696. }
  40697. }
  40698. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40699. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40700. return false;
  40701. }
  40702. }
  40703. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40704. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40705. return false;
  40706. }
  40707. }
  40708. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40709. if (this._metallicTexture) {
  40710. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40711. return false;
  40712. }
  40713. }
  40714. else if (this._reflectivityTexture) {
  40715. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40716. return false;
  40717. }
  40718. }
  40719. if (this._microSurfaceTexture) {
  40720. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40721. return false;
  40722. }
  40723. }
  40724. }
  40725. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40726. // Bump texture cannot be not blocking.
  40727. if (!this._bumpTexture.isReady()) {
  40728. return false;
  40729. }
  40730. }
  40731. var refractionTexture = this._getRefractionTexture();
  40732. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40733. if (!refractionTexture.isReadyOrNotBlocking()) {
  40734. return false;
  40735. }
  40736. }
  40737. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40738. // This is blocking.
  40739. if (!this._environmentBRDFTexture.isReady()) {
  40740. return false;
  40741. }
  40742. }
  40743. }
  40744. }
  40745. if (defines._areImageProcessingDirty) {
  40746. if (!this._imageProcessingConfiguration.isReady()) {
  40747. return false;
  40748. }
  40749. }
  40750. if (!engine.getCaps().standardDerivatives) {
  40751. var bufferMesh = null;
  40752. if (mesh.getClassName() === "InstancedMesh") {
  40753. bufferMesh = mesh.sourceMesh;
  40754. }
  40755. else if (mesh.getClassName() === "Mesh") {
  40756. bufferMesh = mesh;
  40757. }
  40758. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40759. bufferMesh.createNormals(true);
  40760. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40761. }
  40762. }
  40763. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40764. if (effect) {
  40765. scene.resetCachedMaterial();
  40766. subMesh.setEffect(effect, defines);
  40767. this.buildUniformLayout();
  40768. }
  40769. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40770. return false;
  40771. }
  40772. defines._renderId = scene.getRenderId();
  40773. this._wasPreviouslyReady = true;
  40774. return true;
  40775. };
  40776. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40777. if (onCompiled === void 0) { onCompiled = null; }
  40778. if (onError === void 0) { onError = null; }
  40779. if (useInstances === void 0) { useInstances = null; }
  40780. if (useClipPlane === void 0) { useClipPlane = null; }
  40781. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40782. if (!defines.isDirty) {
  40783. return null;
  40784. }
  40785. defines.markAsProcessed();
  40786. var scene = this.getScene();
  40787. var engine = scene.getEngine();
  40788. // Fallbacks
  40789. var fallbacks = new BABYLON.EffectFallbacks();
  40790. var fallbackRank = 0;
  40791. if (defines.USESPHERICALINVERTEX) {
  40792. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40793. }
  40794. if (defines.FOG) {
  40795. fallbacks.addFallback(fallbackRank, "FOG");
  40796. }
  40797. if (defines.POINTSIZE) {
  40798. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40799. }
  40800. if (defines.LOGARITHMICDEPTH) {
  40801. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40802. }
  40803. if (defines.PARALLAX) {
  40804. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40805. }
  40806. if (defines.PARALLAXOCCLUSION) {
  40807. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40808. }
  40809. if (defines.ENVIRONMENTBRDF) {
  40810. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40811. }
  40812. if (defines.TANGENT) {
  40813. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40814. }
  40815. if (defines.BUMP) {
  40816. fallbacks.addFallback(fallbackRank++, "BUMP");
  40817. }
  40818. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40819. if (defines.SPECULARTERM) {
  40820. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40821. }
  40822. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40823. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40824. }
  40825. if (defines.LIGHTMAP) {
  40826. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40827. }
  40828. if (defines.NORMAL) {
  40829. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40830. }
  40831. if (defines.AMBIENT) {
  40832. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40833. }
  40834. if (defines.EMISSIVE) {
  40835. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40836. }
  40837. if (defines.VERTEXCOLOR) {
  40838. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40839. }
  40840. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40841. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40842. }
  40843. if (defines.MORPHTARGETS) {
  40844. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40845. }
  40846. //Attributes
  40847. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40848. if (defines.NORMAL) {
  40849. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40850. }
  40851. if (defines.TANGENT) {
  40852. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40853. }
  40854. if (defines.UV1) {
  40855. attribs.push(BABYLON.VertexBuffer.UVKind);
  40856. }
  40857. if (defines.UV2) {
  40858. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40859. }
  40860. if (defines.VERTEXCOLOR) {
  40861. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40862. }
  40863. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40864. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40865. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40866. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40867. "vFogInfos", "vFogColor", "pointSize",
  40868. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40869. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40870. "mBones",
  40871. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40872. "vLightingIntensity",
  40873. "logarithmicDepthConstant",
  40874. "vSphericalX", "vSphericalY", "vSphericalZ",
  40875. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40876. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40877. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40878. "vTangentSpaceParams"
  40879. ];
  40880. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40881. "bumpSampler", "lightmapSampler", "opacitySampler",
  40882. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40883. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40884. "microSurfaceSampler", "environmentBrdfSampler"];
  40885. var uniformBuffers = ["Material", "Scene"];
  40886. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40887. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40888. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40889. uniformsNames: uniforms,
  40890. uniformBuffersNames: uniformBuffers,
  40891. samplers: samplers,
  40892. defines: defines,
  40893. maxSimultaneousLights: this._maxSimultaneousLights
  40894. });
  40895. var join = defines.toString();
  40896. return engine.createEffect("pbr", {
  40897. attributes: attribs,
  40898. uniformsNames: uniforms,
  40899. uniformBuffersNames: uniformBuffers,
  40900. samplers: samplers,
  40901. defines: join,
  40902. fallbacks: fallbacks,
  40903. onCompiled: onCompiled,
  40904. onError: onError,
  40905. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40906. }, engine);
  40907. };
  40908. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40909. if (useInstances === void 0) { useInstances = null; }
  40910. if (useClipPlane === void 0) { useClipPlane = null; }
  40911. var scene = this.getScene();
  40912. var engine = scene.getEngine();
  40913. // Lights
  40914. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40915. defines._needNormals = true;
  40916. // Textures
  40917. if (defines._areTexturesDirty) {
  40918. defines._needUVs = false;
  40919. if (scene.texturesEnabled) {
  40920. if (scene.getEngine().getCaps().textureLOD) {
  40921. defines.LODBASEDMICROSFURACE = true;
  40922. }
  40923. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40924. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40925. }
  40926. else {
  40927. defines.ALBEDO = false;
  40928. }
  40929. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40930. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40931. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40932. }
  40933. else {
  40934. defines.AMBIENT = false;
  40935. }
  40936. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40937. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40938. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40939. }
  40940. else {
  40941. defines.OPACITY = false;
  40942. }
  40943. var reflectionTexture = this._getReflectionTexture();
  40944. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40945. defines.REFLECTION = true;
  40946. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40947. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40948. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40949. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40950. defines.INVERTCUBICMAP = true;
  40951. }
  40952. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40953. switch (reflectionTexture.coordinatesMode) {
  40954. case BABYLON.Texture.CUBIC_MODE:
  40955. case BABYLON.Texture.INVCUBIC_MODE:
  40956. defines.REFLECTIONMAP_CUBIC = true;
  40957. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40958. break;
  40959. case BABYLON.Texture.EXPLICIT_MODE:
  40960. defines.REFLECTIONMAP_EXPLICIT = true;
  40961. break;
  40962. case BABYLON.Texture.PLANAR_MODE:
  40963. defines.REFLECTIONMAP_PLANAR = true;
  40964. break;
  40965. case BABYLON.Texture.PROJECTION_MODE:
  40966. defines.REFLECTIONMAP_PROJECTION = true;
  40967. break;
  40968. case BABYLON.Texture.SKYBOX_MODE:
  40969. defines.REFLECTIONMAP_SKYBOX = true;
  40970. break;
  40971. case BABYLON.Texture.SPHERICAL_MODE:
  40972. defines.REFLECTIONMAP_SPHERICAL = true;
  40973. break;
  40974. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40975. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40976. break;
  40977. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40978. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40979. break;
  40980. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40981. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40982. break;
  40983. }
  40984. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40985. if (reflectionTexture.sphericalPolynomial) {
  40986. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40987. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40988. defines.USESPHERICALINVERTEX = false;
  40989. }
  40990. else {
  40991. defines.USESPHERICALINVERTEX = true;
  40992. }
  40993. }
  40994. }
  40995. }
  40996. else {
  40997. defines.REFLECTION = false;
  40998. defines.REFLECTIONMAP_3D = false;
  40999. defines.REFLECTIONMAP_SPHERICAL = false;
  41000. defines.REFLECTIONMAP_PLANAR = false;
  41001. defines.REFLECTIONMAP_CUBIC = false;
  41002. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41003. defines.REFLECTIONMAP_PROJECTION = false;
  41004. defines.REFLECTIONMAP_SKYBOX = false;
  41005. defines.REFLECTIONMAP_EXPLICIT = false;
  41006. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41007. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41008. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41009. defines.INVERTCUBICMAP = false;
  41010. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41011. defines.USESPHERICALINVERTEX = false;
  41012. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41013. defines.LODINREFLECTIONALPHA = false;
  41014. defines.GAMMAREFLECTION = false;
  41015. }
  41016. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41017. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41018. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41019. }
  41020. else {
  41021. defines.LIGHTMAP = false;
  41022. }
  41023. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41024. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41025. }
  41026. else {
  41027. defines.EMISSIVE = false;
  41028. }
  41029. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41030. if (this._metallicTexture) {
  41031. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41032. defines.METALLICWORKFLOW = true;
  41033. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41034. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41035. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41036. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41037. }
  41038. else if (this._reflectivityTexture) {
  41039. defines.METALLICWORKFLOW = false;
  41040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41041. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41042. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41043. }
  41044. else {
  41045. defines.METALLICWORKFLOW = false;
  41046. defines.REFLECTIVITY = false;
  41047. }
  41048. if (this._microSurfaceTexture) {
  41049. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41050. }
  41051. else {
  41052. defines.MICROSURFACEMAP = false;
  41053. }
  41054. }
  41055. else {
  41056. defines.REFLECTIVITY = false;
  41057. defines.MICROSURFACEMAP = false;
  41058. }
  41059. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41060. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41061. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41062. defines.PARALLAX = true;
  41063. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41064. }
  41065. else {
  41066. defines.PARALLAX = false;
  41067. }
  41068. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41069. }
  41070. else {
  41071. defines.BUMP = false;
  41072. }
  41073. var refractionTexture = this._getRefractionTexture();
  41074. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41075. defines.REFRACTION = true;
  41076. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41077. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41078. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41079. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41080. if (this._linkRefractionWithTransparency) {
  41081. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41082. }
  41083. }
  41084. else {
  41085. defines.REFRACTION = false;
  41086. }
  41087. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41088. defines.ENVIRONMENTBRDF = true;
  41089. }
  41090. else {
  41091. defines.ENVIRONMENTBRDF = false;
  41092. }
  41093. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41094. defines.ALPHAFROMALBEDO = true;
  41095. }
  41096. else {
  41097. defines.ALPHAFROMALBEDO = false;
  41098. }
  41099. }
  41100. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41101. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41102. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41103. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  41104. defines.METALLICWORKFLOW = true;
  41105. }
  41106. else {
  41107. defines.METALLICWORKFLOW = false;
  41108. }
  41109. if (!this.backFaceCulling && this._twoSidedLighting) {
  41110. defines.TWOSIDEDLIGHTING = true;
  41111. }
  41112. else {
  41113. defines.TWOSIDEDLIGHTING = false;
  41114. }
  41115. defines.ALPHATESTVALUE = this._alphaCutOff;
  41116. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41117. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41118. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41119. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41120. }
  41121. if (defines._areImageProcessingDirty) {
  41122. this._imageProcessingConfiguration.prepareDefines(defines);
  41123. }
  41124. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41125. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41126. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41127. // Misc.
  41128. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41129. // Values that need to be evaluated on every frame
  41130. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41131. // Attribs
  41132. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41133. };
  41134. /**
  41135. * Force shader compilation
  41136. */
  41137. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41138. var _this = this;
  41139. var localOptions = __assign({ clipPlane: false }, options);
  41140. var defines = new PBRMaterialDefines();
  41141. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41142. if (effect.isReady()) {
  41143. if (onCompiled) {
  41144. onCompiled(this);
  41145. }
  41146. }
  41147. else {
  41148. effect.onCompileObservable.add(function () {
  41149. if (onCompiled) {
  41150. onCompiled(_this);
  41151. }
  41152. });
  41153. }
  41154. };
  41155. /**
  41156. * Initializes the uniform buffer layout for the shader.
  41157. */
  41158. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41159. // Order is important !
  41160. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41161. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41162. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41163. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41164. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41165. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41166. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41167. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41168. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41169. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41170. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41171. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41172. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41173. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41174. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41175. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41176. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41177. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41178. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41179. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41180. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41181. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41182. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41183. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41184. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41185. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41186. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41187. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41188. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41189. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41190. this._uniformBuffer.addUniform("pointSize", 1);
  41191. this._uniformBuffer.create();
  41192. };
  41193. /**
  41194. * Unbinds the textures.
  41195. */
  41196. PBRBaseMaterial.prototype.unbind = function () {
  41197. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41198. this._uniformBuffer.setTexture("reflectionSampler", null);
  41199. }
  41200. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41201. this._uniformBuffer.setTexture("refractionSampler", null);
  41202. }
  41203. _super.prototype.unbind.call(this);
  41204. };
  41205. /**
  41206. * Binds the submesh data.
  41207. * @param world - The world matrix.
  41208. * @param mesh - The BJS mesh.
  41209. * @param subMesh - A submesh of the BJS mesh.
  41210. */
  41211. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41212. var scene = this.getScene();
  41213. var defines = subMesh._materialDefines;
  41214. if (!defines) {
  41215. return;
  41216. }
  41217. var effect = subMesh.effect;
  41218. if (!effect) {
  41219. return;
  41220. }
  41221. this._activeEffect = effect;
  41222. // Matrices
  41223. this.bindOnlyWorldMatrix(world);
  41224. // Normal Matrix
  41225. if (defines.OBJECTSPACE_NORMALMAP) {
  41226. world.toNormalMatrix(this._normalMatrix);
  41227. this.bindOnlyNormalMatrix(this._normalMatrix);
  41228. }
  41229. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41230. // Bones
  41231. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41232. var reflectionTexture = null;
  41233. if (mustRebind) {
  41234. this._uniformBuffer.bindToEffect(effect, "Material");
  41235. this.bindViewProjection(effect);
  41236. reflectionTexture = this._getReflectionTexture();
  41237. var refractionTexture = this._getRefractionTexture();
  41238. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41239. // Texture uniforms
  41240. if (scene.texturesEnabled) {
  41241. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41242. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41243. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41244. }
  41245. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41246. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41247. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41248. }
  41249. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41250. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41251. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41252. }
  41253. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41254. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41255. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41256. if (reflectionTexture.boundingBoxSize) {
  41257. var cubeTexture = reflectionTexture;
  41258. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41259. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41260. }
  41261. var polynomials = reflectionTexture.sphericalPolynomial;
  41262. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41263. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41264. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41265. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41266. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41267. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41268. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41269. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41270. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41271. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41272. }
  41273. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41274. }
  41275. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41276. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41277. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41278. }
  41279. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41280. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41281. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41282. }
  41283. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41284. if (this._metallicTexture) {
  41285. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41286. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41287. }
  41288. else if (this._reflectivityTexture) {
  41289. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41290. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41291. }
  41292. if (this._microSurfaceTexture) {
  41293. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41294. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41295. }
  41296. }
  41297. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41298. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41299. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41300. if (scene._mirroredCameraPosition) {
  41301. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41302. }
  41303. else {
  41304. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41305. }
  41306. }
  41307. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41308. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41309. var depth = 1.0;
  41310. if (!refractionTexture.isCube) {
  41311. if (refractionTexture.depth) {
  41312. depth = refractionTexture.depth;
  41313. }
  41314. }
  41315. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41316. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41317. }
  41318. }
  41319. // Point size
  41320. if (this.pointsCloud) {
  41321. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41322. }
  41323. // Colors
  41324. if (defines.METALLICWORKFLOW) {
  41325. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41326. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41327. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41328. }
  41329. else {
  41330. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41331. }
  41332. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41333. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41334. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41335. // Misc
  41336. this._lightingInfos.x = this._directIntensity;
  41337. this._lightingInfos.y = this._emissiveIntensity;
  41338. this._lightingInfos.z = this._environmentIntensity;
  41339. this._lightingInfos.w = this._specularIntensity;
  41340. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41341. }
  41342. // Textures
  41343. if (scene.texturesEnabled) {
  41344. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41345. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41346. }
  41347. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41348. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41349. }
  41350. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41351. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41352. }
  41353. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41354. if (defines.LODBASEDMICROSFURACE) {
  41355. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41356. }
  41357. else {
  41358. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41359. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41360. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41361. }
  41362. }
  41363. if (defines.ENVIRONMENTBRDF) {
  41364. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41365. }
  41366. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41367. if (defines.LODBASEDMICROSFURACE) {
  41368. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41369. }
  41370. else {
  41371. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41372. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41373. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41374. }
  41375. }
  41376. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41377. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41378. }
  41379. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41380. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41381. }
  41382. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41383. if (this._metallicTexture) {
  41384. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41385. }
  41386. else if (this._reflectivityTexture) {
  41387. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41388. }
  41389. if (this._microSurfaceTexture) {
  41390. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41391. }
  41392. }
  41393. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41394. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41395. }
  41396. }
  41397. // Clip plane
  41398. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41399. // Colors
  41400. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41401. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41402. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41403. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41404. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41405. }
  41406. if (mustRebind || !this.isFrozen) {
  41407. // Lights
  41408. if (scene.lightsEnabled && !this._disableLighting) {
  41409. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41410. }
  41411. // View
  41412. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41413. this.bindView(effect);
  41414. }
  41415. // Fog
  41416. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41417. // Morph targets
  41418. if (defines.NUM_MORPH_INFLUENCERS) {
  41419. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41420. }
  41421. // image processing
  41422. this._imageProcessingConfiguration.bind(this._activeEffect);
  41423. // Log. depth
  41424. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41425. }
  41426. this._uniformBuffer.update();
  41427. this._afterBind(mesh);
  41428. };
  41429. /**
  41430. * Returns the animatable textures.
  41431. * @returns - Array of animatable textures.
  41432. */
  41433. PBRBaseMaterial.prototype.getAnimatables = function () {
  41434. var results = [];
  41435. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41436. results.push(this._albedoTexture);
  41437. }
  41438. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41439. results.push(this._ambientTexture);
  41440. }
  41441. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41442. results.push(this._opacityTexture);
  41443. }
  41444. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41445. results.push(this._reflectionTexture);
  41446. }
  41447. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41448. results.push(this._emissiveTexture);
  41449. }
  41450. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41451. results.push(this._metallicTexture);
  41452. }
  41453. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41454. results.push(this._reflectivityTexture);
  41455. }
  41456. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41457. results.push(this._bumpTexture);
  41458. }
  41459. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41460. results.push(this._lightmapTexture);
  41461. }
  41462. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41463. results.push(this._refractionTexture);
  41464. }
  41465. return results;
  41466. };
  41467. /**
  41468. * Returns the texture used for reflections.
  41469. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41470. */
  41471. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41472. if (this._reflectionTexture) {
  41473. return this._reflectionTexture;
  41474. }
  41475. return this.getScene().environmentTexture;
  41476. };
  41477. /**
  41478. * Returns the texture used for refraction or null if none is used.
  41479. * @returns - Refection texture if present. If no refraction texture and refraction
  41480. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41481. */
  41482. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41483. if (this._refractionTexture) {
  41484. return this._refractionTexture;
  41485. }
  41486. if (this._linkRefractionWithTransparency) {
  41487. return this.getScene().environmentTexture;
  41488. }
  41489. return null;
  41490. };
  41491. /**
  41492. * Disposes the resources of the material.
  41493. * @param forceDisposeEffect - Forces the disposal of effects.
  41494. * @param forceDisposeTextures - Forces the disposal of all textures.
  41495. */
  41496. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41497. if (forceDisposeTextures) {
  41498. if (this._albedoTexture) {
  41499. this._albedoTexture.dispose();
  41500. }
  41501. if (this._ambientTexture) {
  41502. this._ambientTexture.dispose();
  41503. }
  41504. if (this._opacityTexture) {
  41505. this._opacityTexture.dispose();
  41506. }
  41507. if (this._reflectionTexture) {
  41508. this._reflectionTexture.dispose();
  41509. }
  41510. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41511. this._environmentBRDFTexture.dispose();
  41512. }
  41513. if (this._emissiveTexture) {
  41514. this._emissiveTexture.dispose();
  41515. }
  41516. if (this._metallicTexture) {
  41517. this._metallicTexture.dispose();
  41518. }
  41519. if (this._reflectivityTexture) {
  41520. this._reflectivityTexture.dispose();
  41521. }
  41522. if (this._bumpTexture) {
  41523. this._bumpTexture.dispose();
  41524. }
  41525. if (this._lightmapTexture) {
  41526. this._lightmapTexture.dispose();
  41527. }
  41528. if (this._refractionTexture) {
  41529. this._refractionTexture.dispose();
  41530. }
  41531. }
  41532. this._renderTargets.dispose();
  41533. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41534. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41535. }
  41536. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41537. };
  41538. /**
  41539. * Stores the reflectivity values based on metallic roughness workflow.
  41540. */
  41541. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41542. __decorate([
  41543. BABYLON.serializeAsImageProcessingConfiguration()
  41544. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41545. __decorate([
  41546. BABYLON.serialize()
  41547. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41548. __decorate([
  41549. BABYLON.serialize()
  41550. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41551. return PBRBaseMaterial;
  41552. }(BABYLON.PushMaterial));
  41553. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41554. })(BABYLON || (BABYLON = {}));
  41555. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41556. var BABYLON;
  41557. (function (BABYLON) {
  41558. /**
  41559. * The Physically based simple base material of BJS.
  41560. *
  41561. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41562. * It is used as the base class for both the specGloss and metalRough conventions.
  41563. */
  41564. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41565. __extends(PBRBaseSimpleMaterial, _super);
  41566. /**
  41567. * Instantiates a new PBRMaterial instance.
  41568. *
  41569. * @param name The material name
  41570. * @param scene The scene the material will be use in.
  41571. */
  41572. function PBRBaseSimpleMaterial(name, scene) {
  41573. var _this = _super.call(this, name, scene) || this;
  41574. /**
  41575. * Number of Simultaneous lights allowed on the material.
  41576. */
  41577. _this.maxSimultaneousLights = 4;
  41578. /**
  41579. * If sets to true, disables all the lights affecting the material.
  41580. */
  41581. _this.disableLighting = false;
  41582. /**
  41583. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41584. */
  41585. _this.invertNormalMapX = false;
  41586. /**
  41587. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41588. */
  41589. _this.invertNormalMapY = false;
  41590. /**
  41591. * Emissivie color used to self-illuminate the model.
  41592. */
  41593. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41594. /**
  41595. * Occlusion Channel Strenght.
  41596. */
  41597. _this.occlusionStrength = 1.0;
  41598. _this.useLightmapAsShadowmap = false;
  41599. _this._useAlphaFromAlbedoTexture = true;
  41600. _this._useAmbientInGrayScale = true;
  41601. return _this;
  41602. }
  41603. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41604. /**
  41605. * Gets the current double sided mode.
  41606. */
  41607. get: function () {
  41608. return this._twoSidedLighting;
  41609. },
  41610. /**
  41611. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41612. */
  41613. set: function (value) {
  41614. if (this._twoSidedLighting === value) {
  41615. return;
  41616. }
  41617. this._twoSidedLighting = value;
  41618. this.backFaceCulling = !value;
  41619. this._markAllSubMeshesAsTexturesDirty();
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. /**
  41625. * Return the active textures of the material.
  41626. */
  41627. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41628. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41629. if (this.environmentTexture) {
  41630. activeTextures.push(this.environmentTexture);
  41631. }
  41632. if (this.normalTexture) {
  41633. activeTextures.push(this.normalTexture);
  41634. }
  41635. if (this.emissiveTexture) {
  41636. activeTextures.push(this.emissiveTexture);
  41637. }
  41638. if (this.occlusionTexture) {
  41639. activeTextures.push(this.occlusionTexture);
  41640. }
  41641. if (this.lightmapTexture) {
  41642. activeTextures.push(this.lightmapTexture);
  41643. }
  41644. return activeTextures;
  41645. };
  41646. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41647. if (_super.prototype.hasTexture.call(this, texture)) {
  41648. return true;
  41649. }
  41650. if (this.lightmapTexture === texture) {
  41651. return true;
  41652. }
  41653. return false;
  41654. };
  41655. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41656. return "PBRBaseSimpleMaterial";
  41657. };
  41658. __decorate([
  41659. BABYLON.serialize(),
  41660. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41661. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41662. __decorate([
  41663. BABYLON.serialize(),
  41664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41665. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41666. __decorate([
  41667. BABYLON.serializeAsTexture(),
  41668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41669. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41670. __decorate([
  41671. BABYLON.serialize(),
  41672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41673. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41674. __decorate([
  41675. BABYLON.serialize(),
  41676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41677. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41678. __decorate([
  41679. BABYLON.serializeAsTexture(),
  41680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41681. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41682. __decorate([
  41683. BABYLON.serializeAsColor3("emissive"),
  41684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41685. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41686. __decorate([
  41687. BABYLON.serializeAsTexture(),
  41688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41689. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41690. __decorate([
  41691. BABYLON.serialize(),
  41692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41693. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41694. __decorate([
  41695. BABYLON.serializeAsTexture(),
  41696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41697. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41698. __decorate([
  41699. BABYLON.serialize(),
  41700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41701. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41702. __decorate([
  41703. BABYLON.serialize()
  41704. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41705. __decorate([
  41706. BABYLON.serializeAsTexture(),
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41708. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41712. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41713. return PBRBaseSimpleMaterial;
  41714. }(BABYLON.PBRBaseMaterial));
  41715. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41716. })(BABYLON || (BABYLON = {}));
  41717. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41718. var BABYLON;
  41719. (function (BABYLON) {
  41720. /**
  41721. * The Physically based material of BJS.
  41722. *
  41723. * This offers the main features of a standard PBR material.
  41724. * For more information, please refer to the documentation :
  41725. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41726. */
  41727. var PBRMaterial = /** @class */ (function (_super) {
  41728. __extends(PBRMaterial, _super);
  41729. /**
  41730. * Instantiates a new PBRMaterial instance.
  41731. *
  41732. * @param name The material name
  41733. * @param scene The scene the material will be use in.
  41734. */
  41735. function PBRMaterial(name, scene) {
  41736. var _this = _super.call(this, name, scene) || this;
  41737. /**
  41738. * Intensity of the direct lights e.g. the four lights available in your scene.
  41739. * This impacts both the direct diffuse and specular highlights.
  41740. */
  41741. _this.directIntensity = 1.0;
  41742. /**
  41743. * Intensity of the emissive part of the material.
  41744. * This helps controlling the emissive effect without modifying the emissive color.
  41745. */
  41746. _this.emissiveIntensity = 1.0;
  41747. /**
  41748. * Intensity of the environment e.g. how much the environment will light the object
  41749. * either through harmonics for rough material or through the refelction for shiny ones.
  41750. */
  41751. _this.environmentIntensity = 1.0;
  41752. /**
  41753. * This is a special control allowing the reduction of the specular highlights coming from the
  41754. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41755. */
  41756. _this.specularIntensity = 1.0;
  41757. /**
  41758. * Debug Control allowing disabling the bump map on this material.
  41759. */
  41760. _this.disableBumpMap = false;
  41761. /**
  41762. * AKA Occlusion Texture Intensity in other nomenclature.
  41763. */
  41764. _this.ambientTextureStrength = 1.0;
  41765. /**
  41766. * The color of a material in ambient lighting.
  41767. */
  41768. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41769. /**
  41770. * AKA Diffuse Color in other nomenclature.
  41771. */
  41772. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41773. /**
  41774. * AKA Specular Color in other nomenclature.
  41775. */
  41776. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41777. /**
  41778. * The color reflected from the material.
  41779. */
  41780. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41781. /**
  41782. * The color emitted from the material.
  41783. */
  41784. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41785. /**
  41786. * AKA Glossiness in other nomenclature.
  41787. */
  41788. _this.microSurface = 1.0;
  41789. /**
  41790. * source material index of refraction (IOR)' / 'destination material IOR.
  41791. */
  41792. _this.indexOfRefraction = 0.66;
  41793. /**
  41794. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41795. */
  41796. _this.invertRefractionY = false;
  41797. /**
  41798. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41799. * Materials half opaque for instance using refraction could benefit from this control.
  41800. */
  41801. _this.linkRefractionWithTransparency = false;
  41802. _this.useLightmapAsShadowmap = false;
  41803. /**
  41804. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41805. */
  41806. _this.useAlphaFromAlbedoTexture = false;
  41807. /**
  41808. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41809. */
  41810. _this.forceAlphaTest = false;
  41811. /**
  41812. * Defines the alpha limits in alpha test mode.
  41813. */
  41814. _this.alphaCutOff = 0.4;
  41815. /**
  41816. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41817. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41818. */
  41819. _this.useSpecularOverAlpha = true;
  41820. /**
  41821. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41822. */
  41823. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41824. /**
  41825. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41826. */
  41827. _this.useRoughnessFromMetallicTextureAlpha = true;
  41828. /**
  41829. * Specifies if the metallic texture contains the roughness information in its green channel.
  41830. */
  41831. _this.useRoughnessFromMetallicTextureGreen = false;
  41832. /**
  41833. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41834. */
  41835. _this.useMetallnessFromMetallicTextureBlue = false;
  41836. /**
  41837. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41838. */
  41839. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41840. /**
  41841. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41842. */
  41843. _this.useAmbientInGrayScale = false;
  41844. /**
  41845. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41846. * The material will try to infer what glossiness each pixel should be.
  41847. */
  41848. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41849. /**
  41850. * BJS is using an harcoded light falloff based on a manually sets up range.
  41851. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41852. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41853. */
  41854. _this.usePhysicalLightFalloff = true;
  41855. /**
  41856. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41857. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41858. */
  41859. _this.useRadianceOverAlpha = true;
  41860. /**
  41861. * Allows using an object space normal map (instead of tangent space).
  41862. */
  41863. _this.useObjectSpaceNormalMap = false;
  41864. /**
  41865. * Allows using the bump map in parallax mode.
  41866. */
  41867. _this.useParallax = false;
  41868. /**
  41869. * Allows using the bump map in parallax occlusion mode.
  41870. */
  41871. _this.useParallaxOcclusion = false;
  41872. /**
  41873. * Controls the scale bias of the parallax mode.
  41874. */
  41875. _this.parallaxScaleBias = 0.05;
  41876. /**
  41877. * If sets to true, disables all the lights affecting the material.
  41878. */
  41879. _this.disableLighting = false;
  41880. /**
  41881. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41882. */
  41883. _this.forceIrradianceInFragment = false;
  41884. /**
  41885. * Number of Simultaneous lights allowed on the material.
  41886. */
  41887. _this.maxSimultaneousLights = 4;
  41888. /**
  41889. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41890. */
  41891. _this.invertNormalMapX = false;
  41892. /**
  41893. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41894. */
  41895. _this.invertNormalMapY = false;
  41896. /**
  41897. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41898. */
  41899. _this.twoSidedLighting = false;
  41900. /**
  41901. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41902. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41903. */
  41904. _this.useAlphaFresnel = false;
  41905. /**
  41906. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41907. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41908. */
  41909. _this.useLinearAlphaFresnel = false;
  41910. /**
  41911. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41912. * And/Or occlude the blended part.
  41913. */
  41914. _this.environmentBRDFTexture = null;
  41915. /**
  41916. * Force normal to face away from face.
  41917. */
  41918. _this.forceNormalForward = false;
  41919. /**
  41920. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41921. * makes the reflect vector face the model (under horizon).
  41922. */
  41923. _this.useHorizonOcclusion = true;
  41924. /**
  41925. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41926. * too much the area relying on ambient texture to define their ambient occlusion.
  41927. */
  41928. _this.useRadianceOcclusion = true;
  41929. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41930. return _this;
  41931. }
  41932. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41933. /**
  41934. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41935. */
  41936. get: function () {
  41937. return this._PBRMATERIAL_OPAQUE;
  41938. },
  41939. enumerable: true,
  41940. configurable: true
  41941. });
  41942. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41943. /**
  41944. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41945. */
  41946. get: function () {
  41947. return this._PBRMATERIAL_ALPHATEST;
  41948. },
  41949. enumerable: true,
  41950. configurable: true
  41951. });
  41952. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41953. /**
  41954. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41955. */
  41956. get: function () {
  41957. return this._PBRMATERIAL_ALPHABLEND;
  41958. },
  41959. enumerable: true,
  41960. configurable: true
  41961. });
  41962. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41963. /**
  41964. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41965. * They are also discarded below the alpha cutoff threshold to improve performances.
  41966. */
  41967. get: function () {
  41968. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41969. },
  41970. enumerable: true,
  41971. configurable: true
  41972. });
  41973. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41974. /**
  41975. * Gets the image processing configuration used either in this material.
  41976. */
  41977. get: function () {
  41978. return this._imageProcessingConfiguration;
  41979. },
  41980. /**
  41981. * Sets the Default image processing configuration used either in the this material.
  41982. *
  41983. * If sets to null, the scene one is in use.
  41984. */
  41985. set: function (value) {
  41986. this._attachImageProcessingConfiguration(value);
  41987. // Ensure the effect will be rebuilt.
  41988. this._markAllSubMeshesAsTexturesDirty();
  41989. },
  41990. enumerable: true,
  41991. configurable: true
  41992. });
  41993. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41994. /**
  41995. * Gets wether the color curves effect is enabled.
  41996. */
  41997. get: function () {
  41998. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41999. },
  42000. /**
  42001. * Sets wether the color curves effect is enabled.
  42002. */
  42003. set: function (value) {
  42004. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42005. },
  42006. enumerable: true,
  42007. configurable: true
  42008. });
  42009. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42010. /**
  42011. * Gets wether the color grading effect is enabled.
  42012. */
  42013. get: function () {
  42014. return this.imageProcessingConfiguration.colorGradingEnabled;
  42015. },
  42016. /**
  42017. * Gets wether the color grading effect is enabled.
  42018. */
  42019. set: function (value) {
  42020. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42021. },
  42022. enumerable: true,
  42023. configurable: true
  42024. });
  42025. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42026. /**
  42027. * Gets wether tonemapping is enabled or not.
  42028. */
  42029. get: function () {
  42030. return this._imageProcessingConfiguration.toneMappingEnabled;
  42031. },
  42032. /**
  42033. * Sets wether tonemapping is enabled or not
  42034. */
  42035. set: function (value) {
  42036. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. ;
  42042. ;
  42043. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42044. /**
  42045. * The camera exposure used on this material.
  42046. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42047. * This corresponds to a photographic exposure.
  42048. */
  42049. get: function () {
  42050. return this._imageProcessingConfiguration.exposure;
  42051. },
  42052. /**
  42053. * The camera exposure used on this material.
  42054. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42055. * This corresponds to a photographic exposure.
  42056. */
  42057. set: function (value) {
  42058. this._imageProcessingConfiguration.exposure = value;
  42059. },
  42060. enumerable: true,
  42061. configurable: true
  42062. });
  42063. ;
  42064. ;
  42065. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42066. /**
  42067. * Gets The camera contrast used on this material.
  42068. */
  42069. get: function () {
  42070. return this._imageProcessingConfiguration.contrast;
  42071. },
  42072. /**
  42073. * Sets The camera contrast used on this material.
  42074. */
  42075. set: function (value) {
  42076. this._imageProcessingConfiguration.contrast = value;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42082. /**
  42083. * Gets the Color Grading 2D Lookup Texture.
  42084. */
  42085. get: function () {
  42086. return this._imageProcessingConfiguration.colorGradingTexture;
  42087. },
  42088. /**
  42089. * Sets the Color Grading 2D Lookup Texture.
  42090. */
  42091. set: function (value) {
  42092. this._imageProcessingConfiguration.colorGradingTexture = value;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42098. /**
  42099. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42100. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42101. * 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;
  42102. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42103. */
  42104. get: function () {
  42105. return this._imageProcessingConfiguration.colorCurves;
  42106. },
  42107. /**
  42108. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42109. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42110. * 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;
  42111. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42112. */
  42113. set: function (value) {
  42114. this._imageProcessingConfiguration.colorCurves = value;
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. /**
  42120. * Returns the name of this material class.
  42121. */
  42122. PBRMaterial.prototype.getClassName = function () {
  42123. return "PBRMaterial";
  42124. };
  42125. /**
  42126. * Returns an array of the actively used textures.
  42127. * @returns - Array of BaseTextures
  42128. */
  42129. PBRMaterial.prototype.getActiveTextures = function () {
  42130. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42131. if (this._albedoTexture) {
  42132. activeTextures.push(this._albedoTexture);
  42133. }
  42134. if (this._ambientTexture) {
  42135. activeTextures.push(this._ambientTexture);
  42136. }
  42137. if (this._opacityTexture) {
  42138. activeTextures.push(this._opacityTexture);
  42139. }
  42140. if (this._reflectionTexture) {
  42141. activeTextures.push(this._reflectionTexture);
  42142. }
  42143. if (this._emissiveTexture) {
  42144. activeTextures.push(this._emissiveTexture);
  42145. }
  42146. if (this._reflectivityTexture) {
  42147. activeTextures.push(this._reflectivityTexture);
  42148. }
  42149. if (this._metallicTexture) {
  42150. activeTextures.push(this._metallicTexture);
  42151. }
  42152. if (this._microSurfaceTexture) {
  42153. activeTextures.push(this._microSurfaceTexture);
  42154. }
  42155. if (this._bumpTexture) {
  42156. activeTextures.push(this._bumpTexture);
  42157. }
  42158. if (this._lightmapTexture) {
  42159. activeTextures.push(this._lightmapTexture);
  42160. }
  42161. if (this._refractionTexture) {
  42162. activeTextures.push(this._refractionTexture);
  42163. }
  42164. return activeTextures;
  42165. };
  42166. /**
  42167. * Checks to see if a texture is used in the material.
  42168. * @param texture - Base texture to use.
  42169. * @returns - Boolean specifying if a texture is used in the material.
  42170. */
  42171. PBRMaterial.prototype.hasTexture = function (texture) {
  42172. if (_super.prototype.hasTexture.call(this, texture)) {
  42173. return true;
  42174. }
  42175. if (this._albedoTexture === texture) {
  42176. return true;
  42177. }
  42178. if (this._ambientTexture === texture) {
  42179. return true;
  42180. }
  42181. if (this._opacityTexture === texture) {
  42182. return true;
  42183. }
  42184. if (this._reflectionTexture === texture) {
  42185. return true;
  42186. }
  42187. if (this._reflectivityTexture === texture) {
  42188. return true;
  42189. }
  42190. if (this._metallicTexture === texture) {
  42191. return true;
  42192. }
  42193. if (this._microSurfaceTexture === texture) {
  42194. return true;
  42195. }
  42196. if (this._bumpTexture === texture) {
  42197. return true;
  42198. }
  42199. if (this._lightmapTexture === texture) {
  42200. return true;
  42201. }
  42202. if (this._refractionTexture === texture) {
  42203. return true;
  42204. }
  42205. return false;
  42206. };
  42207. /**
  42208. * Makes a duplicate of the current material.
  42209. * @param name - name to use for the new material.
  42210. */
  42211. PBRMaterial.prototype.clone = function (name) {
  42212. var _this = this;
  42213. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42214. clone.id = name;
  42215. clone.name = name;
  42216. return clone;
  42217. };
  42218. /**
  42219. * Serializes this PBR Material.
  42220. * @returns - An object with the serialized material.
  42221. */
  42222. PBRMaterial.prototype.serialize = function () {
  42223. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42224. serializationObject.customType = "BABYLON.PBRMaterial";
  42225. return serializationObject;
  42226. };
  42227. // Statics
  42228. /**
  42229. * Parses a PBR Material from a serialized object.
  42230. * @param source - Serialized object.
  42231. * @param scene - BJS scene instance.
  42232. * @param rootUrl - url for the scene object
  42233. * @returns - PBRMaterial
  42234. */
  42235. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42236. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42237. };
  42238. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42239. /**
  42240. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42241. */
  42242. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42243. /**
  42244. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42245. */
  42246. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42247. /**
  42248. * 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.
  42249. * They are also discarded below the alpha cutoff threshold to improve performances.
  42250. */
  42251. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42252. __decorate([
  42253. BABYLON.serialize(),
  42254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42255. ], PBRMaterial.prototype, "directIntensity", void 0);
  42256. __decorate([
  42257. BABYLON.serialize(),
  42258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42259. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42260. __decorate([
  42261. BABYLON.serialize(),
  42262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42263. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42264. __decorate([
  42265. BABYLON.serialize(),
  42266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42267. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42268. __decorate([
  42269. BABYLON.serialize(),
  42270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42271. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42272. __decorate([
  42273. BABYLON.serializeAsTexture(),
  42274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42275. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42276. __decorate([
  42277. BABYLON.serializeAsTexture(),
  42278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42279. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42280. __decorate([
  42281. BABYLON.serialize(),
  42282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42283. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42284. __decorate([
  42285. BABYLON.serializeAsTexture(),
  42286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42287. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42288. __decorate([
  42289. BABYLON.serializeAsTexture(),
  42290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42291. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42292. __decorate([
  42293. BABYLON.serializeAsTexture(),
  42294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42295. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42296. __decorate([
  42297. BABYLON.serializeAsTexture(),
  42298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42299. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42300. __decorate([
  42301. BABYLON.serializeAsTexture(),
  42302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42303. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42304. __decorate([
  42305. BABYLON.serialize(),
  42306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42307. ], PBRMaterial.prototype, "metallic", void 0);
  42308. __decorate([
  42309. BABYLON.serialize(),
  42310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42311. ], PBRMaterial.prototype, "roughness", void 0);
  42312. __decorate([
  42313. BABYLON.serializeAsTexture(),
  42314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42315. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42316. __decorate([
  42317. BABYLON.serializeAsTexture(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42319. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42320. __decorate([
  42321. BABYLON.serializeAsTexture(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42323. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42324. __decorate([
  42325. BABYLON.serializeAsTexture(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42327. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42328. __decorate([
  42329. BABYLON.serializeAsColor3("ambient"),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42331. ], PBRMaterial.prototype, "ambientColor", void 0);
  42332. __decorate([
  42333. BABYLON.serializeAsColor3("albedo"),
  42334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42335. ], PBRMaterial.prototype, "albedoColor", void 0);
  42336. __decorate([
  42337. BABYLON.serializeAsColor3("reflectivity"),
  42338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42339. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42340. __decorate([
  42341. BABYLON.serializeAsColor3("reflection"),
  42342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42343. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42344. __decorate([
  42345. BABYLON.serializeAsColor3("emissive"),
  42346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42347. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42348. __decorate([
  42349. BABYLON.serialize(),
  42350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42351. ], PBRMaterial.prototype, "microSurface", void 0);
  42352. __decorate([
  42353. BABYLON.serialize(),
  42354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42355. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42356. __decorate([
  42357. BABYLON.serialize(),
  42358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42359. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42360. __decorate([
  42361. BABYLON.serialize(),
  42362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42363. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42364. __decorate([
  42365. BABYLON.serialize(),
  42366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42367. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42368. __decorate([
  42369. BABYLON.serialize(),
  42370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42371. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42372. __decorate([
  42373. BABYLON.serialize(),
  42374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42375. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42376. __decorate([
  42377. BABYLON.serialize(),
  42378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42379. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42380. __decorate([
  42381. BABYLON.serialize(),
  42382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42383. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42384. __decorate([
  42385. BABYLON.serialize(),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42387. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42388. __decorate([
  42389. BABYLON.serialize(),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42391. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42392. __decorate([
  42393. BABYLON.serialize(),
  42394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42395. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42396. __decorate([
  42397. BABYLON.serialize(),
  42398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42399. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42400. __decorate([
  42401. BABYLON.serialize(),
  42402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42403. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42404. __decorate([
  42405. BABYLON.serialize(),
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42407. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42408. __decorate([
  42409. BABYLON.serialize(),
  42410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42411. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42412. __decorate([
  42413. BABYLON.serialize(),
  42414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42415. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42416. __decorate([
  42417. BABYLON.serialize(),
  42418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42419. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42420. __decorate([
  42421. BABYLON.serialize(),
  42422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42423. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42424. __decorate([
  42425. BABYLON.serialize(),
  42426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42427. ], PBRMaterial.prototype, "useParallax", void 0);
  42428. __decorate([
  42429. BABYLON.serialize(),
  42430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42431. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42432. __decorate([
  42433. BABYLON.serialize(),
  42434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42435. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42436. __decorate([
  42437. BABYLON.serialize(),
  42438. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42439. ], PBRMaterial.prototype, "disableLighting", void 0);
  42440. __decorate([
  42441. BABYLON.serialize(),
  42442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42443. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42444. __decorate([
  42445. BABYLON.serialize(),
  42446. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42447. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42448. __decorate([
  42449. BABYLON.serialize(),
  42450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42451. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42452. __decorate([
  42453. BABYLON.serialize(),
  42454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42455. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42456. __decorate([
  42457. BABYLON.serialize(),
  42458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42459. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42460. __decorate([
  42461. BABYLON.serialize(),
  42462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42463. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42464. __decorate([
  42465. BABYLON.serialize(),
  42466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42467. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42468. __decorate([
  42469. BABYLON.serializeAsTexture(),
  42470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42471. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42472. __decorate([
  42473. BABYLON.serialize(),
  42474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42475. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42476. __decorate([
  42477. BABYLON.serialize(),
  42478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42479. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42480. __decorate([
  42481. BABYLON.serialize(),
  42482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42483. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42484. return PBRMaterial;
  42485. }(BABYLON.PBRBaseMaterial));
  42486. BABYLON.PBRMaterial = PBRMaterial;
  42487. })(BABYLON || (BABYLON = {}));
  42488. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42489. var BABYLON;
  42490. (function (BABYLON) {
  42491. /**
  42492. * The PBR material of BJS following the metal roughness convention.
  42493. *
  42494. * This fits to the PBR convention in the GLTF definition:
  42495. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42496. */
  42497. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42498. __extends(PBRMetallicRoughnessMaterial, _super);
  42499. /**
  42500. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42501. *
  42502. * @param name The material name
  42503. * @param scene The scene the material will be use in.
  42504. */
  42505. function PBRMetallicRoughnessMaterial(name, scene) {
  42506. var _this = _super.call(this, name, scene) || this;
  42507. _this._useRoughnessFromMetallicTextureAlpha = false;
  42508. _this._useRoughnessFromMetallicTextureGreen = true;
  42509. _this._useMetallnessFromMetallicTextureBlue = true;
  42510. _this._forceMetallicWorkflow = true;
  42511. return _this;
  42512. }
  42513. /**
  42514. * Return the currrent class name of the material.
  42515. */
  42516. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42517. return "PBRMetallicRoughnessMaterial";
  42518. };
  42519. /**
  42520. * Return the active textures of the material.
  42521. */
  42522. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42523. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42524. if (this.baseTexture) {
  42525. activeTextures.push(this.baseTexture);
  42526. }
  42527. if (this.metallicRoughnessTexture) {
  42528. activeTextures.push(this.metallicRoughnessTexture);
  42529. }
  42530. return activeTextures;
  42531. };
  42532. /**
  42533. * Checks to see if a texture is used in the material.
  42534. * @param texture - Base texture to use.
  42535. * @returns - Boolean specifying if a texture is used in the material.
  42536. */
  42537. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42538. if (_super.prototype.hasTexture.call(this, texture)) {
  42539. return true;
  42540. }
  42541. if (this.baseTexture === texture) {
  42542. return true;
  42543. }
  42544. if (this.metallicRoughnessTexture === texture) {
  42545. return true;
  42546. }
  42547. return false;
  42548. };
  42549. /**
  42550. * Makes a duplicate of the current material.
  42551. * @param name - name to use for the new material.
  42552. */
  42553. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42554. var _this = this;
  42555. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42556. clone.id = name;
  42557. clone.name = name;
  42558. return clone;
  42559. };
  42560. /**
  42561. * Serialize the material to a parsable JSON object.
  42562. */
  42563. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42564. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42565. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42566. return serializationObject;
  42567. };
  42568. /**
  42569. * Parses a JSON object correponding to the serialize function.
  42570. */
  42571. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42572. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42573. };
  42574. __decorate([
  42575. BABYLON.serializeAsColor3(),
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42577. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42578. __decorate([
  42579. BABYLON.serializeAsTexture(),
  42580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42581. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42582. __decorate([
  42583. BABYLON.serialize(),
  42584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42585. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42586. __decorate([
  42587. BABYLON.serialize(),
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42589. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42590. __decorate([
  42591. BABYLON.serializeAsTexture(),
  42592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42593. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42594. return PBRMetallicRoughnessMaterial;
  42595. }(BABYLON.PBRBaseSimpleMaterial));
  42596. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42597. })(BABYLON || (BABYLON = {}));
  42598. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42599. var BABYLON;
  42600. (function (BABYLON) {
  42601. /**
  42602. * The PBR material of BJS following the specular glossiness convention.
  42603. *
  42604. * This fits to the PBR convention in the GLTF definition:
  42605. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42606. */
  42607. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42608. __extends(PBRSpecularGlossinessMaterial, _super);
  42609. /**
  42610. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42611. *
  42612. * @param name The material name
  42613. * @param scene The scene the material will be use in.
  42614. */
  42615. function PBRSpecularGlossinessMaterial(name, scene) {
  42616. var _this = _super.call(this, name, scene) || this;
  42617. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42618. return _this;
  42619. }
  42620. /**
  42621. * Return the currrent class name of the material.
  42622. */
  42623. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42624. return "PBRSpecularGlossinessMaterial";
  42625. };
  42626. /**
  42627. * Return the active textures of the material.
  42628. */
  42629. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42630. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42631. if (this.diffuseTexture) {
  42632. activeTextures.push(this.diffuseTexture);
  42633. }
  42634. if (this.specularGlossinessTexture) {
  42635. activeTextures.push(this.specularGlossinessTexture);
  42636. }
  42637. return activeTextures;
  42638. };
  42639. /**
  42640. * Checks to see if a texture is used in the material.
  42641. * @param texture - Base texture to use.
  42642. * @returns - Boolean specifying if a texture is used in the material.
  42643. */
  42644. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42645. if (_super.prototype.hasTexture.call(this, texture)) {
  42646. return true;
  42647. }
  42648. if (this.diffuseTexture === texture) {
  42649. return true;
  42650. }
  42651. if (this.specularGlossinessTexture === texture) {
  42652. return true;
  42653. }
  42654. return false;
  42655. };
  42656. /**
  42657. * Makes a duplicate of the current material.
  42658. * @param name - name to use for the new material.
  42659. */
  42660. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42661. var _this = this;
  42662. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42663. clone.id = name;
  42664. clone.name = name;
  42665. return clone;
  42666. };
  42667. /**
  42668. * Serialize the material to a parsable JSON object.
  42669. */
  42670. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42671. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42672. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42673. return serializationObject;
  42674. };
  42675. /**
  42676. * Parses a JSON object correponding to the serialize function.
  42677. */
  42678. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42679. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42680. };
  42681. __decorate([
  42682. BABYLON.serializeAsColor3("diffuse"),
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42684. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42685. __decorate([
  42686. BABYLON.serializeAsTexture(),
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42688. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42689. __decorate([
  42690. BABYLON.serializeAsColor3("specular"),
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42692. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42693. __decorate([
  42694. BABYLON.serialize(),
  42695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42696. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42697. __decorate([
  42698. BABYLON.serializeAsTexture(),
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42700. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42701. return PBRSpecularGlossinessMaterial;
  42702. }(BABYLON.PBRBaseSimpleMaterial));
  42703. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42704. })(BABYLON || (BABYLON = {}));
  42705. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42706. var BABYLON;
  42707. (function (BABYLON) {
  42708. BABYLON.CameraInputTypes = {};
  42709. var CameraInputsManager = /** @class */ (function () {
  42710. function CameraInputsManager(camera) {
  42711. this.attached = {};
  42712. this.camera = camera;
  42713. this.checkInputs = function () { };
  42714. }
  42715. /**
  42716. * Add an input method to a camera.
  42717. * builtin inputs example: camera.inputs.addGamepad();
  42718. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42719. * @param input camera input method
  42720. */
  42721. CameraInputsManager.prototype.add = function (input) {
  42722. var type = input.getSimpleName();
  42723. if (this.attached[type]) {
  42724. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42725. return;
  42726. }
  42727. this.attached[type] = input;
  42728. input.camera = this.camera;
  42729. //for checkInputs, we are dynamically creating a function
  42730. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42731. if (input.checkInputs) {
  42732. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42733. }
  42734. if (this.attachedElement) {
  42735. input.attachControl(this.attachedElement);
  42736. }
  42737. };
  42738. /**
  42739. * Remove a specific input method from a camera
  42740. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42741. * @param inputToRemove camera input method
  42742. */
  42743. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42744. for (var cam in this.attached) {
  42745. var input = this.attached[cam];
  42746. if (input === inputToRemove) {
  42747. input.detachControl(this.attachedElement);
  42748. input.camera = null;
  42749. delete this.attached[cam];
  42750. this.rebuildInputCheck();
  42751. }
  42752. }
  42753. };
  42754. CameraInputsManager.prototype.removeByType = function (inputType) {
  42755. for (var cam in this.attached) {
  42756. var input = this.attached[cam];
  42757. if (input.getClassName() === inputType) {
  42758. input.detachControl(this.attachedElement);
  42759. input.camera = null;
  42760. delete this.attached[cam];
  42761. this.rebuildInputCheck();
  42762. }
  42763. }
  42764. };
  42765. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42766. var current = this.checkInputs;
  42767. return function () {
  42768. current();
  42769. fn();
  42770. };
  42771. };
  42772. CameraInputsManager.prototype.attachInput = function (input) {
  42773. if (this.attachedElement) {
  42774. input.attachControl(this.attachedElement, this.noPreventDefault);
  42775. }
  42776. };
  42777. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42778. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42779. if (this.attachedElement) {
  42780. return;
  42781. }
  42782. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42783. this.attachedElement = element;
  42784. this.noPreventDefault = noPreventDefault;
  42785. for (var cam in this.attached) {
  42786. this.attached[cam].attachControl(element, noPreventDefault);
  42787. }
  42788. };
  42789. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42790. if (disconnect === void 0) { disconnect = false; }
  42791. if (this.attachedElement !== element) {
  42792. return;
  42793. }
  42794. for (var cam in this.attached) {
  42795. this.attached[cam].detachControl(element);
  42796. if (disconnect) {
  42797. this.attached[cam].camera = null;
  42798. }
  42799. }
  42800. this.attachedElement = null;
  42801. };
  42802. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42803. this.checkInputs = function () { };
  42804. for (var cam in this.attached) {
  42805. var input = this.attached[cam];
  42806. if (input.checkInputs) {
  42807. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42808. }
  42809. }
  42810. };
  42811. /**
  42812. * Remove all attached input methods from a camera
  42813. */
  42814. CameraInputsManager.prototype.clear = function () {
  42815. if (this.attachedElement) {
  42816. this.detachElement(this.attachedElement, true);
  42817. }
  42818. this.attached = {};
  42819. this.attachedElement = null;
  42820. this.checkInputs = function () { };
  42821. };
  42822. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42823. var inputs = {};
  42824. for (var cam in this.attached) {
  42825. var input = this.attached[cam];
  42826. var res = BABYLON.SerializationHelper.Serialize(input);
  42827. inputs[input.getClassName()] = res;
  42828. }
  42829. serializedCamera.inputsmgr = inputs;
  42830. };
  42831. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42832. var parsedInputs = parsedCamera.inputsmgr;
  42833. if (parsedInputs) {
  42834. this.clear();
  42835. for (var n in parsedInputs) {
  42836. var construct = BABYLON.CameraInputTypes[n];
  42837. if (construct) {
  42838. var parsedinput = parsedInputs[n];
  42839. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42840. this.add(input);
  42841. }
  42842. }
  42843. }
  42844. else {
  42845. //2016-03-08 this part is for managing backward compatibility
  42846. for (var n in this.attached) {
  42847. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42848. if (construct) {
  42849. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42850. this.remove(this.attached[n]);
  42851. this.add(input);
  42852. }
  42853. }
  42854. }
  42855. };
  42856. return CameraInputsManager;
  42857. }());
  42858. BABYLON.CameraInputsManager = CameraInputsManager;
  42859. })(BABYLON || (BABYLON = {}));
  42860. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42861. var BABYLON;
  42862. (function (BABYLON) {
  42863. var TargetCamera = /** @class */ (function (_super) {
  42864. __extends(TargetCamera, _super);
  42865. function TargetCamera(name, position, scene) {
  42866. var _this = _super.call(this, name, position, scene) || this;
  42867. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42868. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42869. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42870. _this.speed = 2.0;
  42871. _this.noRotationConstraint = false;
  42872. _this.lockedTarget = null;
  42873. _this._currentTarget = BABYLON.Vector3.Zero();
  42874. _this._viewMatrix = BABYLON.Matrix.Zero();
  42875. _this._camMatrix = BABYLON.Matrix.Zero();
  42876. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42877. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42878. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42879. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42880. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42881. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42882. _this._tempMatrix = BABYLON.Matrix.Zero();
  42883. return _this;
  42884. }
  42885. TargetCamera.prototype.getFrontPosition = function (distance) {
  42886. this.getWorldMatrix();
  42887. var direction = this.getTarget().subtract(this.position);
  42888. direction.normalize();
  42889. direction.scaleInPlace(distance);
  42890. return this.globalPosition.add(direction);
  42891. };
  42892. TargetCamera.prototype._getLockedTargetPosition = function () {
  42893. if (!this.lockedTarget) {
  42894. return null;
  42895. }
  42896. if (this.lockedTarget.absolutePosition) {
  42897. this.lockedTarget.computeWorldMatrix();
  42898. }
  42899. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42900. };
  42901. TargetCamera.prototype.storeState = function () {
  42902. this._storedPosition = this.position.clone();
  42903. this._storedRotation = this.rotation.clone();
  42904. if (this.rotationQuaternion) {
  42905. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42906. }
  42907. return _super.prototype.storeState.call(this);
  42908. };
  42909. /**
  42910. * Restored camera state. You must call storeState() first
  42911. */
  42912. TargetCamera.prototype._restoreStateValues = function () {
  42913. if (!_super.prototype._restoreStateValues.call(this)) {
  42914. return false;
  42915. }
  42916. this.position = this._storedPosition.clone();
  42917. this.rotation = this._storedRotation.clone();
  42918. if (this.rotationQuaternion) {
  42919. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42920. }
  42921. this.cameraDirection.copyFromFloats(0, 0, 0);
  42922. this.cameraRotation.copyFromFloats(0, 0);
  42923. return true;
  42924. };
  42925. // Cache
  42926. TargetCamera.prototype._initCache = function () {
  42927. _super.prototype._initCache.call(this);
  42928. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42929. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42930. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42931. };
  42932. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42933. if (!ignoreParentClass) {
  42934. _super.prototype._updateCache.call(this);
  42935. }
  42936. var lockedTargetPosition = this._getLockedTargetPosition();
  42937. if (!lockedTargetPosition) {
  42938. this._cache.lockedTarget = null;
  42939. }
  42940. else {
  42941. if (!this._cache.lockedTarget) {
  42942. this._cache.lockedTarget = lockedTargetPosition.clone();
  42943. }
  42944. else {
  42945. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42946. }
  42947. }
  42948. this._cache.rotation.copyFrom(this.rotation);
  42949. if (this.rotationQuaternion)
  42950. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42951. };
  42952. // Synchronized
  42953. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42954. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42955. return false;
  42956. }
  42957. var lockedTargetPosition = this._getLockedTargetPosition();
  42958. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42959. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42960. };
  42961. // Methods
  42962. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42963. var engine = this.getEngine();
  42964. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42965. };
  42966. // Target
  42967. TargetCamera.prototype.setTarget = function (target) {
  42968. this.upVector.normalize();
  42969. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42970. this._camMatrix.invert();
  42971. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42972. var vDir = target.subtract(this.position);
  42973. if (vDir.x >= 0.0) {
  42974. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42975. }
  42976. else {
  42977. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42978. }
  42979. this.rotation.z = 0;
  42980. if (isNaN(this.rotation.x)) {
  42981. this.rotation.x = 0;
  42982. }
  42983. if (isNaN(this.rotation.y)) {
  42984. this.rotation.y = 0;
  42985. }
  42986. if (isNaN(this.rotation.z)) {
  42987. this.rotation.z = 0;
  42988. }
  42989. if (this.rotationQuaternion) {
  42990. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42991. }
  42992. };
  42993. /**
  42994. * Return the current target position of the camera. This value is expressed in local space.
  42995. */
  42996. TargetCamera.prototype.getTarget = function () {
  42997. return this._currentTarget;
  42998. };
  42999. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43000. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43001. };
  43002. TargetCamera.prototype._updatePosition = function () {
  43003. if (this.parent) {
  43004. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43005. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43006. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43007. return;
  43008. }
  43009. this.position.addInPlace(this.cameraDirection);
  43010. };
  43011. TargetCamera.prototype._checkInputs = function () {
  43012. var needToMove = this._decideIfNeedsToMove();
  43013. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43014. // Move
  43015. if (needToMove) {
  43016. this._updatePosition();
  43017. }
  43018. // Rotate
  43019. if (needToRotate) {
  43020. this.rotation.x += this.cameraRotation.x;
  43021. this.rotation.y += this.cameraRotation.y;
  43022. //rotate, if quaternion is set and rotation was used
  43023. if (this.rotationQuaternion) {
  43024. var len = this.rotation.lengthSquared();
  43025. if (len) {
  43026. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43027. }
  43028. }
  43029. if (!this.noRotationConstraint) {
  43030. var limit = (Math.PI / 2) * 0.95;
  43031. if (this.rotation.x > limit)
  43032. this.rotation.x = limit;
  43033. if (this.rotation.x < -limit)
  43034. this.rotation.x = -limit;
  43035. }
  43036. }
  43037. // Inertia
  43038. if (needToMove) {
  43039. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43040. this.cameraDirection.x = 0;
  43041. }
  43042. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43043. this.cameraDirection.y = 0;
  43044. }
  43045. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43046. this.cameraDirection.z = 0;
  43047. }
  43048. this.cameraDirection.scaleInPlace(this.inertia);
  43049. }
  43050. if (needToRotate) {
  43051. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43052. this.cameraRotation.x = 0;
  43053. }
  43054. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43055. this.cameraRotation.y = 0;
  43056. }
  43057. this.cameraRotation.scaleInPlace(this.inertia);
  43058. }
  43059. _super.prototype._checkInputs.call(this);
  43060. };
  43061. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43062. if (this.rotationQuaternion) {
  43063. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43064. }
  43065. else {
  43066. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43067. }
  43068. //update the up vector!
  43069. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43070. };
  43071. TargetCamera.prototype._getViewMatrix = function () {
  43072. if (this.lockedTarget) {
  43073. this.setTarget(this._getLockedTargetPosition());
  43074. }
  43075. // Compute
  43076. this._updateCameraRotationMatrix();
  43077. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43078. // Computing target and final matrix
  43079. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43080. if (this.getScene().useRightHandedSystem) {
  43081. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43082. }
  43083. else {
  43084. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43085. }
  43086. return this._viewMatrix;
  43087. };
  43088. /**
  43089. * @override
  43090. * Override Camera.createRigCamera
  43091. */
  43092. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43093. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43094. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43095. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43096. if (!this.rotationQuaternion) {
  43097. this.rotationQuaternion = new BABYLON.Quaternion();
  43098. }
  43099. rigCamera._cameraRigParams = {};
  43100. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43101. }
  43102. return rigCamera;
  43103. }
  43104. return null;
  43105. };
  43106. /**
  43107. * @override
  43108. * Override Camera._updateRigCameras
  43109. */
  43110. TargetCamera.prototype._updateRigCameras = function () {
  43111. var camLeft = this._rigCameras[0];
  43112. var camRight = this._rigCameras[1];
  43113. switch (this.cameraRigMode) {
  43114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43115. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43116. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43117. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43118. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43119. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43120. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43121. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43122. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43123. camLeft.setTarget(this.getTarget());
  43124. camRight.setTarget(this.getTarget());
  43125. break;
  43126. case BABYLON.Camera.RIG_MODE_VR:
  43127. if (camLeft.rotationQuaternion) {
  43128. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43129. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43130. }
  43131. else {
  43132. camLeft.rotation.copyFrom(this.rotation);
  43133. camRight.rotation.copyFrom(this.rotation);
  43134. }
  43135. camLeft.position.copyFrom(this.position);
  43136. camRight.position.copyFrom(this.position);
  43137. break;
  43138. }
  43139. _super.prototype._updateRigCameras.call(this);
  43140. };
  43141. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43142. if (!this._rigCamTransformMatrix) {
  43143. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43144. }
  43145. var target = this.getTarget();
  43146. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43147. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43148. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43149. };
  43150. TargetCamera.prototype.getClassName = function () {
  43151. return "TargetCamera";
  43152. };
  43153. __decorate([
  43154. BABYLON.serializeAsVector3()
  43155. ], TargetCamera.prototype, "rotation", void 0);
  43156. __decorate([
  43157. BABYLON.serialize()
  43158. ], TargetCamera.prototype, "speed", void 0);
  43159. __decorate([
  43160. BABYLON.serializeAsMeshReference("lockedTargetId")
  43161. ], TargetCamera.prototype, "lockedTarget", void 0);
  43162. return TargetCamera;
  43163. }(BABYLON.Camera));
  43164. BABYLON.TargetCamera = TargetCamera;
  43165. })(BABYLON || (BABYLON = {}));
  43166. //# sourceMappingURL=babylon.targetCamera.js.map
  43167. var BABYLON;
  43168. (function (BABYLON) {
  43169. var FreeCameraMouseInput = /** @class */ (function () {
  43170. function FreeCameraMouseInput(touchEnabled) {
  43171. if (touchEnabled === void 0) { touchEnabled = true; }
  43172. this.touchEnabled = touchEnabled;
  43173. this.buttons = [0, 1, 2];
  43174. this.angularSensibility = 2000.0;
  43175. this.previousPosition = null;
  43176. }
  43177. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43178. var _this = this;
  43179. var engine = this.camera.getEngine();
  43180. if (!this._pointerInput) {
  43181. this._pointerInput = function (p, s) {
  43182. var evt = p.event;
  43183. if (engine.isInVRExclusivePointerMode) {
  43184. return;
  43185. }
  43186. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43187. return;
  43188. }
  43189. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43190. return;
  43191. }
  43192. var srcElement = (evt.srcElement || evt.target);
  43193. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43194. try {
  43195. srcElement.setPointerCapture(evt.pointerId);
  43196. }
  43197. catch (e) {
  43198. //Nothing to do with the error. Execution will continue.
  43199. }
  43200. _this.previousPosition = {
  43201. x: evt.clientX,
  43202. y: evt.clientY
  43203. };
  43204. if (!noPreventDefault) {
  43205. evt.preventDefault();
  43206. element.focus();
  43207. }
  43208. }
  43209. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43210. try {
  43211. srcElement.releasePointerCapture(evt.pointerId);
  43212. }
  43213. catch (e) {
  43214. //Nothing to do with the error.
  43215. }
  43216. _this.previousPosition = null;
  43217. if (!noPreventDefault) {
  43218. evt.preventDefault();
  43219. }
  43220. }
  43221. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43222. if (!_this.previousPosition || engine.isPointerLock) {
  43223. return;
  43224. }
  43225. var offsetX = evt.clientX - _this.previousPosition.x;
  43226. var offsetY = evt.clientY - _this.previousPosition.y;
  43227. if (_this.camera.getScene().useRightHandedSystem) {
  43228. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43229. }
  43230. else {
  43231. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43232. }
  43233. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43234. _this.previousPosition = {
  43235. x: evt.clientX,
  43236. y: evt.clientY
  43237. };
  43238. if (!noPreventDefault) {
  43239. evt.preventDefault();
  43240. }
  43241. }
  43242. };
  43243. }
  43244. this._onMouseMove = function (evt) {
  43245. if (!engine.isPointerLock) {
  43246. return;
  43247. }
  43248. if (engine.isInVRExclusivePointerMode) {
  43249. return;
  43250. }
  43251. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43252. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43253. if (_this.camera.getScene().useRightHandedSystem) {
  43254. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43255. }
  43256. else {
  43257. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43258. }
  43259. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43260. _this.previousPosition = null;
  43261. if (!noPreventDefault) {
  43262. evt.preventDefault();
  43263. }
  43264. };
  43265. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43266. element.addEventListener("mousemove", this._onMouseMove, false);
  43267. };
  43268. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43269. if (this._observer && element) {
  43270. this.camera.getScene().onPointerObservable.remove(this._observer);
  43271. if (this._onMouseMove) {
  43272. element.removeEventListener("mousemove", this._onMouseMove);
  43273. }
  43274. this._observer = null;
  43275. this._onMouseMove = null;
  43276. this.previousPosition = null;
  43277. }
  43278. };
  43279. FreeCameraMouseInput.prototype.getClassName = function () {
  43280. return "FreeCameraMouseInput";
  43281. };
  43282. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43283. return "mouse";
  43284. };
  43285. __decorate([
  43286. BABYLON.serialize()
  43287. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43288. __decorate([
  43289. BABYLON.serialize()
  43290. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43291. return FreeCameraMouseInput;
  43292. }());
  43293. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43294. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43295. })(BABYLON || (BABYLON = {}));
  43296. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43297. var BABYLON;
  43298. (function (BABYLON) {
  43299. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43300. function FreeCameraKeyboardMoveInput() {
  43301. this._keys = new Array();
  43302. this.keysUp = [38];
  43303. this.keysDown = [40];
  43304. this.keysLeft = [37];
  43305. this.keysRight = [39];
  43306. }
  43307. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43308. var _this = this;
  43309. if (this._onCanvasBlurObserver) {
  43310. return;
  43311. }
  43312. this._scene = this.camera.getScene();
  43313. this._engine = this._scene.getEngine();
  43314. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43315. _this._keys = [];
  43316. });
  43317. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43318. var evt = info.event;
  43319. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43320. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43321. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43322. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43323. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43324. var index = _this._keys.indexOf(evt.keyCode);
  43325. if (index === -1) {
  43326. _this._keys.push(evt.keyCode);
  43327. }
  43328. if (!noPreventDefault) {
  43329. evt.preventDefault();
  43330. }
  43331. }
  43332. }
  43333. else {
  43334. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43335. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43336. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43337. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43338. var index = _this._keys.indexOf(evt.keyCode);
  43339. if (index >= 0) {
  43340. _this._keys.splice(index, 1);
  43341. }
  43342. if (!noPreventDefault) {
  43343. evt.preventDefault();
  43344. }
  43345. }
  43346. }
  43347. });
  43348. };
  43349. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43350. if (this._scene) {
  43351. if (this._onKeyboardObserver) {
  43352. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43353. }
  43354. if (this._onCanvasBlurObserver) {
  43355. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43356. }
  43357. this._onKeyboardObserver = null;
  43358. this._onCanvasBlurObserver = null;
  43359. }
  43360. this._keys = [];
  43361. };
  43362. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43363. if (this._onKeyboardObserver) {
  43364. var camera = this.camera;
  43365. // Keyboard
  43366. for (var index = 0; index < this._keys.length; index++) {
  43367. var keyCode = this._keys[index];
  43368. var speed = camera._computeLocalCameraSpeed();
  43369. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43370. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43371. }
  43372. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43373. camera._localDirection.copyFromFloats(0, 0, speed);
  43374. }
  43375. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43376. camera._localDirection.copyFromFloats(speed, 0, 0);
  43377. }
  43378. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43379. camera._localDirection.copyFromFloats(0, 0, -speed);
  43380. }
  43381. if (camera.getScene().useRightHandedSystem) {
  43382. camera._localDirection.z *= -1;
  43383. }
  43384. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43385. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43386. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43387. }
  43388. }
  43389. };
  43390. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43391. return "FreeCameraKeyboardMoveInput";
  43392. };
  43393. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43394. this._keys = [];
  43395. };
  43396. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43397. return "keyboard";
  43398. };
  43399. __decorate([
  43400. BABYLON.serialize()
  43401. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43402. __decorate([
  43403. BABYLON.serialize()
  43404. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43405. __decorate([
  43406. BABYLON.serialize()
  43407. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43408. __decorate([
  43409. BABYLON.serialize()
  43410. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43411. return FreeCameraKeyboardMoveInput;
  43412. }());
  43413. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43414. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43415. })(BABYLON || (BABYLON = {}));
  43416. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43417. var BABYLON;
  43418. (function (BABYLON) {
  43419. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43420. __extends(FreeCameraInputsManager, _super);
  43421. function FreeCameraInputsManager(camera) {
  43422. return _super.call(this, camera) || this;
  43423. }
  43424. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43425. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43426. return this;
  43427. };
  43428. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43429. if (touchEnabled === void 0) { touchEnabled = true; }
  43430. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43431. return this;
  43432. };
  43433. FreeCameraInputsManager.prototype.addGamepad = function () {
  43434. this.add(new BABYLON.FreeCameraGamepadInput());
  43435. return this;
  43436. };
  43437. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43438. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43439. return this;
  43440. };
  43441. FreeCameraInputsManager.prototype.addTouch = function () {
  43442. this.add(new BABYLON.FreeCameraTouchInput());
  43443. return this;
  43444. };
  43445. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43446. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43447. return this;
  43448. };
  43449. return FreeCameraInputsManager;
  43450. }(BABYLON.CameraInputsManager));
  43451. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43452. })(BABYLON || (BABYLON = {}));
  43453. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43454. var BABYLON;
  43455. (function (BABYLON) {
  43456. var FreeCamera = /** @class */ (function (_super) {
  43457. __extends(FreeCamera, _super);
  43458. function FreeCamera(name, position, scene) {
  43459. var _this = _super.call(this, name, position, scene) || this;
  43460. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43461. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43462. _this.checkCollisions = false;
  43463. _this.applyGravity = false;
  43464. _this._needMoveForGravity = false;
  43465. _this._oldPosition = BABYLON.Vector3.Zero();
  43466. _this._diffPosition = BABYLON.Vector3.Zero();
  43467. _this._newPosition = BABYLON.Vector3.Zero();
  43468. // Collisions
  43469. _this._collisionMask = -1;
  43470. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43471. if (collidedMesh === void 0) { collidedMesh = null; }
  43472. //TODO move this to the collision coordinator!
  43473. if (_this.getScene().workerCollisions)
  43474. newPosition.multiplyInPlace(_this._collider._radius);
  43475. var updatePosition = function (newPos) {
  43476. _this._newPosition.copyFrom(newPos);
  43477. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43478. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43479. _this.position.addInPlace(_this._diffPosition);
  43480. if (_this.onCollide && collidedMesh) {
  43481. _this.onCollide(collidedMesh);
  43482. }
  43483. }
  43484. };
  43485. updatePosition(newPosition);
  43486. };
  43487. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43488. _this.inputs.addKeyboard().addMouse();
  43489. return _this;
  43490. }
  43491. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43492. //-- begin properties for backward compatibility for inputs
  43493. /**
  43494. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43495. * Higher values reduce sensitivity.
  43496. */
  43497. get: function () {
  43498. var mouse = this.inputs.attached["mouse"];
  43499. if (mouse)
  43500. return mouse.angularSensibility;
  43501. return 0;
  43502. },
  43503. /**
  43504. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43505. * Higher values reduce sensitivity.
  43506. */
  43507. set: function (value) {
  43508. var mouse = this.inputs.attached["mouse"];
  43509. if (mouse)
  43510. mouse.angularSensibility = value;
  43511. },
  43512. enumerable: true,
  43513. configurable: true
  43514. });
  43515. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43516. get: function () {
  43517. var keyboard = this.inputs.attached["keyboard"];
  43518. if (keyboard)
  43519. return keyboard.keysUp;
  43520. return [];
  43521. },
  43522. set: function (value) {
  43523. var keyboard = this.inputs.attached["keyboard"];
  43524. if (keyboard)
  43525. keyboard.keysUp = value;
  43526. },
  43527. enumerable: true,
  43528. configurable: true
  43529. });
  43530. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43531. get: function () {
  43532. var keyboard = this.inputs.attached["keyboard"];
  43533. if (keyboard)
  43534. return keyboard.keysDown;
  43535. return [];
  43536. },
  43537. set: function (value) {
  43538. var keyboard = this.inputs.attached["keyboard"];
  43539. if (keyboard)
  43540. keyboard.keysDown = value;
  43541. },
  43542. enumerable: true,
  43543. configurable: true
  43544. });
  43545. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43546. get: function () {
  43547. var keyboard = this.inputs.attached["keyboard"];
  43548. if (keyboard)
  43549. return keyboard.keysLeft;
  43550. return [];
  43551. },
  43552. set: function (value) {
  43553. var keyboard = this.inputs.attached["keyboard"];
  43554. if (keyboard)
  43555. keyboard.keysLeft = value;
  43556. },
  43557. enumerable: true,
  43558. configurable: true
  43559. });
  43560. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43561. get: function () {
  43562. var keyboard = this.inputs.attached["keyboard"];
  43563. if (keyboard)
  43564. return keyboard.keysRight;
  43565. return [];
  43566. },
  43567. set: function (value) {
  43568. var keyboard = this.inputs.attached["keyboard"];
  43569. if (keyboard)
  43570. keyboard.keysRight = value;
  43571. },
  43572. enumerable: true,
  43573. configurable: true
  43574. });
  43575. // Controls
  43576. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43577. this.inputs.attachElement(element, noPreventDefault);
  43578. };
  43579. FreeCamera.prototype.detachControl = function (element) {
  43580. this.inputs.detachElement(element);
  43581. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43582. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43583. };
  43584. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43585. get: function () {
  43586. return this._collisionMask;
  43587. },
  43588. set: function (mask) {
  43589. this._collisionMask = !isNaN(mask) ? mask : -1;
  43590. },
  43591. enumerable: true,
  43592. configurable: true
  43593. });
  43594. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43595. var globalPosition;
  43596. if (this.parent) {
  43597. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43598. }
  43599. else {
  43600. globalPosition = this.position;
  43601. }
  43602. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43603. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43604. if (!this._collider) {
  43605. this._collider = new BABYLON.Collider();
  43606. }
  43607. this._collider._radius = this.ellipsoid;
  43608. this._collider.collisionMask = this._collisionMask;
  43609. //no need for clone, as long as gravity is not on.
  43610. var actualDisplacement = displacement;
  43611. //add gravity to the direction to prevent the dual-collision checking
  43612. if (this.applyGravity) {
  43613. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43614. actualDisplacement = displacement.add(this.getScene().gravity);
  43615. }
  43616. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43617. };
  43618. FreeCamera.prototype._checkInputs = function () {
  43619. if (!this._localDirection) {
  43620. this._localDirection = BABYLON.Vector3.Zero();
  43621. this._transformedDirection = BABYLON.Vector3.Zero();
  43622. }
  43623. this.inputs.checkInputs();
  43624. _super.prototype._checkInputs.call(this);
  43625. };
  43626. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43627. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43628. };
  43629. FreeCamera.prototype._updatePosition = function () {
  43630. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43631. this._collideWithWorld(this.cameraDirection);
  43632. }
  43633. else {
  43634. _super.prototype._updatePosition.call(this);
  43635. }
  43636. };
  43637. FreeCamera.prototype.dispose = function () {
  43638. this.inputs.clear();
  43639. _super.prototype.dispose.call(this);
  43640. };
  43641. FreeCamera.prototype.getClassName = function () {
  43642. return "FreeCamera";
  43643. };
  43644. __decorate([
  43645. BABYLON.serializeAsVector3()
  43646. ], FreeCamera.prototype, "ellipsoid", void 0);
  43647. __decorate([
  43648. BABYLON.serializeAsVector3()
  43649. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43650. __decorate([
  43651. BABYLON.serialize()
  43652. ], FreeCamera.prototype, "checkCollisions", void 0);
  43653. __decorate([
  43654. BABYLON.serialize()
  43655. ], FreeCamera.prototype, "applyGravity", void 0);
  43656. return FreeCamera;
  43657. }(BABYLON.TargetCamera));
  43658. BABYLON.FreeCamera = FreeCamera;
  43659. })(BABYLON || (BABYLON = {}));
  43660. //# sourceMappingURL=babylon.freeCamera.js.map
  43661. var BABYLON;
  43662. (function (BABYLON) {
  43663. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43664. function ArcRotateCameraKeyboardMoveInput() {
  43665. this._keys = new Array();
  43666. this.keysUp = [38];
  43667. this.keysDown = [40];
  43668. this.keysLeft = [37];
  43669. this.keysRight = [39];
  43670. this.keysReset = [220];
  43671. this.panningSensibility = 50.0;
  43672. this.zoomingSensibility = 25.0;
  43673. this.useAltToZoom = true;
  43674. }
  43675. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43676. var _this = this;
  43677. if (this._onCanvasBlurObserver) {
  43678. return;
  43679. }
  43680. this._scene = this.camera.getScene();
  43681. this._engine = this._scene.getEngine();
  43682. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43683. _this._keys = [];
  43684. });
  43685. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43686. var evt = info.event;
  43687. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43688. _this._ctrlPressed = evt.ctrlKey;
  43689. _this._altPressed = evt.altKey;
  43690. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43691. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43692. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43693. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43694. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43695. var index = _this._keys.indexOf(evt.keyCode);
  43696. if (index === -1) {
  43697. _this._keys.push(evt.keyCode);
  43698. }
  43699. if (evt.preventDefault) {
  43700. if (!noPreventDefault) {
  43701. evt.preventDefault();
  43702. }
  43703. }
  43704. }
  43705. }
  43706. else {
  43707. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43708. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43709. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43710. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43711. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43712. var index = _this._keys.indexOf(evt.keyCode);
  43713. if (index >= 0) {
  43714. _this._keys.splice(index, 1);
  43715. }
  43716. if (evt.preventDefault) {
  43717. if (!noPreventDefault) {
  43718. evt.preventDefault();
  43719. }
  43720. }
  43721. }
  43722. }
  43723. });
  43724. };
  43725. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43726. if (this._scene) {
  43727. if (this._onKeyboardObserver) {
  43728. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43729. }
  43730. if (this._onCanvasBlurObserver) {
  43731. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43732. }
  43733. this._onKeyboardObserver = null;
  43734. this._onCanvasBlurObserver = null;
  43735. }
  43736. this._keys = [];
  43737. };
  43738. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43739. if (this._onKeyboardObserver) {
  43740. var camera = this.camera;
  43741. for (var index = 0; index < this._keys.length; index++) {
  43742. var keyCode = this._keys[index];
  43743. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43744. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43745. camera.inertialPanningX -= 1 / this.panningSensibility;
  43746. }
  43747. else {
  43748. camera.inertialAlphaOffset -= 0.01;
  43749. }
  43750. }
  43751. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43752. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43753. camera.inertialPanningY += 1 / this.panningSensibility;
  43754. }
  43755. else if (this._altPressed && this.useAltToZoom) {
  43756. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43757. }
  43758. else {
  43759. camera.inertialBetaOffset -= 0.01;
  43760. }
  43761. }
  43762. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43763. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43764. camera.inertialPanningX += 1 / this.panningSensibility;
  43765. }
  43766. else {
  43767. camera.inertialAlphaOffset += 0.01;
  43768. }
  43769. }
  43770. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43771. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43772. camera.inertialPanningY -= 1 / this.panningSensibility;
  43773. }
  43774. else if (this._altPressed && this.useAltToZoom) {
  43775. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43776. }
  43777. else {
  43778. camera.inertialBetaOffset += 0.01;
  43779. }
  43780. }
  43781. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43782. camera.restoreState();
  43783. }
  43784. }
  43785. }
  43786. };
  43787. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43788. return "ArcRotateCameraKeyboardMoveInput";
  43789. };
  43790. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43791. return "keyboard";
  43792. };
  43793. __decorate([
  43794. BABYLON.serialize()
  43795. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43796. __decorate([
  43797. BABYLON.serialize()
  43798. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43799. __decorate([
  43800. BABYLON.serialize()
  43801. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43802. __decorate([
  43803. BABYLON.serialize()
  43804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43805. __decorate([
  43806. BABYLON.serialize()
  43807. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43808. __decorate([
  43809. BABYLON.serialize()
  43810. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43811. __decorate([
  43812. BABYLON.serialize()
  43813. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43814. __decorate([
  43815. BABYLON.serialize()
  43816. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43817. return ArcRotateCameraKeyboardMoveInput;
  43818. }());
  43819. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43820. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43821. })(BABYLON || (BABYLON = {}));
  43822. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43823. var BABYLON;
  43824. (function (BABYLON) {
  43825. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43826. function ArcRotateCameraMouseWheelInput() {
  43827. this.wheelPrecision = 3.0;
  43828. /**
  43829. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43830. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43831. */
  43832. this.wheelDeltaPercentage = 0;
  43833. }
  43834. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43835. var _this = this;
  43836. this._wheel = function (p, s) {
  43837. //sanity check - this should be a PointerWheel event.
  43838. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43839. return;
  43840. var event = p.event;
  43841. var delta = 0;
  43842. if (event.wheelDelta) {
  43843. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43844. }
  43845. else if (event.detail) {
  43846. delta = -event.detail / _this.wheelPrecision;
  43847. }
  43848. if (delta)
  43849. _this.camera.inertialRadiusOffset += delta;
  43850. if (event.preventDefault) {
  43851. if (!noPreventDefault) {
  43852. event.preventDefault();
  43853. }
  43854. }
  43855. };
  43856. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43857. };
  43858. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43859. if (this._observer && element) {
  43860. this.camera.getScene().onPointerObservable.remove(this._observer);
  43861. this._observer = null;
  43862. this._wheel = null;
  43863. }
  43864. };
  43865. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43866. return "ArcRotateCameraMouseWheelInput";
  43867. };
  43868. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43869. return "mousewheel";
  43870. };
  43871. __decorate([
  43872. BABYLON.serialize()
  43873. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43874. __decorate([
  43875. BABYLON.serialize()
  43876. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43877. return ArcRotateCameraMouseWheelInput;
  43878. }());
  43879. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43880. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43881. })(BABYLON || (BABYLON = {}));
  43882. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43883. var BABYLON;
  43884. (function (BABYLON) {
  43885. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43886. function ArcRotateCameraPointersInput() {
  43887. this.buttons = [0, 1, 2];
  43888. this.angularSensibilityX = 1000.0;
  43889. this.angularSensibilityY = 1000.0;
  43890. this.pinchPrecision = 12.0;
  43891. /**
  43892. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43893. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43894. */
  43895. this.pinchDeltaPercentage = 0;
  43896. this.panningSensibility = 1000.0;
  43897. this.multiTouchPanning = true;
  43898. this.multiTouchPanAndZoom = true;
  43899. this._isPanClick = false;
  43900. this.pinchInwards = true;
  43901. }
  43902. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43903. var _this = this;
  43904. var engine = this.camera.getEngine();
  43905. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43906. var pointA = null;
  43907. var pointB = null;
  43908. var previousPinchSquaredDistance = 0;
  43909. var initialDistance = 0;
  43910. var twoFingerActivityCount = 0;
  43911. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43912. this._pointerInput = function (p, s) {
  43913. var evt = p.event;
  43914. var isTouch = p.event.pointerType === "touch";
  43915. if (engine.isInVRExclusivePointerMode) {
  43916. return;
  43917. }
  43918. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43919. return;
  43920. }
  43921. var srcElement = (evt.srcElement || evt.target);
  43922. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43923. try {
  43924. srcElement.setPointerCapture(evt.pointerId);
  43925. }
  43926. catch (e) {
  43927. //Nothing to do with the error. Execution will continue.
  43928. }
  43929. // Manage panning with pan button click
  43930. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43931. // manage pointers
  43932. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43933. if (pointA === null) {
  43934. pointA = cacheSoloPointer;
  43935. }
  43936. else if (pointB === null) {
  43937. pointB = cacheSoloPointer;
  43938. }
  43939. if (!noPreventDefault) {
  43940. evt.preventDefault();
  43941. element.focus();
  43942. }
  43943. }
  43944. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43945. _this.camera.restoreState();
  43946. }
  43947. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43948. try {
  43949. srcElement.releasePointerCapture(evt.pointerId);
  43950. }
  43951. catch (e) {
  43952. //Nothing to do with the error.
  43953. }
  43954. cacheSoloPointer = null;
  43955. previousPinchSquaredDistance = 0;
  43956. previousMultiTouchPanPosition.isPaning = false;
  43957. previousMultiTouchPanPosition.isPinching = false;
  43958. twoFingerActivityCount = 0;
  43959. initialDistance = 0;
  43960. if (!isTouch) {
  43961. pointB = null; // Mouse and pen are mono pointer
  43962. }
  43963. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43964. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43965. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43966. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43967. if (engine.badOS) {
  43968. pointA = pointB = null;
  43969. }
  43970. else {
  43971. //only remove the impacted pointer in case of multitouch allowing on most
  43972. //platforms switching from rotate to zoom and pan seamlessly.
  43973. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43974. pointA = pointB;
  43975. pointB = null;
  43976. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43977. }
  43978. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43979. pointB = null;
  43980. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43981. }
  43982. else {
  43983. pointA = pointB = null;
  43984. }
  43985. }
  43986. if (!noPreventDefault) {
  43987. evt.preventDefault();
  43988. }
  43989. }
  43990. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43991. if (!noPreventDefault) {
  43992. evt.preventDefault();
  43993. }
  43994. // One button down
  43995. if (pointA && pointB === null && cacheSoloPointer) {
  43996. if (_this.panningSensibility !== 0 &&
  43997. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43998. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43999. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44000. }
  44001. else {
  44002. var offsetX = evt.clientX - cacheSoloPointer.x;
  44003. var offsetY = evt.clientY - cacheSoloPointer.y;
  44004. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44005. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44006. }
  44007. cacheSoloPointer.x = evt.clientX;
  44008. cacheSoloPointer.y = evt.clientY;
  44009. }
  44010. else if (pointA && pointB) {
  44011. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44012. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44013. ed.x = evt.clientX;
  44014. ed.y = evt.clientY;
  44015. var direction = _this.pinchInwards ? 1 : -1;
  44016. var distX = pointA.x - pointB.x;
  44017. var distY = pointA.y - pointB.y;
  44018. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44019. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44020. if (previousPinchSquaredDistance === 0) {
  44021. initialDistance = pinchDistance;
  44022. previousPinchSquaredDistance = pinchSquaredDistance;
  44023. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44024. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44025. return;
  44026. }
  44027. if (_this.multiTouchPanAndZoom) {
  44028. if (_this.pinchDeltaPercentage) {
  44029. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44030. }
  44031. else {
  44032. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44033. (_this.pinchPrecision *
  44034. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44035. direction);
  44036. }
  44037. if (_this.panningSensibility !== 0) {
  44038. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44039. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44040. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44041. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44042. previousMultiTouchPanPosition.x = pointersCenterX;
  44043. previousMultiTouchPanPosition.y = pointersCenterY;
  44044. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44045. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44046. }
  44047. }
  44048. else {
  44049. twoFingerActivityCount++;
  44050. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44051. if (_this.pinchDeltaPercentage) {
  44052. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44053. }
  44054. else {
  44055. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44056. (_this.pinchPrecision *
  44057. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44058. direction);
  44059. }
  44060. previousMultiTouchPanPosition.isPaning = false;
  44061. previousMultiTouchPanPosition.isPinching = true;
  44062. }
  44063. else {
  44064. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44065. if (!previousMultiTouchPanPosition.isPaning) {
  44066. previousMultiTouchPanPosition.isPaning = true;
  44067. previousMultiTouchPanPosition.isPinching = false;
  44068. previousMultiTouchPanPosition.x = ed.x;
  44069. previousMultiTouchPanPosition.y = ed.y;
  44070. return;
  44071. }
  44072. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44073. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44074. }
  44075. }
  44076. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44077. previousMultiTouchPanPosition.x = ed.x;
  44078. previousMultiTouchPanPosition.y = ed.y;
  44079. }
  44080. }
  44081. previousPinchSquaredDistance = pinchSquaredDistance;
  44082. }
  44083. }
  44084. };
  44085. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44086. this._onContextMenu = function (evt) {
  44087. evt.preventDefault();
  44088. };
  44089. if (!this.camera._useCtrlForPanning) {
  44090. element.addEventListener("contextmenu", this._onContextMenu, false);
  44091. }
  44092. this._onLostFocus = function () {
  44093. //this._keys = [];
  44094. pointA = pointB = null;
  44095. previousPinchSquaredDistance = 0;
  44096. previousMultiTouchPanPosition.isPaning = false;
  44097. previousMultiTouchPanPosition.isPinching = false;
  44098. twoFingerActivityCount = 0;
  44099. cacheSoloPointer = null;
  44100. initialDistance = 0;
  44101. };
  44102. this._onMouseMove = function (evt) {
  44103. if (!engine.isPointerLock) {
  44104. return;
  44105. }
  44106. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44107. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44108. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44109. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44110. if (!noPreventDefault) {
  44111. evt.preventDefault();
  44112. }
  44113. };
  44114. this._onGestureStart = function (e) {
  44115. if (window.MSGesture === undefined) {
  44116. return;
  44117. }
  44118. if (!_this._MSGestureHandler) {
  44119. _this._MSGestureHandler = new MSGesture();
  44120. _this._MSGestureHandler.target = element;
  44121. }
  44122. _this._MSGestureHandler.addPointer(e.pointerId);
  44123. };
  44124. this._onGesture = function (e) {
  44125. _this.camera.radius *= e.scale;
  44126. if (e.preventDefault) {
  44127. if (!noPreventDefault) {
  44128. e.stopPropagation();
  44129. e.preventDefault();
  44130. }
  44131. }
  44132. };
  44133. element.addEventListener("mousemove", this._onMouseMove, false);
  44134. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44135. element.addEventListener("MSGestureChange", this._onGesture, false);
  44136. BABYLON.Tools.RegisterTopRootEvents([
  44137. { name: "blur", handler: this._onLostFocus }
  44138. ]);
  44139. };
  44140. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44141. if (this._onLostFocus) {
  44142. BABYLON.Tools.UnregisterTopRootEvents([
  44143. { name: "blur", handler: this._onLostFocus }
  44144. ]);
  44145. }
  44146. if (element && this._observer) {
  44147. this.camera.getScene().onPointerObservable.remove(this._observer);
  44148. this._observer = null;
  44149. if (this._onContextMenu) {
  44150. element.removeEventListener("contextmenu", this._onContextMenu);
  44151. }
  44152. if (this._onMouseMove) {
  44153. element.removeEventListener("mousemove", this._onMouseMove);
  44154. }
  44155. if (this._onGestureStart) {
  44156. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44157. }
  44158. if (this._onGesture) {
  44159. element.removeEventListener("MSGestureChange", this._onGesture);
  44160. }
  44161. this._isPanClick = false;
  44162. this.pinchInwards = true;
  44163. this._onMouseMove = null;
  44164. this._onGestureStart = null;
  44165. this._onGesture = null;
  44166. this._MSGestureHandler = null;
  44167. this._onLostFocus = null;
  44168. this._onContextMenu = null;
  44169. }
  44170. };
  44171. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44172. return "ArcRotateCameraPointersInput";
  44173. };
  44174. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44175. return "pointers";
  44176. };
  44177. __decorate([
  44178. BABYLON.serialize()
  44179. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44180. __decorate([
  44181. BABYLON.serialize()
  44182. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44183. __decorate([
  44184. BABYLON.serialize()
  44185. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44186. __decorate([
  44187. BABYLON.serialize()
  44188. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44189. __decorate([
  44190. BABYLON.serialize()
  44191. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44192. __decorate([
  44193. BABYLON.serialize()
  44194. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44195. __decorate([
  44196. BABYLON.serialize()
  44197. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44198. __decorate([
  44199. BABYLON.serialize()
  44200. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44201. return ArcRotateCameraPointersInput;
  44202. }());
  44203. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44204. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44205. })(BABYLON || (BABYLON = {}));
  44206. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44207. var BABYLON;
  44208. (function (BABYLON) {
  44209. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44210. __extends(ArcRotateCameraInputsManager, _super);
  44211. function ArcRotateCameraInputsManager(camera) {
  44212. return _super.call(this, camera) || this;
  44213. }
  44214. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44215. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44216. return this;
  44217. };
  44218. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44219. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44220. return this;
  44221. };
  44222. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44223. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44224. return this;
  44225. };
  44226. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44227. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44228. return this;
  44229. };
  44230. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44231. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44232. return this;
  44233. };
  44234. return ArcRotateCameraInputsManager;
  44235. }(BABYLON.CameraInputsManager));
  44236. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44237. })(BABYLON || (BABYLON = {}));
  44238. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44239. var BABYLON;
  44240. (function (BABYLON) {
  44241. var ArcRotateCamera = /** @class */ (function (_super) {
  44242. __extends(ArcRotateCamera, _super);
  44243. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44244. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44245. _this.inertialAlphaOffset = 0;
  44246. _this.inertialBetaOffset = 0;
  44247. _this.inertialRadiusOffset = 0;
  44248. _this.lowerAlphaLimit = null;
  44249. _this.upperAlphaLimit = null;
  44250. _this.lowerBetaLimit = 0.01;
  44251. _this.upperBetaLimit = Math.PI;
  44252. _this.lowerRadiusLimit = null;
  44253. _this.upperRadiusLimit = null;
  44254. _this.inertialPanningX = 0;
  44255. _this.inertialPanningY = 0;
  44256. _this.pinchToPanMaxDistance = 20;
  44257. _this.panningDistanceLimit = null;
  44258. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44259. _this.panningInertia = 0.9;
  44260. //-- end properties for backward compatibility for inputs
  44261. _this.zoomOnFactor = 1;
  44262. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44263. _this.allowUpsideDown = true;
  44264. _this._viewMatrix = new BABYLON.Matrix();
  44265. // Panning
  44266. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44267. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44268. _this.checkCollisions = false;
  44269. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44270. _this._previousPosition = BABYLON.Vector3.Zero();
  44271. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44272. _this._newPosition = BABYLON.Vector3.Zero();
  44273. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44274. if (collidedMesh === void 0) { collidedMesh = null; }
  44275. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44276. newPosition.multiplyInPlace(_this._collider._radius);
  44277. }
  44278. if (!collidedMesh) {
  44279. _this._previousPosition.copyFrom(_this.position);
  44280. }
  44281. else {
  44282. _this.setPosition(newPosition);
  44283. if (_this.onCollide) {
  44284. _this.onCollide(collidedMesh);
  44285. }
  44286. }
  44287. // Recompute because of constraints
  44288. var cosa = Math.cos(_this.alpha);
  44289. var sina = Math.sin(_this.alpha);
  44290. var cosb = Math.cos(_this.beta);
  44291. var sinb = Math.sin(_this.beta);
  44292. if (sinb === 0) {
  44293. sinb = 0.0001;
  44294. }
  44295. var target = _this._getTargetPosition();
  44296. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44297. _this.position.copyFrom(_this._newPosition);
  44298. var up = _this.upVector;
  44299. if (_this.allowUpsideDown && _this.beta < 0) {
  44300. up = up.clone();
  44301. up = up.negate();
  44302. }
  44303. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44304. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44305. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44306. _this._collisionTriggered = false;
  44307. };
  44308. _this._target = BABYLON.Vector3.Zero();
  44309. if (target) {
  44310. _this.setTarget(target);
  44311. }
  44312. _this.alpha = alpha;
  44313. _this.beta = beta;
  44314. _this.radius = radius;
  44315. _this.getViewMatrix();
  44316. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44317. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44318. return _this;
  44319. }
  44320. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44321. get: function () {
  44322. return this._target;
  44323. },
  44324. set: function (value) {
  44325. this.setTarget(value);
  44326. },
  44327. enumerable: true,
  44328. configurable: true
  44329. });
  44330. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44331. //-- begin properties for backward compatibility for inputs
  44332. get: function () {
  44333. var pointers = this.inputs.attached["pointers"];
  44334. if (pointers)
  44335. return pointers.angularSensibilityX;
  44336. return 0;
  44337. },
  44338. set: function (value) {
  44339. var pointers = this.inputs.attached["pointers"];
  44340. if (pointers) {
  44341. pointers.angularSensibilityX = value;
  44342. }
  44343. },
  44344. enumerable: true,
  44345. configurable: true
  44346. });
  44347. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44348. get: function () {
  44349. var pointers = this.inputs.attached["pointers"];
  44350. if (pointers)
  44351. return pointers.angularSensibilityY;
  44352. return 0;
  44353. },
  44354. set: function (value) {
  44355. var pointers = this.inputs.attached["pointers"];
  44356. if (pointers) {
  44357. pointers.angularSensibilityY = value;
  44358. }
  44359. },
  44360. enumerable: true,
  44361. configurable: true
  44362. });
  44363. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44364. get: function () {
  44365. var pointers = this.inputs.attached["pointers"];
  44366. if (pointers)
  44367. return pointers.pinchPrecision;
  44368. return 0;
  44369. },
  44370. set: function (value) {
  44371. var pointers = this.inputs.attached["pointers"];
  44372. if (pointers) {
  44373. pointers.pinchPrecision = value;
  44374. }
  44375. },
  44376. enumerable: true,
  44377. configurable: true
  44378. });
  44379. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44380. get: function () {
  44381. var pointers = this.inputs.attached["pointers"];
  44382. if (pointers)
  44383. return pointers.pinchDeltaPercentage;
  44384. return 0;
  44385. },
  44386. set: function (value) {
  44387. var pointers = this.inputs.attached["pointers"];
  44388. if (pointers) {
  44389. pointers.pinchDeltaPercentage = value;
  44390. }
  44391. },
  44392. enumerable: true,
  44393. configurable: true
  44394. });
  44395. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44396. get: function () {
  44397. var pointers = this.inputs.attached["pointers"];
  44398. if (pointers)
  44399. return pointers.panningSensibility;
  44400. return 0;
  44401. },
  44402. set: function (value) {
  44403. var pointers = this.inputs.attached["pointers"];
  44404. if (pointers) {
  44405. pointers.panningSensibility = value;
  44406. }
  44407. },
  44408. enumerable: true,
  44409. configurable: true
  44410. });
  44411. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44412. get: function () {
  44413. var keyboard = this.inputs.attached["keyboard"];
  44414. if (keyboard)
  44415. return keyboard.keysUp;
  44416. return [];
  44417. },
  44418. set: function (value) {
  44419. var keyboard = this.inputs.attached["keyboard"];
  44420. if (keyboard)
  44421. keyboard.keysUp = value;
  44422. },
  44423. enumerable: true,
  44424. configurable: true
  44425. });
  44426. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44427. get: function () {
  44428. var keyboard = this.inputs.attached["keyboard"];
  44429. if (keyboard)
  44430. return keyboard.keysDown;
  44431. return [];
  44432. },
  44433. set: function (value) {
  44434. var keyboard = this.inputs.attached["keyboard"];
  44435. if (keyboard)
  44436. keyboard.keysDown = value;
  44437. },
  44438. enumerable: true,
  44439. configurable: true
  44440. });
  44441. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44442. get: function () {
  44443. var keyboard = this.inputs.attached["keyboard"];
  44444. if (keyboard)
  44445. return keyboard.keysLeft;
  44446. return [];
  44447. },
  44448. set: function (value) {
  44449. var keyboard = this.inputs.attached["keyboard"];
  44450. if (keyboard)
  44451. keyboard.keysLeft = value;
  44452. },
  44453. enumerable: true,
  44454. configurable: true
  44455. });
  44456. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44457. get: function () {
  44458. var keyboard = this.inputs.attached["keyboard"];
  44459. if (keyboard)
  44460. return keyboard.keysRight;
  44461. return [];
  44462. },
  44463. set: function (value) {
  44464. var keyboard = this.inputs.attached["keyboard"];
  44465. if (keyboard)
  44466. keyboard.keysRight = value;
  44467. },
  44468. enumerable: true,
  44469. configurable: true
  44470. });
  44471. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44472. get: function () {
  44473. var mousewheel = this.inputs.attached["mousewheel"];
  44474. if (mousewheel)
  44475. return mousewheel.wheelPrecision;
  44476. return 0;
  44477. },
  44478. set: function (value) {
  44479. var mousewheel = this.inputs.attached["mousewheel"];
  44480. if (mousewheel)
  44481. mousewheel.wheelPrecision = value;
  44482. },
  44483. enumerable: true,
  44484. configurable: true
  44485. });
  44486. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44487. get: function () {
  44488. var mousewheel = this.inputs.attached["mousewheel"];
  44489. if (mousewheel)
  44490. return mousewheel.wheelDeltaPercentage;
  44491. return 0;
  44492. },
  44493. set: function (value) {
  44494. var mousewheel = this.inputs.attached["mousewheel"];
  44495. if (mousewheel)
  44496. mousewheel.wheelDeltaPercentage = value;
  44497. },
  44498. enumerable: true,
  44499. configurable: true
  44500. });
  44501. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44502. get: function () {
  44503. return this._bouncingBehavior;
  44504. },
  44505. enumerable: true,
  44506. configurable: true
  44507. });
  44508. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44509. get: function () {
  44510. return this._bouncingBehavior != null;
  44511. },
  44512. set: function (value) {
  44513. if (value === this.useBouncingBehavior) {
  44514. return;
  44515. }
  44516. if (value) {
  44517. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44518. this.addBehavior(this._bouncingBehavior);
  44519. }
  44520. else if (this._bouncingBehavior) {
  44521. this.removeBehavior(this._bouncingBehavior);
  44522. this._bouncingBehavior = null;
  44523. }
  44524. },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44529. get: function () {
  44530. return this._framingBehavior;
  44531. },
  44532. enumerable: true,
  44533. configurable: true
  44534. });
  44535. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44536. get: function () {
  44537. return this._framingBehavior != null;
  44538. },
  44539. set: function (value) {
  44540. if (value === this.useFramingBehavior) {
  44541. return;
  44542. }
  44543. if (value) {
  44544. this._framingBehavior = new BABYLON.FramingBehavior();
  44545. this.addBehavior(this._framingBehavior);
  44546. }
  44547. else if (this._framingBehavior) {
  44548. this.removeBehavior(this._framingBehavior);
  44549. this._framingBehavior = null;
  44550. }
  44551. },
  44552. enumerable: true,
  44553. configurable: true
  44554. });
  44555. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44556. get: function () {
  44557. return this._autoRotationBehavior;
  44558. },
  44559. enumerable: true,
  44560. configurable: true
  44561. });
  44562. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44563. get: function () {
  44564. return this._autoRotationBehavior != null;
  44565. },
  44566. set: function (value) {
  44567. if (value === this.useAutoRotationBehavior) {
  44568. return;
  44569. }
  44570. if (value) {
  44571. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44572. this.addBehavior(this._autoRotationBehavior);
  44573. }
  44574. else if (this._autoRotationBehavior) {
  44575. this.removeBehavior(this._autoRotationBehavior);
  44576. this._autoRotationBehavior = null;
  44577. }
  44578. },
  44579. enumerable: true,
  44580. configurable: true
  44581. });
  44582. // Cache
  44583. ArcRotateCamera.prototype._initCache = function () {
  44584. _super.prototype._initCache.call(this);
  44585. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44586. this._cache.alpha = undefined;
  44587. this._cache.beta = undefined;
  44588. this._cache.radius = undefined;
  44589. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44590. };
  44591. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44592. if (!ignoreParentClass) {
  44593. _super.prototype._updateCache.call(this);
  44594. }
  44595. this._cache._target.copyFrom(this._getTargetPosition());
  44596. this._cache.alpha = this.alpha;
  44597. this._cache.beta = this.beta;
  44598. this._cache.radius = this.radius;
  44599. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44600. };
  44601. ArcRotateCamera.prototype._getTargetPosition = function () {
  44602. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44603. var pos = this._targetHost.getAbsolutePosition();
  44604. if (this._targetBoundingCenter) {
  44605. pos.addToRef(this._targetBoundingCenter, this._target);
  44606. }
  44607. else {
  44608. this._target.copyFrom(pos);
  44609. }
  44610. }
  44611. var lockedTargetPosition = this._getLockedTargetPosition();
  44612. if (lockedTargetPosition) {
  44613. return lockedTargetPosition;
  44614. }
  44615. return this._target;
  44616. };
  44617. ArcRotateCamera.prototype.storeState = function () {
  44618. this._storedAlpha = this.alpha;
  44619. this._storedBeta = this.beta;
  44620. this._storedRadius = this.radius;
  44621. this._storedTarget = this._getTargetPosition().clone();
  44622. return _super.prototype.storeState.call(this);
  44623. };
  44624. /**
  44625. * Restored camera state. You must call storeState() first
  44626. */
  44627. ArcRotateCamera.prototype._restoreStateValues = function () {
  44628. if (!_super.prototype._restoreStateValues.call(this)) {
  44629. return false;
  44630. }
  44631. this.alpha = this._storedAlpha;
  44632. this.beta = this._storedBeta;
  44633. this.radius = this._storedRadius;
  44634. this.setTarget(this._storedTarget.clone());
  44635. this.inertialAlphaOffset = 0;
  44636. this.inertialBetaOffset = 0;
  44637. this.inertialRadiusOffset = 0;
  44638. this.inertialPanningX = 0;
  44639. this.inertialPanningY = 0;
  44640. return true;
  44641. };
  44642. // Synchronized
  44643. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44644. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44645. return false;
  44646. return this._cache._target.equals(this._getTargetPosition())
  44647. && this._cache.alpha === this.alpha
  44648. && this._cache.beta === this.beta
  44649. && this._cache.radius === this.radius
  44650. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44651. };
  44652. // Methods
  44653. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44654. var _this = this;
  44655. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44656. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44657. this._useCtrlForPanning = useCtrlForPanning;
  44658. this._panningMouseButton = panningMouseButton;
  44659. this.inputs.attachElement(element, noPreventDefault);
  44660. this._reset = function () {
  44661. _this.inertialAlphaOffset = 0;
  44662. _this.inertialBetaOffset = 0;
  44663. _this.inertialRadiusOffset = 0;
  44664. _this.inertialPanningX = 0;
  44665. _this.inertialPanningY = 0;
  44666. };
  44667. };
  44668. ArcRotateCamera.prototype.detachControl = function (element) {
  44669. this.inputs.detachElement(element);
  44670. if (this._reset) {
  44671. this._reset();
  44672. }
  44673. };
  44674. ArcRotateCamera.prototype._checkInputs = function () {
  44675. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44676. if (this._collisionTriggered) {
  44677. return;
  44678. }
  44679. this.inputs.checkInputs();
  44680. // Inertia
  44681. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44682. if (this.getScene().useRightHandedSystem) {
  44683. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44684. }
  44685. else {
  44686. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44687. }
  44688. this.beta += this.inertialBetaOffset;
  44689. this.radius -= this.inertialRadiusOffset;
  44690. this.inertialAlphaOffset *= this.inertia;
  44691. this.inertialBetaOffset *= this.inertia;
  44692. this.inertialRadiusOffset *= this.inertia;
  44693. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44694. this.inertialAlphaOffset = 0;
  44695. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44696. this.inertialBetaOffset = 0;
  44697. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44698. this.inertialRadiusOffset = 0;
  44699. }
  44700. // Panning inertia
  44701. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44702. if (!this._localDirection) {
  44703. this._localDirection = BABYLON.Vector3.Zero();
  44704. this._transformedDirection = BABYLON.Vector3.Zero();
  44705. }
  44706. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44707. this._localDirection.multiplyInPlace(this.panningAxis);
  44708. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44709. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44710. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44711. if (!this.panningAxis.y) {
  44712. this._transformedDirection.y = 0;
  44713. }
  44714. if (!this._targetHost) {
  44715. if (this.panningDistanceLimit) {
  44716. this._transformedDirection.addInPlace(this._target);
  44717. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44718. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44719. this._target.copyFrom(this._transformedDirection);
  44720. }
  44721. }
  44722. else {
  44723. this._target.addInPlace(this._transformedDirection);
  44724. }
  44725. }
  44726. this.inertialPanningX *= this.panningInertia;
  44727. this.inertialPanningY *= this.panningInertia;
  44728. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44729. this.inertialPanningX = 0;
  44730. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44731. this.inertialPanningY = 0;
  44732. }
  44733. // Limits
  44734. this._checkLimits();
  44735. _super.prototype._checkInputs.call(this);
  44736. };
  44737. ArcRotateCamera.prototype._checkLimits = function () {
  44738. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44739. if (this.allowUpsideDown && this.beta > Math.PI) {
  44740. this.beta = this.beta - (2 * Math.PI);
  44741. }
  44742. }
  44743. else {
  44744. if (this.beta < this.lowerBetaLimit) {
  44745. this.beta = this.lowerBetaLimit;
  44746. }
  44747. }
  44748. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44749. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44750. this.beta = this.beta + (2 * Math.PI);
  44751. }
  44752. }
  44753. else {
  44754. if (this.beta > this.upperBetaLimit) {
  44755. this.beta = this.upperBetaLimit;
  44756. }
  44757. }
  44758. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44759. this.alpha = this.lowerAlphaLimit;
  44760. }
  44761. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44762. this.alpha = this.upperAlphaLimit;
  44763. }
  44764. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44765. this.radius = this.lowerRadiusLimit;
  44766. }
  44767. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44768. this.radius = this.upperRadiusLimit;
  44769. }
  44770. };
  44771. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44772. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44773. this.radius = radiusv3.length();
  44774. if (this.radius === 0) {
  44775. this.radius = 0.0001; // Just to avoid division by zero
  44776. }
  44777. // Alpha
  44778. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44779. if (radiusv3.z < 0) {
  44780. this.alpha = 2 * Math.PI - this.alpha;
  44781. }
  44782. // Beta
  44783. this.beta = Math.acos(radiusv3.y / this.radius);
  44784. this._checkLimits();
  44785. };
  44786. ArcRotateCamera.prototype.setPosition = function (position) {
  44787. if (this.position.equals(position)) {
  44788. return;
  44789. }
  44790. this.position.copyFrom(position);
  44791. this.rebuildAnglesAndRadius();
  44792. };
  44793. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44794. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44795. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44796. if (target.getBoundingInfo) {
  44797. if (toBoundingCenter) {
  44798. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44799. }
  44800. else {
  44801. this._targetBoundingCenter = null;
  44802. }
  44803. this._targetHost = target;
  44804. this._target = this._getTargetPosition();
  44805. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44806. }
  44807. else {
  44808. var newTarget = target;
  44809. var currentTarget = this._getTargetPosition();
  44810. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44811. return;
  44812. }
  44813. this._targetHost = null;
  44814. this._target = newTarget;
  44815. this._targetBoundingCenter = null;
  44816. this.onMeshTargetChangedObservable.notifyObservers(null);
  44817. }
  44818. this.rebuildAnglesAndRadius();
  44819. };
  44820. ArcRotateCamera.prototype._getViewMatrix = function () {
  44821. // Compute
  44822. var cosa = Math.cos(this.alpha);
  44823. var sina = Math.sin(this.alpha);
  44824. var cosb = Math.cos(this.beta);
  44825. var sinb = Math.sin(this.beta);
  44826. if (sinb === 0) {
  44827. sinb = 0.0001;
  44828. }
  44829. var target = this._getTargetPosition();
  44830. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44831. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44832. if (!this._collider) {
  44833. this._collider = new BABYLON.Collider();
  44834. }
  44835. this._collider._radius = this.collisionRadius;
  44836. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44837. this._collisionTriggered = true;
  44838. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44839. }
  44840. else {
  44841. this.position.copyFrom(this._newPosition);
  44842. var up = this.upVector;
  44843. if (this.allowUpsideDown && sinb < 0) {
  44844. up = up.clone();
  44845. up = up.negate();
  44846. }
  44847. if (this.getScene().useRightHandedSystem) {
  44848. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44849. }
  44850. else {
  44851. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44852. }
  44853. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44854. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44855. }
  44856. this._currentTarget = target;
  44857. return this._viewMatrix;
  44858. };
  44859. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44860. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44861. meshes = meshes || this.getScene().meshes;
  44862. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44863. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44864. this.radius = distance * this.zoomOnFactor;
  44865. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44866. };
  44867. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44868. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44869. var meshesOrMinMaxVector;
  44870. var distance;
  44871. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44872. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44873. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44874. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44875. }
  44876. else {
  44877. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44878. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44879. distance = minMaxVectorAndDistance.distance;
  44880. }
  44881. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44882. if (!doNotUpdateMaxZ) {
  44883. this.maxZ = distance * 2;
  44884. }
  44885. };
  44886. /**
  44887. * @override
  44888. * Override Camera.createRigCamera
  44889. */
  44890. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44891. var alphaShift = 0;
  44892. switch (this.cameraRigMode) {
  44893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44895. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44896. case BABYLON.Camera.RIG_MODE_VR:
  44897. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44898. break;
  44899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44900. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44901. break;
  44902. }
  44903. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44904. rigCam._cameraRigParams = {};
  44905. return rigCam;
  44906. };
  44907. /**
  44908. * @override
  44909. * Override Camera._updateRigCameras
  44910. */
  44911. ArcRotateCamera.prototype._updateRigCameras = function () {
  44912. var camLeft = this._rigCameras[0];
  44913. var camRight = this._rigCameras[1];
  44914. camLeft.beta = camRight.beta = this.beta;
  44915. camLeft.radius = camRight.radius = this.radius;
  44916. switch (this.cameraRigMode) {
  44917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44919. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44920. case BABYLON.Camera.RIG_MODE_VR:
  44921. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44922. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44923. break;
  44924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44925. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44926. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44927. break;
  44928. }
  44929. _super.prototype._updateRigCameras.call(this);
  44930. };
  44931. ArcRotateCamera.prototype.dispose = function () {
  44932. this.inputs.clear();
  44933. _super.prototype.dispose.call(this);
  44934. };
  44935. ArcRotateCamera.prototype.getClassName = function () {
  44936. return "ArcRotateCamera";
  44937. };
  44938. __decorate([
  44939. BABYLON.serialize()
  44940. ], ArcRotateCamera.prototype, "alpha", void 0);
  44941. __decorate([
  44942. BABYLON.serialize()
  44943. ], ArcRotateCamera.prototype, "beta", void 0);
  44944. __decorate([
  44945. BABYLON.serialize()
  44946. ], ArcRotateCamera.prototype, "radius", void 0);
  44947. __decorate([
  44948. BABYLON.serializeAsVector3("target")
  44949. ], ArcRotateCamera.prototype, "_target", void 0);
  44950. __decorate([
  44951. BABYLON.serialize()
  44952. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44953. __decorate([
  44954. BABYLON.serialize()
  44955. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44956. __decorate([
  44957. BABYLON.serialize()
  44958. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44959. __decorate([
  44960. BABYLON.serialize()
  44961. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44962. __decorate([
  44963. BABYLON.serialize()
  44964. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44965. __decorate([
  44966. BABYLON.serialize()
  44967. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44968. __decorate([
  44969. BABYLON.serialize()
  44970. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44971. __decorate([
  44972. BABYLON.serialize()
  44973. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44974. __decorate([
  44975. BABYLON.serialize()
  44976. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44977. __decorate([
  44978. BABYLON.serialize()
  44979. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44980. __decorate([
  44981. BABYLON.serialize()
  44982. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44983. __decorate([
  44984. BABYLON.serialize()
  44985. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44986. __decorate([
  44987. BABYLON.serialize()
  44988. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44989. __decorate([
  44990. BABYLON.serializeAsVector3()
  44991. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44992. __decorate([
  44993. BABYLON.serialize()
  44994. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44995. __decorate([
  44996. BABYLON.serialize()
  44997. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44998. __decorate([
  44999. BABYLON.serialize()
  45000. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45001. return ArcRotateCamera;
  45002. }(BABYLON.TargetCamera));
  45003. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45004. })(BABYLON || (BABYLON = {}));
  45005. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45006. var BABYLON;
  45007. (function (BABYLON) {
  45008. /**
  45009. * The HemisphericLight simulates the ambient environment light,
  45010. * so the passed direction is the light reflection direction, not the incoming direction.
  45011. */
  45012. var HemisphericLight = /** @class */ (function (_super) {
  45013. __extends(HemisphericLight, _super);
  45014. /**
  45015. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45016. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45017. * The HemisphericLight can't cast shadows.
  45018. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45019. * @param name The friendly name of the light
  45020. * @param direction The direction of the light reflection
  45021. * @param scene The scene the light belongs to
  45022. */
  45023. function HemisphericLight(name, direction, scene) {
  45024. var _this = _super.call(this, name, scene) || this;
  45025. /**
  45026. * The groundColor is the light in the opposite direction to the one specified during creation.
  45027. * 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.
  45028. */
  45029. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45030. _this.direction = direction || BABYLON.Vector3.Up();
  45031. return _this;
  45032. }
  45033. HemisphericLight.prototype._buildUniformLayout = function () {
  45034. this._uniformBuffer.addUniform("vLightData", 4);
  45035. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45036. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45037. this._uniformBuffer.addUniform("vLightGround", 3);
  45038. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45039. this._uniformBuffer.addUniform("depthValues", 2);
  45040. this._uniformBuffer.create();
  45041. };
  45042. /**
  45043. * Returns the string "HemisphericLight".
  45044. * @return The class name
  45045. */
  45046. HemisphericLight.prototype.getClassName = function () {
  45047. return "HemisphericLight";
  45048. };
  45049. /**
  45050. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45051. * Returns the updated direction.
  45052. * @param target The target the direction should point to
  45053. * @return The computed direction
  45054. */
  45055. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45056. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45057. return this.direction;
  45058. };
  45059. /**
  45060. * Returns the shadow generator associated to the light.
  45061. * @returns Always null for hemispheric lights because it does not support shadows.
  45062. */
  45063. HemisphericLight.prototype.getShadowGenerator = function () {
  45064. return null;
  45065. };
  45066. /**
  45067. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45068. * @param effect The effect to update
  45069. * @param lightIndex The index of the light in the effect to update
  45070. * @returns The hemispheric light
  45071. */
  45072. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45073. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45074. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45075. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45076. return this;
  45077. };
  45078. /**
  45079. * @ignore internal use only.
  45080. */
  45081. HemisphericLight.prototype._getWorldMatrix = function () {
  45082. if (!this._worldMatrix) {
  45083. this._worldMatrix = BABYLON.Matrix.Identity();
  45084. }
  45085. return this._worldMatrix;
  45086. };
  45087. /**
  45088. * Returns the integer 3.
  45089. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45090. */
  45091. HemisphericLight.prototype.getTypeID = function () {
  45092. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45093. };
  45094. __decorate([
  45095. BABYLON.serializeAsColor3()
  45096. ], HemisphericLight.prototype, "groundColor", void 0);
  45097. __decorate([
  45098. BABYLON.serializeAsVector3()
  45099. ], HemisphericLight.prototype, "direction", void 0);
  45100. return HemisphericLight;
  45101. }(BABYLON.Light));
  45102. BABYLON.HemisphericLight = HemisphericLight;
  45103. })(BABYLON || (BABYLON = {}));
  45104. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45105. var BABYLON;
  45106. (function (BABYLON) {
  45107. /**
  45108. * Base implementation of @see IShadowLight
  45109. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45110. */
  45111. var ShadowLight = /** @class */ (function (_super) {
  45112. __extends(ShadowLight, _super);
  45113. function ShadowLight() {
  45114. var _this = _super !== null && _super.apply(this, arguments) || this;
  45115. _this._needProjectionMatrixCompute = true;
  45116. return _this;
  45117. }
  45118. ShadowLight.prototype._setPosition = function (value) {
  45119. this._position = value;
  45120. };
  45121. Object.defineProperty(ShadowLight.prototype, "position", {
  45122. /**
  45123. * Sets the position the shadow will be casted from. Also use as the light position for both
  45124. * point and spot lights.
  45125. */
  45126. get: function () {
  45127. return this._position;
  45128. },
  45129. /**
  45130. * Sets the position the shadow will be casted from. Also use as the light position for both
  45131. * point and spot lights.
  45132. */
  45133. set: function (value) {
  45134. this._setPosition(value);
  45135. },
  45136. enumerable: true,
  45137. configurable: true
  45138. });
  45139. ShadowLight.prototype._setDirection = function (value) {
  45140. this._direction = value;
  45141. };
  45142. Object.defineProperty(ShadowLight.prototype, "direction", {
  45143. /**
  45144. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45145. * Also use as the light direction on spot and directional lights.
  45146. */
  45147. get: function () {
  45148. return this._direction;
  45149. },
  45150. /**
  45151. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45152. * Also use as the light direction on spot and directional lights.
  45153. */
  45154. set: function (value) {
  45155. this._setDirection(value);
  45156. },
  45157. enumerable: true,
  45158. configurable: true
  45159. });
  45160. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45161. /**
  45162. * Gets the shadow projection clipping minimum z value.
  45163. */
  45164. get: function () {
  45165. return this._shadowMinZ;
  45166. },
  45167. /**
  45168. * Sets the shadow projection clipping minimum z value.
  45169. */
  45170. set: function (value) {
  45171. this._shadowMinZ = value;
  45172. this.forceProjectionMatrixCompute();
  45173. },
  45174. enumerable: true,
  45175. configurable: true
  45176. });
  45177. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45178. /**
  45179. * Sets the shadow projection clipping maximum z value.
  45180. */
  45181. get: function () {
  45182. return this._shadowMaxZ;
  45183. },
  45184. /**
  45185. * Gets the shadow projection clipping maximum z value.
  45186. */
  45187. set: function (value) {
  45188. this._shadowMaxZ = value;
  45189. this.forceProjectionMatrixCompute();
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. /**
  45195. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45196. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45197. */
  45198. ShadowLight.prototype.computeTransformedInformation = function () {
  45199. if (this.parent && this.parent.getWorldMatrix) {
  45200. if (!this.transformedPosition) {
  45201. this.transformedPosition = BABYLON.Vector3.Zero();
  45202. }
  45203. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45204. // In case the direction is present.
  45205. if (this.direction) {
  45206. if (!this.transformedDirection) {
  45207. this.transformedDirection = BABYLON.Vector3.Zero();
  45208. }
  45209. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45210. }
  45211. return true;
  45212. }
  45213. return false;
  45214. };
  45215. /**
  45216. * Return the depth scale used for the shadow map.
  45217. * @returns the depth scale.
  45218. */
  45219. ShadowLight.prototype.getDepthScale = function () {
  45220. return 50.0;
  45221. };
  45222. /**
  45223. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45224. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45225. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45226. */
  45227. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45228. return this.transformedDirection ? this.transformedDirection : this.direction;
  45229. };
  45230. /**
  45231. * Returns the ShadowLight absolute position in the World.
  45232. * @returns the position vector in world space
  45233. */
  45234. ShadowLight.prototype.getAbsolutePosition = function () {
  45235. return this.transformedPosition ? this.transformedPosition : this.position;
  45236. };
  45237. /**
  45238. * Sets the ShadowLight direction toward the passed target.
  45239. * @param target The point tot target in local space
  45240. * @returns the updated ShadowLight direction
  45241. */
  45242. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45243. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45244. return this.direction;
  45245. };
  45246. /**
  45247. * Returns the light rotation in euler definition.
  45248. * @returns the x y z rotation in local space.
  45249. */
  45250. ShadowLight.prototype.getRotation = function () {
  45251. this.direction.normalize();
  45252. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45253. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45254. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45255. };
  45256. /**
  45257. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45258. * @returns true if a cube texture needs to be use
  45259. */
  45260. ShadowLight.prototype.needCube = function () {
  45261. return false;
  45262. };
  45263. /**
  45264. * Detects if the projection matrix requires to be recomputed this frame.
  45265. * @returns true if it requires to be recomputed otherwise, false.
  45266. */
  45267. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45268. return this._needProjectionMatrixCompute;
  45269. };
  45270. /**
  45271. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45272. */
  45273. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45274. this._needProjectionMatrixCompute = true;
  45275. };
  45276. /**
  45277. * Get the world matrix of the sahdow lights.
  45278. * @ignore Internal Use Only
  45279. */
  45280. ShadowLight.prototype._getWorldMatrix = function () {
  45281. if (!this._worldMatrix) {
  45282. this._worldMatrix = BABYLON.Matrix.Identity();
  45283. }
  45284. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45285. return this._worldMatrix;
  45286. };
  45287. /**
  45288. * Gets the minZ used for shadow according to both the scene and the light.
  45289. * @param activeCamera The camera we are returning the min for
  45290. * @returns the depth min z
  45291. */
  45292. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45293. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45294. };
  45295. /**
  45296. * Gets the maxZ used for shadow according to both the scene and the light.
  45297. * @param activeCamera The camera we are returning the max for
  45298. * @returns the depth max z
  45299. */
  45300. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45301. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45302. };
  45303. /**
  45304. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45305. * @param matrix The materix to updated with the projection information
  45306. * @param viewMatrix The transform matrix of the light
  45307. * @param renderList The list of mesh to render in the map
  45308. * @returns The current light
  45309. */
  45310. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45311. if (this.customProjectionMatrixBuilder) {
  45312. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45313. }
  45314. else {
  45315. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45316. }
  45317. return this;
  45318. };
  45319. __decorate([
  45320. BABYLON.serializeAsVector3()
  45321. ], ShadowLight.prototype, "position", null);
  45322. __decorate([
  45323. BABYLON.serializeAsVector3()
  45324. ], ShadowLight.prototype, "direction", null);
  45325. __decorate([
  45326. BABYLON.serialize()
  45327. ], ShadowLight.prototype, "shadowMinZ", null);
  45328. __decorate([
  45329. BABYLON.serialize()
  45330. ], ShadowLight.prototype, "shadowMaxZ", null);
  45331. return ShadowLight;
  45332. }(BABYLON.Light));
  45333. BABYLON.ShadowLight = ShadowLight;
  45334. })(BABYLON || (BABYLON = {}));
  45335. //# sourceMappingURL=babylon.shadowLight.js.map
  45336. var BABYLON;
  45337. (function (BABYLON) {
  45338. /**
  45339. * A point light is a light defined by an unique point in world space.
  45340. * The light is emitted in every direction from this point.
  45341. * A good example of a point light is a standard light bulb.
  45342. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45343. */
  45344. var PointLight = /** @class */ (function (_super) {
  45345. __extends(PointLight, _super);
  45346. /**
  45347. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45348. * A PointLight emits the light in every direction.
  45349. * It can cast shadows.
  45350. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45351. * ```javascript
  45352. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45353. * ```
  45354. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45355. * @param name The light friendly name
  45356. * @param position The position of the point light in the scene
  45357. * @param scene The scene the lights belongs to
  45358. */
  45359. function PointLight(name, position, scene) {
  45360. var _this = _super.call(this, name, scene) || this;
  45361. _this._shadowAngle = Math.PI / 2;
  45362. _this.position = position;
  45363. return _this;
  45364. }
  45365. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45366. /**
  45367. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45368. * This specifies what angle the shadow will use to be created.
  45369. *
  45370. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45371. */
  45372. get: function () {
  45373. return this._shadowAngle;
  45374. },
  45375. /**
  45376. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45377. * This specifies what angle the shadow will use to be created.
  45378. *
  45379. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45380. */
  45381. set: function (value) {
  45382. this._shadowAngle = value;
  45383. this.forceProjectionMatrixCompute();
  45384. },
  45385. enumerable: true,
  45386. configurable: true
  45387. });
  45388. Object.defineProperty(PointLight.prototype, "direction", {
  45389. /**
  45390. * Gets the direction if it has been set.
  45391. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45392. */
  45393. get: function () {
  45394. return this._direction;
  45395. },
  45396. /**
  45397. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45398. */
  45399. set: function (value) {
  45400. var previousNeedCube = this.needCube();
  45401. this._direction = value;
  45402. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45403. this._shadowGenerator.recreateShadowMap();
  45404. }
  45405. },
  45406. enumerable: true,
  45407. configurable: true
  45408. });
  45409. /**
  45410. * Returns the string "PointLight"
  45411. * @returns the class name
  45412. */
  45413. PointLight.prototype.getClassName = function () {
  45414. return "PointLight";
  45415. };
  45416. /**
  45417. * Returns the integer 0.
  45418. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45419. */
  45420. PointLight.prototype.getTypeID = function () {
  45421. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45422. };
  45423. /**
  45424. * Specifies wether or not the shadowmap should be a cube texture.
  45425. * @returns true if the shadowmap needs to be a cube texture.
  45426. */
  45427. PointLight.prototype.needCube = function () {
  45428. return !this.direction;
  45429. };
  45430. /**
  45431. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45432. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45433. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45434. */
  45435. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45436. if (this.direction) {
  45437. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45438. }
  45439. else {
  45440. switch (faceIndex) {
  45441. case 0:
  45442. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45443. case 1:
  45444. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45445. case 2:
  45446. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45447. case 3:
  45448. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45449. case 4:
  45450. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45451. case 5:
  45452. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45453. }
  45454. }
  45455. return BABYLON.Vector3.Zero();
  45456. };
  45457. /**
  45458. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45459. * - fov = PI / 2
  45460. * - aspect ratio : 1.0
  45461. * - z-near and far equal to the active camera minZ and maxZ.
  45462. * Returns the PointLight.
  45463. */
  45464. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45465. var activeCamera = this.getScene().activeCamera;
  45466. if (!activeCamera) {
  45467. return;
  45468. }
  45469. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45470. };
  45471. PointLight.prototype._buildUniformLayout = function () {
  45472. this._uniformBuffer.addUniform("vLightData", 4);
  45473. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45474. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45475. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45476. this._uniformBuffer.addUniform("depthValues", 2);
  45477. this._uniformBuffer.create();
  45478. };
  45479. /**
  45480. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45481. * @param effect The effect to update
  45482. * @param lightIndex The index of the light in the effect to update
  45483. * @returns The point light
  45484. */
  45485. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45486. if (this.computeTransformedInformation()) {
  45487. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45488. return this;
  45489. }
  45490. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45491. return this;
  45492. };
  45493. __decorate([
  45494. BABYLON.serialize()
  45495. ], PointLight.prototype, "shadowAngle", null);
  45496. return PointLight;
  45497. }(BABYLON.ShadowLight));
  45498. BABYLON.PointLight = PointLight;
  45499. })(BABYLON || (BABYLON = {}));
  45500. //# sourceMappingURL=babylon.pointLight.js.map
  45501. var BABYLON;
  45502. (function (BABYLON) {
  45503. /**
  45504. * A directional light is defined by a direction (what a surprise!).
  45505. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45506. * 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.
  45507. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45508. */
  45509. var DirectionalLight = /** @class */ (function (_super) {
  45510. __extends(DirectionalLight, _super);
  45511. /**
  45512. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45513. * The directional light is emitted from everywhere in the given direction.
  45514. * It can cast shawdows.
  45515. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45516. * @param name The friendly name of the light
  45517. * @param direction The direction of the light
  45518. * @param scene The scene the light belongs to
  45519. */
  45520. function DirectionalLight(name, direction, scene) {
  45521. var _this = _super.call(this, name, scene) || this;
  45522. _this._shadowFrustumSize = 0;
  45523. _this._shadowOrthoScale = 0.5;
  45524. /**
  45525. * Automatically compute the projection matrix to best fit (including all the casters)
  45526. * on each frame.
  45527. */
  45528. _this.autoUpdateExtends = true;
  45529. // Cache
  45530. _this._orthoLeft = Number.MAX_VALUE;
  45531. _this._orthoRight = Number.MIN_VALUE;
  45532. _this._orthoTop = Number.MIN_VALUE;
  45533. _this._orthoBottom = Number.MAX_VALUE;
  45534. _this.position = direction.scale(-1.0);
  45535. _this.direction = direction;
  45536. return _this;
  45537. }
  45538. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45539. /**
  45540. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45541. */
  45542. get: function () {
  45543. return this._shadowFrustumSize;
  45544. },
  45545. /**
  45546. * Specifies a fix frustum size for the shadow generation.
  45547. */
  45548. set: function (value) {
  45549. this._shadowFrustumSize = value;
  45550. this.forceProjectionMatrixCompute();
  45551. },
  45552. enumerable: true,
  45553. configurable: true
  45554. });
  45555. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45556. /**
  45557. * Gets the shadow projection scale against the optimal computed one.
  45558. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45559. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45560. */
  45561. get: function () {
  45562. return this._shadowOrthoScale;
  45563. },
  45564. /**
  45565. * Sets the shadow projection scale against the optimal computed one.
  45566. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45567. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45568. */
  45569. set: function (value) {
  45570. this._shadowOrthoScale = value;
  45571. this.forceProjectionMatrixCompute();
  45572. },
  45573. enumerable: true,
  45574. configurable: true
  45575. });
  45576. /**
  45577. * Returns the string "DirectionalLight".
  45578. * @return The class name
  45579. */
  45580. DirectionalLight.prototype.getClassName = function () {
  45581. return "DirectionalLight";
  45582. };
  45583. /**
  45584. * Returns the integer 1.
  45585. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45586. */
  45587. DirectionalLight.prototype.getTypeID = function () {
  45588. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45589. };
  45590. /**
  45591. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45592. * Returns the DirectionalLight Shadow projection matrix.
  45593. */
  45594. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45595. if (this.shadowFrustumSize > 0) {
  45596. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45597. }
  45598. else {
  45599. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45600. }
  45601. };
  45602. /**
  45603. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45604. * Returns the DirectionalLight Shadow projection matrix.
  45605. */
  45606. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45607. var activeCamera = this.getScene().activeCamera;
  45608. if (!activeCamera) {
  45609. return;
  45610. }
  45611. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45612. };
  45613. /**
  45614. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45615. * Returns the DirectionalLight Shadow projection matrix.
  45616. */
  45617. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45618. var activeCamera = this.getScene().activeCamera;
  45619. if (!activeCamera) {
  45620. return;
  45621. }
  45622. // Check extends
  45623. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45624. var tempVector3 = BABYLON.Vector3.Zero();
  45625. this._orthoLeft = Number.MAX_VALUE;
  45626. this._orthoRight = Number.MIN_VALUE;
  45627. this._orthoTop = Number.MIN_VALUE;
  45628. this._orthoBottom = Number.MAX_VALUE;
  45629. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45630. var mesh = renderList[meshIndex];
  45631. if (!mesh) {
  45632. continue;
  45633. }
  45634. var boundingInfo = mesh.getBoundingInfo();
  45635. var boundingBox = boundingInfo.boundingBox;
  45636. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45637. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45638. if (tempVector3.x < this._orthoLeft)
  45639. this._orthoLeft = tempVector3.x;
  45640. if (tempVector3.y < this._orthoBottom)
  45641. this._orthoBottom = tempVector3.y;
  45642. if (tempVector3.x > this._orthoRight)
  45643. this._orthoRight = tempVector3.x;
  45644. if (tempVector3.y > this._orthoTop)
  45645. this._orthoTop = tempVector3.y;
  45646. }
  45647. }
  45648. }
  45649. var xOffset = this._orthoRight - this._orthoLeft;
  45650. var yOffset = this._orthoTop - this._orthoBottom;
  45651. 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);
  45652. };
  45653. DirectionalLight.prototype._buildUniformLayout = function () {
  45654. this._uniformBuffer.addUniform("vLightData", 4);
  45655. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45656. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45657. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45658. this._uniformBuffer.addUniform("depthValues", 2);
  45659. this._uniformBuffer.create();
  45660. };
  45661. /**
  45662. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45663. * @param effect The effect to update
  45664. * @param lightIndex The index of the light in the effect to update
  45665. * @returns The directional light
  45666. */
  45667. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45668. if (this.computeTransformedInformation()) {
  45669. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45670. return this;
  45671. }
  45672. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45673. return this;
  45674. };
  45675. /**
  45676. * Gets the minZ used for shadow according to both the scene and the light.
  45677. *
  45678. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45679. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45680. * @param activeCamera The camera we are returning the min for
  45681. * @returns the depth min z
  45682. */
  45683. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45684. return 1;
  45685. };
  45686. /**
  45687. * Gets the maxZ used for shadow according to both the scene and the light.
  45688. *
  45689. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45690. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45691. * @param activeCamera The camera we are returning the max for
  45692. * @returns the depth max z
  45693. */
  45694. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45695. return 1;
  45696. };
  45697. __decorate([
  45698. BABYLON.serialize()
  45699. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45700. __decorate([
  45701. BABYLON.serialize()
  45702. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45703. __decorate([
  45704. BABYLON.serialize()
  45705. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45706. return DirectionalLight;
  45707. }(BABYLON.ShadowLight));
  45708. BABYLON.DirectionalLight = DirectionalLight;
  45709. })(BABYLON || (BABYLON = {}));
  45710. //# sourceMappingURL=babylon.directionalLight.js.map
  45711. var BABYLON;
  45712. (function (BABYLON) {
  45713. /**
  45714. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45715. * These values define a cone of light starting from the position, emitting toward the direction.
  45716. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45717. * and the exponent defines the speed of the decay of the light with distance (reach).
  45718. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45719. */
  45720. var SpotLight = /** @class */ (function (_super) {
  45721. __extends(SpotLight, _super);
  45722. /**
  45723. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45724. * It can cast shadows.
  45725. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45726. * @param name The light friendly name
  45727. * @param position The position of the spot light in the scene
  45728. * @param direction The direction of the light in the scene
  45729. * @param angle The cone angle of the light in Radians
  45730. * @param exponent The light decay speed with the distance from the emission spot
  45731. * @param scene The scene the lights belongs to
  45732. */
  45733. function SpotLight(name, position, direction, angle, exponent, scene) {
  45734. var _this = _super.call(this, name, scene) || this;
  45735. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45736. _this._projectionTextureLightNear = 1e-6;
  45737. _this._projectionTextureLightFar = 1000.0;
  45738. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45739. _this._projectionTextureViewLightDirty = true;
  45740. _this._projectionTextureProjectionLightDirty = true;
  45741. _this._projectionTextureDirty = true;
  45742. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45743. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45744. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45745. _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);
  45746. _this.position = position;
  45747. _this.direction = direction;
  45748. _this.angle = angle;
  45749. _this.exponent = exponent;
  45750. return _this;
  45751. }
  45752. Object.defineProperty(SpotLight.prototype, "angle", {
  45753. /**
  45754. * Gets the cone angle of the spot light in Radians.
  45755. */
  45756. get: function () {
  45757. return this._angle;
  45758. },
  45759. /**
  45760. * Sets the cone angle of the spot light in Radians.
  45761. */
  45762. set: function (value) {
  45763. this._angle = value;
  45764. this._projectionTextureProjectionLightDirty = true;
  45765. this.forceProjectionMatrixCompute();
  45766. },
  45767. enumerable: true,
  45768. configurable: true
  45769. });
  45770. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45771. /**
  45772. * Allows scaling the angle of the light for shadow generation only.
  45773. */
  45774. get: function () {
  45775. return this._shadowAngleScale;
  45776. },
  45777. /**
  45778. * Allows scaling the angle of the light for shadow generation only.
  45779. */
  45780. set: function (value) {
  45781. this._shadowAngleScale = value;
  45782. this.forceProjectionMatrixCompute();
  45783. },
  45784. enumerable: true,
  45785. configurable: true
  45786. });
  45787. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45788. /**
  45789. * Allows reading the projecton texture
  45790. */
  45791. get: function () {
  45792. return this._projectionTextureMatrix;
  45793. },
  45794. enumerable: true,
  45795. configurable: true
  45796. });
  45797. ;
  45798. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45799. /**
  45800. * Gets the near clip of the Spotlight for texture projection.
  45801. */
  45802. get: function () {
  45803. return this._projectionTextureLightNear;
  45804. },
  45805. /**
  45806. * Sets the near clip of the Spotlight for texture projection.
  45807. */
  45808. set: function (value) {
  45809. this._projectionTextureLightNear = value;
  45810. this._projectionTextureProjectionLightDirty = true;
  45811. },
  45812. enumerable: true,
  45813. configurable: true
  45814. });
  45815. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45816. /**
  45817. * Gets the far clip of the Spotlight for texture projection.
  45818. */
  45819. get: function () {
  45820. return this._projectionTextureLightFar;
  45821. },
  45822. /**
  45823. * Sets the far clip of the Spotlight for texture projection.
  45824. */
  45825. set: function (value) {
  45826. this._projectionTextureLightFar = value;
  45827. this._projectionTextureProjectionLightDirty = true;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45833. /**
  45834. * Gets the Up vector of the Spotlight for texture projection.
  45835. */
  45836. get: function () {
  45837. return this._projectionTextureUpDirection;
  45838. },
  45839. /**
  45840. * Sets the Up vector of the Spotlight for texture projection.
  45841. */
  45842. set: function (value) {
  45843. this._projectionTextureUpDirection = value;
  45844. this._projectionTextureProjectionLightDirty = true;
  45845. },
  45846. enumerable: true,
  45847. configurable: true
  45848. });
  45849. ;
  45850. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45851. /**
  45852. * Gets the projection texture of the light.
  45853. */
  45854. get: function () {
  45855. return this._projectionTexture;
  45856. },
  45857. /**
  45858. * Sets the projection texture of the light.
  45859. */
  45860. set: function (value) {
  45861. this._projectionTexture = value;
  45862. this._projectionTextureDirty = true;
  45863. },
  45864. enumerable: true,
  45865. configurable: true
  45866. });
  45867. /**
  45868. * Returns the string "SpotLight".
  45869. * @returns the class name
  45870. */
  45871. SpotLight.prototype.getClassName = function () {
  45872. return "SpotLight";
  45873. };
  45874. /**
  45875. * Returns the integer 2.
  45876. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45877. */
  45878. SpotLight.prototype.getTypeID = function () {
  45879. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45880. };
  45881. /**
  45882. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45883. */
  45884. SpotLight.prototype._setDirection = function (value) {
  45885. _super.prototype._setDirection.call(this, value);
  45886. this._projectionTextureViewLightDirty = true;
  45887. };
  45888. /**
  45889. * Overrides the position setter to recompute the projection texture view light Matrix.
  45890. */
  45891. SpotLight.prototype._setPosition = function (value) {
  45892. _super.prototype._setPosition.call(this, value);
  45893. this._projectionTextureViewLightDirty = true;
  45894. };
  45895. /**
  45896. * 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.
  45897. * Returns the SpotLight.
  45898. */
  45899. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45900. var activeCamera = this.getScene().activeCamera;
  45901. if (!activeCamera) {
  45902. return;
  45903. }
  45904. this._shadowAngleScale = this._shadowAngleScale || 1;
  45905. var angle = this._shadowAngleScale * this._angle;
  45906. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45907. };
  45908. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45909. this._projectionTextureViewLightDirty = false;
  45910. this._projectionTextureDirty = true;
  45911. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45912. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45913. };
  45914. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45915. this._projectionTextureProjectionLightDirty = false;
  45916. this._projectionTextureDirty = true;
  45917. var light_far = this.projectionTextureLightFar;
  45918. var light_near = this.projectionTextureLightNear;
  45919. var P = light_far / (light_far - light_near);
  45920. var Q = -P * light_near;
  45921. var S = 1.0 / Math.tan(this._angle / 2.0);
  45922. var A = 1.0;
  45923. 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);
  45924. };
  45925. /**
  45926. * Main function for light texture projection matrix computing.
  45927. */
  45928. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45929. this._projectionTextureDirty = false;
  45930. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45931. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45932. };
  45933. SpotLight.prototype._buildUniformLayout = function () {
  45934. this._uniformBuffer.addUniform("vLightData", 4);
  45935. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45936. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45937. this._uniformBuffer.addUniform("vLightDirection", 3);
  45938. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45939. this._uniformBuffer.addUniform("depthValues", 2);
  45940. this._uniformBuffer.create();
  45941. };
  45942. /**
  45943. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45944. * @param effect The effect to update
  45945. * @param lightIndex The index of the light in the effect to update
  45946. * @returns The spot light
  45947. */
  45948. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45949. var normalizeDirection;
  45950. if (this.computeTransformedInformation()) {
  45951. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45952. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45953. }
  45954. else {
  45955. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45956. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45957. }
  45958. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45959. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45960. if (this._projectionTextureViewLightDirty) {
  45961. this._computeProjectionTextureViewLightMatrix();
  45962. }
  45963. if (this._projectionTextureProjectionLightDirty) {
  45964. this._computeProjectionTextureProjectionLightMatrix();
  45965. }
  45966. if (this._projectionTextureDirty) {
  45967. this._computeProjectionTextureMatrix();
  45968. }
  45969. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45970. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45971. }
  45972. return this;
  45973. };
  45974. /**
  45975. * Disposes the light and the associated resources.
  45976. */
  45977. SpotLight.prototype.dispose = function () {
  45978. _super.prototype.dispose.call(this);
  45979. if (this._projectionTexture) {
  45980. this._projectionTexture.dispose();
  45981. }
  45982. };
  45983. __decorate([
  45984. BABYLON.serialize()
  45985. ], SpotLight.prototype, "angle", null);
  45986. __decorate([
  45987. BABYLON.serialize()
  45988. ], SpotLight.prototype, "shadowAngleScale", null);
  45989. __decorate([
  45990. BABYLON.serialize()
  45991. ], SpotLight.prototype, "exponent", void 0);
  45992. __decorate([
  45993. BABYLON.serialize()
  45994. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45995. __decorate([
  45996. BABYLON.serialize()
  45997. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45998. __decorate([
  45999. BABYLON.serialize()
  46000. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46001. __decorate([
  46002. BABYLON.serializeAsTexture("projectedLightTexture")
  46003. ], SpotLight.prototype, "_projectionTexture", void 0);
  46004. return SpotLight;
  46005. }(BABYLON.ShadowLight));
  46006. BABYLON.SpotLight = SpotLight;
  46007. })(BABYLON || (BABYLON = {}));
  46008. //# sourceMappingURL=babylon.spotLight.js.map
  46009. var BABYLON;
  46010. (function (BABYLON) {
  46011. /**
  46012. * Class used to override all child animations of a given target
  46013. */
  46014. var AnimationPropertiesOverride = /** @class */ (function () {
  46015. function AnimationPropertiesOverride() {
  46016. /**
  46017. * Gets or sets a value indicating if animation blending must be used
  46018. */
  46019. this.enableBlending = false;
  46020. /**
  46021. * Gets or sets the blending speed to use when enableBlending is true
  46022. */
  46023. this.blendingSpeed = 0.01;
  46024. /**
  46025. * Gets or sets the default loop mode to use
  46026. */
  46027. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46028. }
  46029. return AnimationPropertiesOverride;
  46030. }());
  46031. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46032. })(BABYLON || (BABYLON = {}));
  46033. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46034. var BABYLON;
  46035. (function (BABYLON) {
  46036. var AnimationRange = /** @class */ (function () {
  46037. function AnimationRange(name, from, to) {
  46038. this.name = name;
  46039. this.from = from;
  46040. this.to = to;
  46041. }
  46042. AnimationRange.prototype.clone = function () {
  46043. return new AnimationRange(this.name, this.from, this.to);
  46044. };
  46045. return AnimationRange;
  46046. }());
  46047. BABYLON.AnimationRange = AnimationRange;
  46048. /**
  46049. * Composed of a frame, and an action function
  46050. */
  46051. var AnimationEvent = /** @class */ (function () {
  46052. function AnimationEvent(frame, action, onlyOnce) {
  46053. this.frame = frame;
  46054. this.action = action;
  46055. this.onlyOnce = onlyOnce;
  46056. this.isDone = false;
  46057. }
  46058. return AnimationEvent;
  46059. }());
  46060. BABYLON.AnimationEvent = AnimationEvent;
  46061. var PathCursor = /** @class */ (function () {
  46062. function PathCursor(path) {
  46063. this.path = path;
  46064. this._onchange = new Array();
  46065. this.value = 0;
  46066. this.animations = new Array();
  46067. }
  46068. PathCursor.prototype.getPoint = function () {
  46069. var point = this.path.getPointAtLengthPosition(this.value);
  46070. return new BABYLON.Vector3(point.x, 0, point.y);
  46071. };
  46072. PathCursor.prototype.moveAhead = function (step) {
  46073. if (step === void 0) { step = 0.002; }
  46074. this.move(step);
  46075. return this;
  46076. };
  46077. PathCursor.prototype.moveBack = function (step) {
  46078. if (step === void 0) { step = 0.002; }
  46079. this.move(-step);
  46080. return this;
  46081. };
  46082. PathCursor.prototype.move = function (step) {
  46083. if (Math.abs(step) > 1) {
  46084. throw "step size should be less than 1.";
  46085. }
  46086. this.value += step;
  46087. this.ensureLimits();
  46088. this.raiseOnChange();
  46089. return this;
  46090. };
  46091. PathCursor.prototype.ensureLimits = function () {
  46092. while (this.value > 1) {
  46093. this.value -= 1;
  46094. }
  46095. while (this.value < 0) {
  46096. this.value += 1;
  46097. }
  46098. return this;
  46099. };
  46100. // used by animation engine
  46101. PathCursor.prototype.raiseOnChange = function () {
  46102. var _this = this;
  46103. this._onchange.forEach(function (f) { return f(_this); });
  46104. return this;
  46105. };
  46106. PathCursor.prototype.onchange = function (f) {
  46107. this._onchange.push(f);
  46108. return this;
  46109. };
  46110. return PathCursor;
  46111. }());
  46112. BABYLON.PathCursor = PathCursor;
  46113. var AnimationKeyInterpolation;
  46114. (function (AnimationKeyInterpolation) {
  46115. /**
  46116. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46117. */
  46118. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46119. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46120. var Animation = /** @class */ (function () {
  46121. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46122. this.name = name;
  46123. this.targetProperty = targetProperty;
  46124. this.framePerSecond = framePerSecond;
  46125. this.dataType = dataType;
  46126. this.loopMode = loopMode;
  46127. this.enableBlending = enableBlending;
  46128. this._runtimeAnimations = new Array();
  46129. // The set of event that will be linked to this animation
  46130. this._events = new Array();
  46131. this.blendingSpeed = 0.01;
  46132. this._ranges = {};
  46133. this.targetPropertyPath = targetProperty.split(".");
  46134. this.dataType = dataType;
  46135. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46136. }
  46137. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46138. var dataType = undefined;
  46139. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46140. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46141. }
  46142. else if (from instanceof BABYLON.Quaternion) {
  46143. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46144. }
  46145. else if (from instanceof BABYLON.Vector3) {
  46146. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46147. }
  46148. else if (from instanceof BABYLON.Vector2) {
  46149. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46150. }
  46151. else if (from instanceof BABYLON.Color3) {
  46152. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46153. }
  46154. else if (from instanceof BABYLON.Size) {
  46155. dataType = Animation.ANIMATIONTYPE_SIZE;
  46156. }
  46157. if (dataType == undefined) {
  46158. return null;
  46159. }
  46160. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46161. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46162. animation.setKeys(keys);
  46163. if (easingFunction !== undefined) {
  46164. animation.setEasingFunction(easingFunction);
  46165. }
  46166. return animation;
  46167. };
  46168. /**
  46169. * Sets up an animation.
  46170. * @param property the property to animate
  46171. * @param animationType the animation type to apply
  46172. * @param easingFunction the easing function used in the animation
  46173. * @returns The created animation
  46174. */
  46175. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46176. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46177. animation.setEasingFunction(easingFunction);
  46178. return animation;
  46179. };
  46180. /**
  46181. * Create and start an animation on a node
  46182. * @param {string} name defines the name of the global animation that will be run on all nodes
  46183. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46184. * @param {string} targetProperty defines property to animate
  46185. * @param {number} framePerSecond defines the number of frame per second yo use
  46186. * @param {number} totalFrame defines the number of frames in total
  46187. * @param {any} from defines the initial value
  46188. * @param {any} to defines the final value
  46189. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46190. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46191. * @param onAnimationEnd defines the callback to call when animation end
  46192. * @returns the animatable created for this animation
  46193. */
  46194. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46195. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46196. if (!animation) {
  46197. return null;
  46198. }
  46199. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46200. };
  46201. /**
  46202. * Create and start an animation on a node and its descendants
  46203. * @param {string} name defines the name of the global animation that will be run on all nodes
  46204. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46205. * @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.
  46206. * @param {string} targetProperty defines property to animate
  46207. * @param {number} framePerSecond defines the number of frame per second yo use
  46208. * @param {number} totalFrame defines the number of frames in total
  46209. * @param {any} from defines the initial value
  46210. * @param {any} to defines the final value
  46211. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46212. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46213. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46214. * @returns the list of animatables created for all nodes
  46215. * @example https://www.babylonjs-playground.com/#MH0VLI
  46216. */
  46217. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46218. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46219. if (!animation) {
  46220. return null;
  46221. }
  46222. var scene = node.getScene();
  46223. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46224. };
  46225. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46226. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46227. if (!animation) {
  46228. return null;
  46229. }
  46230. node.animations.push(animation);
  46231. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46232. };
  46233. /**
  46234. * Transition property of the Camera to the target Value.
  46235. * @param property The property to transition
  46236. * @param targetValue The target Value of the property
  46237. * @param host The object where the property to animate belongs
  46238. * @param scene Scene used to run the animation
  46239. * @param frameRate Framerate (in frame/s) to use
  46240. * @param transition The transition type we want to use
  46241. * @param duration The duration of the animation, in milliseconds
  46242. * @param onAnimationEnd Call back trigger at the end of the animation.
  46243. */
  46244. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46245. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46246. if (duration <= 0) {
  46247. host[property] = targetValue;
  46248. if (onAnimationEnd) {
  46249. onAnimationEnd();
  46250. }
  46251. return null;
  46252. }
  46253. var endFrame = frameRate * (duration / 1000);
  46254. transition.setKeys([{
  46255. frame: 0,
  46256. value: host[property].clone ? host[property].clone() : host[property]
  46257. },
  46258. {
  46259. frame: endFrame,
  46260. value: targetValue
  46261. }]);
  46262. if (!host.animations) {
  46263. host.animations = [];
  46264. }
  46265. host.animations.push(transition);
  46266. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46267. animation.onAnimationEnd = onAnimationEnd;
  46268. return animation;
  46269. };
  46270. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46271. /**
  46272. * Return the array of runtime animations currently using this animation
  46273. */
  46274. get: function () {
  46275. return this._runtimeAnimations;
  46276. },
  46277. enumerable: true,
  46278. configurable: true
  46279. });
  46280. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46281. get: function () {
  46282. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46283. var runtimeAnimation = _a[_i];
  46284. if (!runtimeAnimation.isStopped) {
  46285. return true;
  46286. }
  46287. }
  46288. return false;
  46289. },
  46290. enumerable: true,
  46291. configurable: true
  46292. });
  46293. // Methods
  46294. /**
  46295. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46296. */
  46297. Animation.prototype.toString = function (fullDetails) {
  46298. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46299. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46300. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46301. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46302. if (fullDetails) {
  46303. ret += ", Ranges: {";
  46304. var first = true;
  46305. for (var name in this._ranges) {
  46306. if (first) {
  46307. ret += ", ";
  46308. first = false;
  46309. }
  46310. ret += name;
  46311. }
  46312. ret += "}";
  46313. }
  46314. return ret;
  46315. };
  46316. /**
  46317. * Add an event to this animation.
  46318. */
  46319. Animation.prototype.addEvent = function (event) {
  46320. this._events.push(event);
  46321. };
  46322. /**
  46323. * Remove all events found at the given frame
  46324. * @param frame
  46325. */
  46326. Animation.prototype.removeEvents = function (frame) {
  46327. for (var index = 0; index < this._events.length; index++) {
  46328. if (this._events[index].frame === frame) {
  46329. this._events.splice(index, 1);
  46330. index--;
  46331. }
  46332. }
  46333. };
  46334. Animation.prototype.getEvents = function () {
  46335. return this._events;
  46336. };
  46337. Animation.prototype.createRange = function (name, from, to) {
  46338. // check name not already in use; could happen for bones after serialized
  46339. if (!this._ranges[name]) {
  46340. this._ranges[name] = new AnimationRange(name, from, to);
  46341. }
  46342. };
  46343. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46344. if (deleteFrames === void 0) { deleteFrames = true; }
  46345. var range = this._ranges[name];
  46346. if (!range) {
  46347. return;
  46348. }
  46349. if (deleteFrames) {
  46350. var from = range.from;
  46351. var to = range.to;
  46352. // this loop MUST go high to low for multiple splices to work
  46353. for (var key = this._keys.length - 1; key >= 0; key--) {
  46354. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46355. this._keys.splice(key, 1);
  46356. }
  46357. }
  46358. }
  46359. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46360. };
  46361. Animation.prototype.getRange = function (name) {
  46362. return this._ranges[name];
  46363. };
  46364. Animation.prototype.getKeys = function () {
  46365. return this._keys;
  46366. };
  46367. Animation.prototype.getHighestFrame = function () {
  46368. var ret = 0;
  46369. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46370. if (ret < this._keys[key].frame) {
  46371. ret = this._keys[key].frame;
  46372. }
  46373. }
  46374. return ret;
  46375. };
  46376. Animation.prototype.getEasingFunction = function () {
  46377. return this._easingFunction;
  46378. };
  46379. Animation.prototype.setEasingFunction = function (easingFunction) {
  46380. this._easingFunction = easingFunction;
  46381. };
  46382. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46383. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46384. };
  46385. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46386. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46387. };
  46388. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46389. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46390. };
  46391. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46392. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46393. };
  46394. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46395. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46396. };
  46397. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46398. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46399. };
  46400. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46401. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46402. };
  46403. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46404. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46405. };
  46406. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46407. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46408. };
  46409. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46410. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46411. };
  46412. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46413. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46414. };
  46415. Animation.prototype.clone = function () {
  46416. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46417. clone.enableBlending = this.enableBlending;
  46418. clone.blendingSpeed = this.blendingSpeed;
  46419. if (this._keys) {
  46420. clone.setKeys(this._keys);
  46421. }
  46422. if (this._ranges) {
  46423. clone._ranges = {};
  46424. for (var name in this._ranges) {
  46425. var range = this._ranges[name];
  46426. if (!range) {
  46427. continue;
  46428. }
  46429. clone._ranges[name] = range.clone();
  46430. }
  46431. }
  46432. return clone;
  46433. };
  46434. Animation.prototype.setKeys = function (values) {
  46435. this._keys = values.slice(0);
  46436. };
  46437. Animation.prototype.serialize = function () {
  46438. var serializationObject = {};
  46439. serializationObject.name = this.name;
  46440. serializationObject.property = this.targetProperty;
  46441. serializationObject.framePerSecond = this.framePerSecond;
  46442. serializationObject.dataType = this.dataType;
  46443. serializationObject.loopBehavior = this.loopMode;
  46444. serializationObject.enableBlending = this.enableBlending;
  46445. serializationObject.blendingSpeed = this.blendingSpeed;
  46446. var dataType = this.dataType;
  46447. serializationObject.keys = [];
  46448. var keys = this.getKeys();
  46449. for (var index = 0; index < keys.length; index++) {
  46450. var animationKey = keys[index];
  46451. var key = {};
  46452. key.frame = animationKey.frame;
  46453. switch (dataType) {
  46454. case Animation.ANIMATIONTYPE_FLOAT:
  46455. key.values = [animationKey.value];
  46456. break;
  46457. case Animation.ANIMATIONTYPE_QUATERNION:
  46458. case Animation.ANIMATIONTYPE_MATRIX:
  46459. case Animation.ANIMATIONTYPE_VECTOR3:
  46460. case Animation.ANIMATIONTYPE_COLOR3:
  46461. key.values = animationKey.value.asArray();
  46462. break;
  46463. }
  46464. serializationObject.keys.push(key);
  46465. }
  46466. serializationObject.ranges = [];
  46467. for (var name in this._ranges) {
  46468. var source = this._ranges[name];
  46469. if (!source) {
  46470. continue;
  46471. }
  46472. var range = {};
  46473. range.name = name;
  46474. range.from = source.from;
  46475. range.to = source.to;
  46476. serializationObject.ranges.push(range);
  46477. }
  46478. return serializationObject;
  46479. };
  46480. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46481. get: function () {
  46482. return Animation._ANIMATIONTYPE_FLOAT;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46488. get: function () {
  46489. return Animation._ANIMATIONTYPE_VECTOR3;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46495. get: function () {
  46496. return Animation._ANIMATIONTYPE_VECTOR2;
  46497. },
  46498. enumerable: true,
  46499. configurable: true
  46500. });
  46501. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46502. get: function () {
  46503. return Animation._ANIMATIONTYPE_SIZE;
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46509. get: function () {
  46510. return Animation._ANIMATIONTYPE_QUATERNION;
  46511. },
  46512. enumerable: true,
  46513. configurable: true
  46514. });
  46515. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46516. get: function () {
  46517. return Animation._ANIMATIONTYPE_MATRIX;
  46518. },
  46519. enumerable: true,
  46520. configurable: true
  46521. });
  46522. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46523. get: function () {
  46524. return Animation._ANIMATIONTYPE_COLOR3;
  46525. },
  46526. enumerable: true,
  46527. configurable: true
  46528. });
  46529. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46530. get: function () {
  46531. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46532. },
  46533. enumerable: true,
  46534. configurable: true
  46535. });
  46536. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46537. get: function () {
  46538. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46539. },
  46540. enumerable: true,
  46541. configurable: true
  46542. });
  46543. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46544. get: function () {
  46545. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46546. },
  46547. enumerable: true,
  46548. configurable: true
  46549. });
  46550. Animation.Parse = function (parsedAnimation) {
  46551. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46552. var dataType = parsedAnimation.dataType;
  46553. var keys = [];
  46554. var data;
  46555. var index;
  46556. if (parsedAnimation.enableBlending) {
  46557. animation.enableBlending = parsedAnimation.enableBlending;
  46558. }
  46559. if (parsedAnimation.blendingSpeed) {
  46560. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46561. }
  46562. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46563. var key = parsedAnimation.keys[index];
  46564. var inTangent;
  46565. var outTangent;
  46566. switch (dataType) {
  46567. case Animation.ANIMATIONTYPE_FLOAT:
  46568. data = key.values[0];
  46569. if (key.values.length >= 1) {
  46570. inTangent = key.values[1];
  46571. }
  46572. if (key.values.length >= 2) {
  46573. outTangent = key.values[2];
  46574. }
  46575. break;
  46576. case Animation.ANIMATIONTYPE_QUATERNION:
  46577. data = BABYLON.Quaternion.FromArray(key.values);
  46578. if (key.values.length >= 8) {
  46579. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46580. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46581. inTangent = _inTangent;
  46582. }
  46583. }
  46584. if (key.values.length >= 12) {
  46585. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46586. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46587. outTangent = _outTangent;
  46588. }
  46589. }
  46590. break;
  46591. case Animation.ANIMATIONTYPE_MATRIX:
  46592. data = BABYLON.Matrix.FromArray(key.values);
  46593. break;
  46594. case Animation.ANIMATIONTYPE_COLOR3:
  46595. data = BABYLON.Color3.FromArray(key.values);
  46596. break;
  46597. case Animation.ANIMATIONTYPE_VECTOR3:
  46598. default:
  46599. data = BABYLON.Vector3.FromArray(key.values);
  46600. break;
  46601. }
  46602. var keyData = {};
  46603. keyData.frame = key.frame;
  46604. keyData.value = data;
  46605. if (inTangent != undefined) {
  46606. keyData.inTangent = inTangent;
  46607. }
  46608. if (outTangent != undefined) {
  46609. keyData.outTangent = outTangent;
  46610. }
  46611. keys.push(keyData);
  46612. }
  46613. animation.setKeys(keys);
  46614. if (parsedAnimation.ranges) {
  46615. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46616. data = parsedAnimation.ranges[index];
  46617. animation.createRange(data.name, data.from, data.to);
  46618. }
  46619. }
  46620. return animation;
  46621. };
  46622. Animation.AppendSerializedAnimations = function (source, destination) {
  46623. if (source.animations) {
  46624. destination.animations = [];
  46625. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46626. var animation = source.animations[animationIndex];
  46627. destination.animations.push(animation.serialize());
  46628. }
  46629. }
  46630. };
  46631. Animation.AllowMatricesInterpolation = false;
  46632. // Statics
  46633. Animation._ANIMATIONTYPE_FLOAT = 0;
  46634. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46635. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46636. Animation._ANIMATIONTYPE_MATRIX = 3;
  46637. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46638. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46639. Animation._ANIMATIONTYPE_SIZE = 6;
  46640. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46641. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46642. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46643. return Animation;
  46644. }());
  46645. BABYLON.Animation = Animation;
  46646. })(BABYLON || (BABYLON = {}));
  46647. //# sourceMappingURL=babylon.animation.js.map
  46648. var BABYLON;
  46649. (function (BABYLON) {
  46650. /**
  46651. * This class defines the direct association between an animation and a target
  46652. */
  46653. var TargetedAnimation = /** @class */ (function () {
  46654. function TargetedAnimation() {
  46655. }
  46656. return TargetedAnimation;
  46657. }());
  46658. BABYLON.TargetedAnimation = TargetedAnimation;
  46659. /**
  46660. * Use this class to create coordinated animations on multiple targets
  46661. */
  46662. var AnimationGroup = /** @class */ (function () {
  46663. function AnimationGroup(name, scene) {
  46664. if (scene === void 0) { scene = null; }
  46665. this.name = name;
  46666. this._targetedAnimations = new Array();
  46667. this._animatables = new Array();
  46668. this._from = Number.MAX_VALUE;
  46669. this._to = -Number.MAX_VALUE;
  46670. this._speedRatio = 1;
  46671. this.onAnimationEndObservable = new BABYLON.Observable();
  46672. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46673. this._scene.animationGroups.push(this);
  46674. }
  46675. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46676. /**
  46677. * Define if the animations are started
  46678. */
  46679. get: function () {
  46680. return this._isStarted;
  46681. },
  46682. enumerable: true,
  46683. configurable: true
  46684. });
  46685. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46686. /**
  46687. * Gets or sets the speed ratio to use for all animations
  46688. */
  46689. get: function () {
  46690. return this._speedRatio;
  46691. },
  46692. /**
  46693. * Gets or sets the speed ratio to use for all animations
  46694. */
  46695. set: function (value) {
  46696. if (this._speedRatio === value) {
  46697. return;
  46698. }
  46699. this._speedRatio = value;
  46700. for (var index = 0; index < this._animatables.length; index++) {
  46701. var animatable = this._animatables[index];
  46702. animatable.speedRatio = this._speedRatio;
  46703. }
  46704. },
  46705. enumerable: true,
  46706. configurable: true
  46707. });
  46708. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46709. /**
  46710. * Gets the targeted animations for this animation group
  46711. */
  46712. get: function () {
  46713. return this._targetedAnimations;
  46714. },
  46715. enumerable: true,
  46716. configurable: true
  46717. });
  46718. /**
  46719. * Add an animation (with its target) in the group
  46720. * @param animation defines the animation we want to add
  46721. * @param target defines the target of the animation
  46722. * @returns the {BABYLON.TargetedAnimation} object
  46723. */
  46724. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46725. var targetedAnimation = {
  46726. animation: animation,
  46727. target: target
  46728. };
  46729. var keys = animation.getKeys();
  46730. if (this._from > keys[0].frame) {
  46731. this._from = keys[0].frame;
  46732. }
  46733. if (this._to < keys[keys.length - 1].frame) {
  46734. this._to = keys[keys.length - 1].frame;
  46735. }
  46736. this._targetedAnimations.push(targetedAnimation);
  46737. return targetedAnimation;
  46738. };
  46739. /**
  46740. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46741. * It can add constant keys at begin or end
  46742. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46743. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46744. */
  46745. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46746. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46747. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46748. beginFrame = Math.max(beginFrame, this._from);
  46749. endFrame = Math.min(endFrame, this._to);
  46750. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46751. var targetedAnimation = this._targetedAnimations[index];
  46752. var keys = targetedAnimation.animation.getKeys();
  46753. var startKey = keys[0];
  46754. var endKey = keys[keys.length - 1];
  46755. if (startKey.frame > beginFrame) {
  46756. var newKey = {
  46757. frame: beginFrame,
  46758. value: startKey.value,
  46759. inTangent: startKey.inTangent,
  46760. outTangent: startKey.outTangent,
  46761. interpolation: startKey.interpolation
  46762. };
  46763. keys.splice(0, 0, newKey);
  46764. }
  46765. if (endKey.frame < endFrame) {
  46766. var newKey = {
  46767. frame: endFrame,
  46768. value: endKey.value,
  46769. inTangent: endKey.outTangent,
  46770. outTangent: endKey.outTangent,
  46771. interpolation: endKey.interpolation
  46772. };
  46773. keys.push(newKey);
  46774. }
  46775. }
  46776. return this;
  46777. };
  46778. /**
  46779. * Start all animations on given targets
  46780. * @param loop defines if animations must loop
  46781. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46782. */
  46783. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46784. var _this = this;
  46785. if (loop === void 0) { loop = false; }
  46786. if (speedRatio === void 0) { speedRatio = 1; }
  46787. if (this._isStarted || this._targetedAnimations.length === 0) {
  46788. return this;
  46789. }
  46790. var _loop_1 = function () {
  46791. var targetedAnimation = this_1._targetedAnimations[index];
  46792. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46793. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46794. }));
  46795. };
  46796. var this_1 = this;
  46797. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46798. _loop_1();
  46799. }
  46800. this._speedRatio = speedRatio;
  46801. this._isStarted = true;
  46802. return this;
  46803. };
  46804. /**
  46805. * Pause all animations
  46806. */
  46807. AnimationGroup.prototype.pause = function () {
  46808. if (!this._isStarted) {
  46809. return this;
  46810. }
  46811. for (var index = 0; index < this._animatables.length; index++) {
  46812. var animatable = this._animatables[index];
  46813. animatable.pause();
  46814. }
  46815. return this;
  46816. };
  46817. /**
  46818. * Play all animations to initial state
  46819. * This function will start() the animations if they were not started or will restart() them if they were paused
  46820. * @param loop defines if animations must loop
  46821. */
  46822. AnimationGroup.prototype.play = function (loop) {
  46823. if (this.isStarted) {
  46824. if (loop !== undefined) {
  46825. for (var index = 0; index < this._animatables.length; index++) {
  46826. var animatable = this._animatables[index];
  46827. animatable.loopAnimation = loop;
  46828. }
  46829. }
  46830. this.restart();
  46831. }
  46832. else {
  46833. this.start(loop, this._speedRatio);
  46834. }
  46835. return this;
  46836. };
  46837. /**
  46838. * Reset all animations to initial state
  46839. */
  46840. AnimationGroup.prototype.reset = function () {
  46841. if (!this._isStarted) {
  46842. return this;
  46843. }
  46844. for (var index = 0; index < this._animatables.length; index++) {
  46845. var animatable = this._animatables[index];
  46846. animatable.reset();
  46847. }
  46848. return this;
  46849. };
  46850. /**
  46851. * Restart animations from key 0
  46852. */
  46853. AnimationGroup.prototype.restart = function () {
  46854. if (!this._isStarted) {
  46855. return this;
  46856. }
  46857. for (var index = 0; index < this._animatables.length; index++) {
  46858. var animatable = this._animatables[index];
  46859. animatable.restart();
  46860. }
  46861. return this;
  46862. };
  46863. /**
  46864. * Stop all animations
  46865. */
  46866. AnimationGroup.prototype.stop = function () {
  46867. if (!this._isStarted) {
  46868. return this;
  46869. }
  46870. for (var index = 0; index < this._animatables.length; index++) {
  46871. var animatable = this._animatables[index];
  46872. animatable.stop();
  46873. }
  46874. this._isStarted = false;
  46875. return this;
  46876. };
  46877. /**
  46878. * Dispose all associated resources
  46879. */
  46880. AnimationGroup.prototype.dispose = function () {
  46881. this._targetedAnimations = [];
  46882. this._animatables = [];
  46883. var index = this._scene.animationGroups.indexOf(this);
  46884. if (index > -1) {
  46885. this._scene.animationGroups.splice(index, 1);
  46886. }
  46887. };
  46888. return AnimationGroup;
  46889. }());
  46890. BABYLON.AnimationGroup = AnimationGroup;
  46891. })(BABYLON || (BABYLON = {}));
  46892. //# sourceMappingURL=babylon.animationGroup.js.map
  46893. var BABYLON;
  46894. (function (BABYLON) {
  46895. var RuntimeAnimation = /** @class */ (function () {
  46896. function RuntimeAnimation(target, animation) {
  46897. this._offsetsCache = {};
  46898. this._highLimitsCache = {};
  46899. this._stopped = false;
  46900. this._blendingFactor = 0;
  46901. this._ratioOffset = 0;
  46902. this._animation = animation;
  46903. this._target = target;
  46904. animation._runtimeAnimations.push(this);
  46905. }
  46906. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46907. get: function () {
  46908. return this._animation;
  46909. },
  46910. enumerable: true,
  46911. configurable: true
  46912. });
  46913. RuntimeAnimation.prototype.reset = function () {
  46914. this._offsetsCache = {};
  46915. this._highLimitsCache = {};
  46916. this.currentFrame = 0;
  46917. this._blendingFactor = 0;
  46918. this._originalBlendValue = null;
  46919. };
  46920. RuntimeAnimation.prototype.isStopped = function () {
  46921. return this._stopped;
  46922. };
  46923. RuntimeAnimation.prototype.dispose = function () {
  46924. var index = this._animation.runtimeAnimations.indexOf(this);
  46925. if (index > -1) {
  46926. this._animation.runtimeAnimations.splice(index, 1);
  46927. }
  46928. };
  46929. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46930. if (typeof value === "function") {
  46931. return value();
  46932. }
  46933. return value;
  46934. };
  46935. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46936. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46937. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46938. }
  46939. this.currentFrame = currentFrame;
  46940. var keys = this._animation.getKeys();
  46941. // Try to get a hash to find the right key
  46942. 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));
  46943. if (keys[startKeyIndex].frame >= currentFrame) {
  46944. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46945. startKeyIndex--;
  46946. }
  46947. }
  46948. for (var key = startKeyIndex; key < keys.length; key++) {
  46949. var endKey = keys[key + 1];
  46950. if (endKey.frame >= currentFrame) {
  46951. var startKey = keys[key];
  46952. var startValue = this._getKeyValue(startKey.value);
  46953. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46954. return startValue;
  46955. }
  46956. var endValue = this._getKeyValue(endKey.value);
  46957. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46958. var frameDelta = endKey.frame - startKey.frame;
  46959. // gradient : percent of currentFrame between the frame inf and the frame sup
  46960. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46961. // check for easingFunction and correction of gradient
  46962. var easingFunction = this._animation.getEasingFunction();
  46963. if (easingFunction != null) {
  46964. gradient = easingFunction.ease(gradient);
  46965. }
  46966. switch (this._animation.dataType) {
  46967. // Float
  46968. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46969. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46970. switch (loopMode) {
  46971. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46972. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46973. return floatValue;
  46974. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46975. return offsetValue * repeatCount + floatValue;
  46976. }
  46977. break;
  46978. // Quaternion
  46979. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46980. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46981. switch (loopMode) {
  46982. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46983. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46984. return quatValue;
  46985. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46986. return quatValue.add(offsetValue.scale(repeatCount));
  46987. }
  46988. return quatValue;
  46989. // Vector3
  46990. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46991. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46992. switch (loopMode) {
  46993. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46994. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46995. return vec3Value;
  46996. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46997. return vec3Value.add(offsetValue.scale(repeatCount));
  46998. }
  46999. // Vector2
  47000. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47001. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47002. switch (loopMode) {
  47003. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47004. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47005. return vec2Value;
  47006. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47007. return vec2Value.add(offsetValue.scale(repeatCount));
  47008. }
  47009. // Size
  47010. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47011. switch (loopMode) {
  47012. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47013. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47014. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47015. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47016. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47017. }
  47018. // Color3
  47019. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47020. switch (loopMode) {
  47021. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47022. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47023. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47024. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47025. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47026. }
  47027. // Matrix
  47028. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47029. switch (loopMode) {
  47030. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47031. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47032. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47033. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47034. }
  47035. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47036. return startValue;
  47037. }
  47038. default:
  47039. break;
  47040. }
  47041. break;
  47042. }
  47043. }
  47044. return this._getKeyValue(keys[keys.length - 1].value);
  47045. };
  47046. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47047. if (blend === void 0) { blend = false; }
  47048. // Set value
  47049. var path;
  47050. var destination;
  47051. var targetPropertyPath = this._animation.targetPropertyPath;
  47052. if (targetPropertyPath.length > 1) {
  47053. var property = this._target[targetPropertyPath[0]];
  47054. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47055. property = property[targetPropertyPath[index]];
  47056. }
  47057. path = targetPropertyPath[targetPropertyPath.length - 1];
  47058. destination = property;
  47059. }
  47060. else {
  47061. path = targetPropertyPath[0];
  47062. destination = this._target;
  47063. }
  47064. // Blending
  47065. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47066. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47067. if (enableBlending && this._blendingFactor <= 1.0) {
  47068. if (!this._originalBlendValue) {
  47069. if (destination[path].clone) {
  47070. this._originalBlendValue = destination[path].clone();
  47071. }
  47072. else {
  47073. this._originalBlendValue = destination[path];
  47074. }
  47075. }
  47076. if (this._originalBlendValue.prototype) {
  47077. if (this._originalBlendValue.prototype.Lerp) {
  47078. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47079. }
  47080. else {
  47081. destination[path] = currentValue;
  47082. }
  47083. }
  47084. else if (this._originalBlendValue.m) {
  47085. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47086. }
  47087. else {
  47088. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47089. }
  47090. this._blendingFactor += blendingSpeed;
  47091. }
  47092. else {
  47093. destination[path] = currentValue;
  47094. }
  47095. if (this._target.markAsDirty) {
  47096. this._target.markAsDirty(this._animation.targetProperty);
  47097. }
  47098. };
  47099. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47100. if (this._target && this._target.animationPropertiesOverride) {
  47101. return this._target.loopMode;
  47102. }
  47103. return this._animation.loopMode;
  47104. };
  47105. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47106. var keys = this._animation.getKeys();
  47107. if (frame < keys[0].frame) {
  47108. frame = keys[0].frame;
  47109. }
  47110. else if (frame > keys[keys.length - 1].frame) {
  47111. frame = keys[keys.length - 1].frame;
  47112. }
  47113. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47114. this.setValue(currentValue);
  47115. };
  47116. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47117. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47118. this._ratioOffset = this._previousRatio - newRatio;
  47119. };
  47120. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47121. if (blend === void 0) { blend = false; }
  47122. var targetPropertyPath = this._animation.targetPropertyPath;
  47123. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47124. this._stopped = true;
  47125. return false;
  47126. }
  47127. var returnValue = true;
  47128. var keys = this._animation.getKeys();
  47129. // Adding a start key at frame 0 if missing
  47130. if (keys[0].frame !== 0) {
  47131. var newKey = { frame: 0, value: keys[0].value };
  47132. keys.splice(0, 0, newKey);
  47133. }
  47134. // Check limits
  47135. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47136. from = keys[0].frame;
  47137. }
  47138. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47139. to = keys[keys.length - 1].frame;
  47140. }
  47141. //to and from cannot be the same key
  47142. if (from === to) {
  47143. if (from > keys[0].frame) {
  47144. from--;
  47145. }
  47146. else if (to < keys[keys.length - 1].frame) {
  47147. to++;
  47148. }
  47149. }
  47150. // Compute ratio
  47151. var range = to - from;
  47152. var offsetValue;
  47153. // ratio represents the frame delta between from and to
  47154. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47155. var highLimitValue = 0;
  47156. this._previousDelay = delay;
  47157. this._previousRatio = ratio;
  47158. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47159. returnValue = false;
  47160. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47161. }
  47162. else {
  47163. // Get max value if required
  47164. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47165. var keyOffset = to.toString() + from.toString();
  47166. if (!this._offsetsCache[keyOffset]) {
  47167. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47168. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47169. switch (this._animation.dataType) {
  47170. // Float
  47171. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47172. this._offsetsCache[keyOffset] = toValue - fromValue;
  47173. break;
  47174. // Quaternion
  47175. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47176. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47177. break;
  47178. // Vector3
  47179. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47181. // Vector2
  47182. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47183. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47184. // Size
  47185. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47186. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47187. // Color3
  47188. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47189. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47190. default:
  47191. break;
  47192. }
  47193. this._highLimitsCache[keyOffset] = toValue;
  47194. }
  47195. highLimitValue = this._highLimitsCache[keyOffset];
  47196. offsetValue = this._offsetsCache[keyOffset];
  47197. }
  47198. }
  47199. if (offsetValue === undefined) {
  47200. switch (this._animation.dataType) {
  47201. // Float
  47202. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47203. offsetValue = 0;
  47204. break;
  47205. // Quaternion
  47206. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47207. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47208. break;
  47209. // Vector3
  47210. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47211. offsetValue = BABYLON.Vector3.Zero();
  47212. break;
  47213. // Vector2
  47214. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47215. offsetValue = BABYLON.Vector2.Zero();
  47216. break;
  47217. // Size
  47218. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47219. offsetValue = BABYLON.Size.Zero();
  47220. break;
  47221. // Color3
  47222. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47223. offsetValue = BABYLON.Color3.Black();
  47224. }
  47225. }
  47226. // Compute value
  47227. var repeatCount = (ratio / range) >> 0;
  47228. var currentFrame = returnValue ? from + ratio % range : to;
  47229. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47230. // Set value
  47231. this.setValue(currentValue);
  47232. // Check events
  47233. var events = this._animation.getEvents();
  47234. for (var index = 0; index < events.length; index++) {
  47235. // Make sure current frame has passed event frame and that event frame is within the current range
  47236. // Also, handle both forward and reverse animations
  47237. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47238. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47239. var event = events[index];
  47240. if (!event.isDone) {
  47241. // If event should be done only once, remove it.
  47242. if (event.onlyOnce) {
  47243. events.splice(index, 1);
  47244. index--;
  47245. }
  47246. event.isDone = true;
  47247. event.action();
  47248. } // Don't do anything if the event has already be done.
  47249. }
  47250. else if (events[index].isDone && !events[index].onlyOnce) {
  47251. // reset event, the animation is looping
  47252. events[index].isDone = false;
  47253. }
  47254. }
  47255. if (!returnValue) {
  47256. this._stopped = true;
  47257. }
  47258. return returnValue;
  47259. };
  47260. return RuntimeAnimation;
  47261. }());
  47262. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47263. })(BABYLON || (BABYLON = {}));
  47264. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47265. var BABYLON;
  47266. (function (BABYLON) {
  47267. var Animatable = /** @class */ (function () {
  47268. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47269. if (fromFrame === void 0) { fromFrame = 0; }
  47270. if (toFrame === void 0) { toFrame = 100; }
  47271. if (loopAnimation === void 0) { loopAnimation = false; }
  47272. if (speedRatio === void 0) { speedRatio = 1.0; }
  47273. this.target = target;
  47274. this.fromFrame = fromFrame;
  47275. this.toFrame = toFrame;
  47276. this.loopAnimation = loopAnimation;
  47277. this.onAnimationEnd = onAnimationEnd;
  47278. this._localDelayOffset = null;
  47279. this._pausedDelay = null;
  47280. this._runtimeAnimations = new Array();
  47281. this._paused = false;
  47282. this._speedRatio = 1;
  47283. this.animationStarted = false;
  47284. if (animations) {
  47285. this.appendAnimations(target, animations);
  47286. }
  47287. this._speedRatio = speedRatio;
  47288. this._scene = scene;
  47289. scene._activeAnimatables.push(this);
  47290. }
  47291. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47292. get: function () {
  47293. return this._speedRatio;
  47294. },
  47295. set: function (value) {
  47296. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47297. var animation = this._runtimeAnimations[index];
  47298. animation._prepareForSpeedRatioChange(value);
  47299. }
  47300. this._speedRatio = value;
  47301. },
  47302. enumerable: true,
  47303. configurable: true
  47304. });
  47305. // Methods
  47306. Animatable.prototype.getAnimations = function () {
  47307. return this._runtimeAnimations;
  47308. };
  47309. Animatable.prototype.appendAnimations = function (target, animations) {
  47310. for (var index = 0; index < animations.length; index++) {
  47311. var animation = animations[index];
  47312. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47313. }
  47314. };
  47315. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47316. var runtimeAnimations = this._runtimeAnimations;
  47317. for (var index = 0; index < runtimeAnimations.length; index++) {
  47318. if (runtimeAnimations[index].animation.targetProperty === property) {
  47319. return runtimeAnimations[index].animation;
  47320. }
  47321. }
  47322. return null;
  47323. };
  47324. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47325. var runtimeAnimations = this._runtimeAnimations;
  47326. for (var index = 0; index < runtimeAnimations.length; index++) {
  47327. if (runtimeAnimations[index].animation.targetProperty === property) {
  47328. return runtimeAnimations[index];
  47329. }
  47330. }
  47331. return null;
  47332. };
  47333. Animatable.prototype.reset = function () {
  47334. var runtimeAnimations = this._runtimeAnimations;
  47335. for (var index = 0; index < runtimeAnimations.length; index++) {
  47336. runtimeAnimations[index].reset();
  47337. }
  47338. // Reset to original value
  47339. for (index = 0; index < runtimeAnimations.length; index++) {
  47340. var animation = runtimeAnimations[index];
  47341. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47342. }
  47343. this._localDelayOffset = null;
  47344. this._pausedDelay = null;
  47345. };
  47346. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47347. var runtimeAnimations = this._runtimeAnimations;
  47348. for (var index = 0; index < runtimeAnimations.length; index++) {
  47349. runtimeAnimations[index].animation.enableBlending = true;
  47350. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47351. }
  47352. };
  47353. Animatable.prototype.disableBlending = function () {
  47354. var runtimeAnimations = this._runtimeAnimations;
  47355. for (var index = 0; index < runtimeAnimations.length; index++) {
  47356. runtimeAnimations[index].animation.enableBlending = false;
  47357. }
  47358. };
  47359. Animatable.prototype.goToFrame = function (frame) {
  47360. var runtimeAnimations = this._runtimeAnimations;
  47361. if (runtimeAnimations[0]) {
  47362. var fps = runtimeAnimations[0].animation.framePerSecond;
  47363. var currentFrame = runtimeAnimations[0].currentFrame;
  47364. var adjustTime = frame - currentFrame;
  47365. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47366. if (this._localDelayOffset === null) {
  47367. this._localDelayOffset = 0;
  47368. }
  47369. this._localDelayOffset -= delay;
  47370. }
  47371. for (var index = 0; index < runtimeAnimations.length; index++) {
  47372. runtimeAnimations[index].goToFrame(frame);
  47373. }
  47374. };
  47375. Animatable.prototype.pause = function () {
  47376. if (this._paused) {
  47377. return;
  47378. }
  47379. this._paused = true;
  47380. };
  47381. Animatable.prototype.restart = function () {
  47382. this._paused = false;
  47383. };
  47384. Animatable.prototype.stop = function (animationName) {
  47385. if (animationName) {
  47386. var idx = this._scene._activeAnimatables.indexOf(this);
  47387. if (idx > -1) {
  47388. var runtimeAnimations = this._runtimeAnimations;
  47389. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47390. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47391. continue;
  47392. }
  47393. runtimeAnimations[index].dispose();
  47394. runtimeAnimations.splice(index, 1);
  47395. }
  47396. if (runtimeAnimations.length == 0) {
  47397. this._scene._activeAnimatables.splice(idx, 1);
  47398. if (this.onAnimationEnd) {
  47399. this.onAnimationEnd();
  47400. }
  47401. }
  47402. }
  47403. }
  47404. else {
  47405. var index = this._scene._activeAnimatables.indexOf(this);
  47406. if (index > -1) {
  47407. this._scene._activeAnimatables.splice(index, 1);
  47408. var runtimeAnimations = this._runtimeAnimations;
  47409. for (var index = 0; index < runtimeAnimations.length; index++) {
  47410. runtimeAnimations[index].dispose();
  47411. }
  47412. if (this.onAnimationEnd) {
  47413. this.onAnimationEnd();
  47414. }
  47415. }
  47416. }
  47417. };
  47418. Animatable.prototype._animate = function (delay) {
  47419. if (this._paused) {
  47420. this.animationStarted = false;
  47421. if (this._pausedDelay === null) {
  47422. this._pausedDelay = delay;
  47423. }
  47424. return true;
  47425. }
  47426. if (this._localDelayOffset === null) {
  47427. this._localDelayOffset = delay;
  47428. this._pausedDelay = null;
  47429. }
  47430. else if (this._pausedDelay !== null) {
  47431. this._localDelayOffset += delay - this._pausedDelay;
  47432. this._pausedDelay = null;
  47433. }
  47434. // Animating
  47435. var running = false;
  47436. var runtimeAnimations = this._runtimeAnimations;
  47437. var index;
  47438. for (index = 0; index < runtimeAnimations.length; index++) {
  47439. var animation = runtimeAnimations[index];
  47440. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47441. running = running || isRunning;
  47442. }
  47443. this.animationStarted = running;
  47444. if (!running) {
  47445. // Remove from active animatables
  47446. index = this._scene._activeAnimatables.indexOf(this);
  47447. this._scene._activeAnimatables.splice(index, 1);
  47448. // Dispose all runtime animations
  47449. for (index = 0; index < runtimeAnimations.length; index++) {
  47450. runtimeAnimations[index].dispose();
  47451. }
  47452. }
  47453. if (!running && this.onAnimationEnd) {
  47454. this.onAnimationEnd();
  47455. this.onAnimationEnd = null;
  47456. }
  47457. return running;
  47458. };
  47459. return Animatable;
  47460. }());
  47461. BABYLON.Animatable = Animatable;
  47462. })(BABYLON || (BABYLON = {}));
  47463. //# sourceMappingURL=babylon.animatable.js.map
  47464. var BABYLON;
  47465. (function (BABYLON) {
  47466. var EasingFunction = /** @class */ (function () {
  47467. function EasingFunction() {
  47468. // Properties
  47469. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47470. }
  47471. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47472. get: function () {
  47473. return EasingFunction._EASINGMODE_EASEIN;
  47474. },
  47475. enumerable: true,
  47476. configurable: true
  47477. });
  47478. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47479. get: function () {
  47480. return EasingFunction._EASINGMODE_EASEOUT;
  47481. },
  47482. enumerable: true,
  47483. configurable: true
  47484. });
  47485. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47486. get: function () {
  47487. return EasingFunction._EASINGMODE_EASEINOUT;
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47493. var n = Math.min(Math.max(easingMode, 0), 2);
  47494. this._easingMode = n;
  47495. };
  47496. EasingFunction.prototype.getEasingMode = function () {
  47497. return this._easingMode;
  47498. };
  47499. EasingFunction.prototype.easeInCore = function (gradient) {
  47500. throw new Error('You must implement this method');
  47501. };
  47502. EasingFunction.prototype.ease = function (gradient) {
  47503. switch (this._easingMode) {
  47504. case EasingFunction.EASINGMODE_EASEIN:
  47505. return this.easeInCore(gradient);
  47506. case EasingFunction.EASINGMODE_EASEOUT:
  47507. return (1 - this.easeInCore(1 - gradient));
  47508. }
  47509. if (gradient >= 0.5) {
  47510. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47511. }
  47512. return (this.easeInCore(gradient * 2) * 0.5);
  47513. };
  47514. //Statics
  47515. EasingFunction._EASINGMODE_EASEIN = 0;
  47516. EasingFunction._EASINGMODE_EASEOUT = 1;
  47517. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47518. return EasingFunction;
  47519. }());
  47520. BABYLON.EasingFunction = EasingFunction;
  47521. var CircleEase = /** @class */ (function (_super) {
  47522. __extends(CircleEase, _super);
  47523. function CircleEase() {
  47524. return _super !== null && _super.apply(this, arguments) || this;
  47525. }
  47526. CircleEase.prototype.easeInCore = function (gradient) {
  47527. gradient = Math.max(0, Math.min(1, gradient));
  47528. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47529. };
  47530. return CircleEase;
  47531. }(EasingFunction));
  47532. BABYLON.CircleEase = CircleEase;
  47533. var BackEase = /** @class */ (function (_super) {
  47534. __extends(BackEase, _super);
  47535. function BackEase(amplitude) {
  47536. if (amplitude === void 0) { amplitude = 1; }
  47537. var _this = _super.call(this) || this;
  47538. _this.amplitude = amplitude;
  47539. return _this;
  47540. }
  47541. BackEase.prototype.easeInCore = function (gradient) {
  47542. var num = Math.max(0, this.amplitude);
  47543. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47544. };
  47545. return BackEase;
  47546. }(EasingFunction));
  47547. BABYLON.BackEase = BackEase;
  47548. var BounceEase = /** @class */ (function (_super) {
  47549. __extends(BounceEase, _super);
  47550. function BounceEase(bounces, bounciness) {
  47551. if (bounces === void 0) { bounces = 3; }
  47552. if (bounciness === void 0) { bounciness = 2; }
  47553. var _this = _super.call(this) || this;
  47554. _this.bounces = bounces;
  47555. _this.bounciness = bounciness;
  47556. return _this;
  47557. }
  47558. BounceEase.prototype.easeInCore = function (gradient) {
  47559. var y = Math.max(0.0, this.bounces);
  47560. var bounciness = this.bounciness;
  47561. if (bounciness <= 1.0) {
  47562. bounciness = 1.001;
  47563. }
  47564. var num9 = Math.pow(bounciness, y);
  47565. var num5 = 1.0 - bounciness;
  47566. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47567. var num15 = gradient * num4;
  47568. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47569. var num3 = Math.floor(num65);
  47570. var num13 = num3 + 1.0;
  47571. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47572. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47573. var num7 = (num8 + num12) * 0.5;
  47574. var num6 = gradient - num7;
  47575. var num2 = num7 - num8;
  47576. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47577. };
  47578. return BounceEase;
  47579. }(EasingFunction));
  47580. BABYLON.BounceEase = BounceEase;
  47581. var CubicEase = /** @class */ (function (_super) {
  47582. __extends(CubicEase, _super);
  47583. function CubicEase() {
  47584. return _super !== null && _super.apply(this, arguments) || this;
  47585. }
  47586. CubicEase.prototype.easeInCore = function (gradient) {
  47587. return (gradient * gradient * gradient);
  47588. };
  47589. return CubicEase;
  47590. }(EasingFunction));
  47591. BABYLON.CubicEase = CubicEase;
  47592. var ElasticEase = /** @class */ (function (_super) {
  47593. __extends(ElasticEase, _super);
  47594. function ElasticEase(oscillations, springiness) {
  47595. if (oscillations === void 0) { oscillations = 3; }
  47596. if (springiness === void 0) { springiness = 3; }
  47597. var _this = _super.call(this) || this;
  47598. _this.oscillations = oscillations;
  47599. _this.springiness = springiness;
  47600. return _this;
  47601. }
  47602. ElasticEase.prototype.easeInCore = function (gradient) {
  47603. var num2;
  47604. var num3 = Math.max(0.0, this.oscillations);
  47605. var num = Math.max(0.0, this.springiness);
  47606. if (num == 0) {
  47607. num2 = gradient;
  47608. }
  47609. else {
  47610. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47611. }
  47612. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47613. };
  47614. return ElasticEase;
  47615. }(EasingFunction));
  47616. BABYLON.ElasticEase = ElasticEase;
  47617. var ExponentialEase = /** @class */ (function (_super) {
  47618. __extends(ExponentialEase, _super);
  47619. function ExponentialEase(exponent) {
  47620. if (exponent === void 0) { exponent = 2; }
  47621. var _this = _super.call(this) || this;
  47622. _this.exponent = exponent;
  47623. return _this;
  47624. }
  47625. ExponentialEase.prototype.easeInCore = function (gradient) {
  47626. if (this.exponent <= 0) {
  47627. return gradient;
  47628. }
  47629. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47630. };
  47631. return ExponentialEase;
  47632. }(EasingFunction));
  47633. BABYLON.ExponentialEase = ExponentialEase;
  47634. var PowerEase = /** @class */ (function (_super) {
  47635. __extends(PowerEase, _super);
  47636. function PowerEase(power) {
  47637. if (power === void 0) { power = 2; }
  47638. var _this = _super.call(this) || this;
  47639. _this.power = power;
  47640. return _this;
  47641. }
  47642. PowerEase.prototype.easeInCore = function (gradient) {
  47643. var y = Math.max(0.0, this.power);
  47644. return Math.pow(gradient, y);
  47645. };
  47646. return PowerEase;
  47647. }(EasingFunction));
  47648. BABYLON.PowerEase = PowerEase;
  47649. var QuadraticEase = /** @class */ (function (_super) {
  47650. __extends(QuadraticEase, _super);
  47651. function QuadraticEase() {
  47652. return _super !== null && _super.apply(this, arguments) || this;
  47653. }
  47654. QuadraticEase.prototype.easeInCore = function (gradient) {
  47655. return (gradient * gradient);
  47656. };
  47657. return QuadraticEase;
  47658. }(EasingFunction));
  47659. BABYLON.QuadraticEase = QuadraticEase;
  47660. var QuarticEase = /** @class */ (function (_super) {
  47661. __extends(QuarticEase, _super);
  47662. function QuarticEase() {
  47663. return _super !== null && _super.apply(this, arguments) || this;
  47664. }
  47665. QuarticEase.prototype.easeInCore = function (gradient) {
  47666. return (gradient * gradient * gradient * gradient);
  47667. };
  47668. return QuarticEase;
  47669. }(EasingFunction));
  47670. BABYLON.QuarticEase = QuarticEase;
  47671. var QuinticEase = /** @class */ (function (_super) {
  47672. __extends(QuinticEase, _super);
  47673. function QuinticEase() {
  47674. return _super !== null && _super.apply(this, arguments) || this;
  47675. }
  47676. QuinticEase.prototype.easeInCore = function (gradient) {
  47677. return (gradient * gradient * gradient * gradient * gradient);
  47678. };
  47679. return QuinticEase;
  47680. }(EasingFunction));
  47681. BABYLON.QuinticEase = QuinticEase;
  47682. var SineEase = /** @class */ (function (_super) {
  47683. __extends(SineEase, _super);
  47684. function SineEase() {
  47685. return _super !== null && _super.apply(this, arguments) || this;
  47686. }
  47687. SineEase.prototype.easeInCore = function (gradient) {
  47688. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47689. };
  47690. return SineEase;
  47691. }(EasingFunction));
  47692. BABYLON.SineEase = SineEase;
  47693. var BezierCurveEase = /** @class */ (function (_super) {
  47694. __extends(BezierCurveEase, _super);
  47695. function BezierCurveEase(x1, y1, x2, y2) {
  47696. if (x1 === void 0) { x1 = 0; }
  47697. if (y1 === void 0) { y1 = 0; }
  47698. if (x2 === void 0) { x2 = 1; }
  47699. if (y2 === void 0) { y2 = 1; }
  47700. var _this = _super.call(this) || this;
  47701. _this.x1 = x1;
  47702. _this.y1 = y1;
  47703. _this.x2 = x2;
  47704. _this.y2 = y2;
  47705. return _this;
  47706. }
  47707. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47708. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47709. };
  47710. return BezierCurveEase;
  47711. }(EasingFunction));
  47712. BABYLON.BezierCurveEase = BezierCurveEase;
  47713. })(BABYLON || (BABYLON = {}));
  47714. //# sourceMappingURL=babylon.easing.js.map
  47715. var BABYLON;
  47716. (function (BABYLON) {
  47717. var Condition = /** @class */ (function () {
  47718. function Condition(actionManager) {
  47719. this._actionManager = actionManager;
  47720. }
  47721. Condition.prototype.isValid = function () {
  47722. return true;
  47723. };
  47724. Condition.prototype._getProperty = function (propertyPath) {
  47725. return this._actionManager._getProperty(propertyPath);
  47726. };
  47727. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47728. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47729. };
  47730. Condition.prototype.serialize = function () {
  47731. };
  47732. Condition.prototype._serialize = function (serializedCondition) {
  47733. return {
  47734. type: 2,
  47735. children: [],
  47736. name: serializedCondition.name,
  47737. properties: serializedCondition.properties
  47738. };
  47739. };
  47740. return Condition;
  47741. }());
  47742. BABYLON.Condition = Condition;
  47743. var ValueCondition = /** @class */ (function (_super) {
  47744. __extends(ValueCondition, _super);
  47745. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47746. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47747. var _this = _super.call(this, actionManager) || this;
  47748. _this.propertyPath = propertyPath;
  47749. _this.value = value;
  47750. _this.operator = operator;
  47751. _this._target = target;
  47752. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47753. _this._property = _this._getProperty(_this.propertyPath);
  47754. return _this;
  47755. }
  47756. Object.defineProperty(ValueCondition, "IsEqual", {
  47757. get: function () {
  47758. return ValueCondition._IsEqual;
  47759. },
  47760. enumerable: true,
  47761. configurable: true
  47762. });
  47763. Object.defineProperty(ValueCondition, "IsDifferent", {
  47764. get: function () {
  47765. return ValueCondition._IsDifferent;
  47766. },
  47767. enumerable: true,
  47768. configurable: true
  47769. });
  47770. Object.defineProperty(ValueCondition, "IsGreater", {
  47771. get: function () {
  47772. return ValueCondition._IsGreater;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(ValueCondition, "IsLesser", {
  47778. get: function () {
  47779. return ValueCondition._IsLesser;
  47780. },
  47781. enumerable: true,
  47782. configurable: true
  47783. });
  47784. // Methods
  47785. ValueCondition.prototype.isValid = function () {
  47786. switch (this.operator) {
  47787. case ValueCondition.IsGreater:
  47788. return this._effectiveTarget[this._property] > this.value;
  47789. case ValueCondition.IsLesser:
  47790. return this._effectiveTarget[this._property] < this.value;
  47791. case ValueCondition.IsEqual:
  47792. case ValueCondition.IsDifferent:
  47793. var check;
  47794. if (this.value.equals) {
  47795. check = this.value.equals(this._effectiveTarget[this._property]);
  47796. }
  47797. else {
  47798. check = this.value === this._effectiveTarget[this._property];
  47799. }
  47800. return this.operator === ValueCondition.IsEqual ? check : !check;
  47801. }
  47802. return false;
  47803. };
  47804. ValueCondition.prototype.serialize = function () {
  47805. return this._serialize({
  47806. name: "ValueCondition",
  47807. properties: [
  47808. BABYLON.Action._GetTargetProperty(this._target),
  47809. { name: "propertyPath", value: this.propertyPath },
  47810. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47811. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47812. ]
  47813. });
  47814. };
  47815. ValueCondition.GetOperatorName = function (operator) {
  47816. switch (operator) {
  47817. case ValueCondition._IsEqual: return "IsEqual";
  47818. case ValueCondition._IsDifferent: return "IsDifferent";
  47819. case ValueCondition._IsGreater: return "IsGreater";
  47820. case ValueCondition._IsLesser: return "IsLesser";
  47821. default: return "";
  47822. }
  47823. };
  47824. // Statics
  47825. ValueCondition._IsEqual = 0;
  47826. ValueCondition._IsDifferent = 1;
  47827. ValueCondition._IsGreater = 2;
  47828. ValueCondition._IsLesser = 3;
  47829. return ValueCondition;
  47830. }(Condition));
  47831. BABYLON.ValueCondition = ValueCondition;
  47832. var PredicateCondition = /** @class */ (function (_super) {
  47833. __extends(PredicateCondition, _super);
  47834. function PredicateCondition(actionManager, predicate) {
  47835. var _this = _super.call(this, actionManager) || this;
  47836. _this.predicate = predicate;
  47837. return _this;
  47838. }
  47839. PredicateCondition.prototype.isValid = function () {
  47840. return this.predicate();
  47841. };
  47842. return PredicateCondition;
  47843. }(Condition));
  47844. BABYLON.PredicateCondition = PredicateCondition;
  47845. var StateCondition = /** @class */ (function (_super) {
  47846. __extends(StateCondition, _super);
  47847. function StateCondition(actionManager, target, value) {
  47848. var _this = _super.call(this, actionManager) || this;
  47849. _this.value = value;
  47850. _this._target = target;
  47851. return _this;
  47852. }
  47853. // Methods
  47854. StateCondition.prototype.isValid = function () {
  47855. return this._target.state === this.value;
  47856. };
  47857. StateCondition.prototype.serialize = function () {
  47858. return this._serialize({
  47859. name: "StateCondition",
  47860. properties: [
  47861. BABYLON.Action._GetTargetProperty(this._target),
  47862. { name: "value", value: this.value }
  47863. ]
  47864. });
  47865. };
  47866. return StateCondition;
  47867. }(Condition));
  47868. BABYLON.StateCondition = StateCondition;
  47869. })(BABYLON || (BABYLON = {}));
  47870. //# sourceMappingURL=babylon.condition.js.map
  47871. var BABYLON;
  47872. (function (BABYLON) {
  47873. var Action = /** @class */ (function () {
  47874. function Action(triggerOptions, condition) {
  47875. this.triggerOptions = triggerOptions;
  47876. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47877. if (triggerOptions.parameter) {
  47878. this.trigger = triggerOptions.trigger;
  47879. this._triggerParameter = triggerOptions.parameter;
  47880. }
  47881. else {
  47882. this.trigger = triggerOptions;
  47883. }
  47884. this._nextActiveAction = this;
  47885. this._condition = condition;
  47886. }
  47887. // Methods
  47888. Action.prototype._prepare = function () {
  47889. };
  47890. Action.prototype.getTriggerParameter = function () {
  47891. return this._triggerParameter;
  47892. };
  47893. Action.prototype._executeCurrent = function (evt) {
  47894. if (this._nextActiveAction._condition) {
  47895. var condition = this._nextActiveAction._condition;
  47896. var currentRenderId = this._actionManager.getScene().getRenderId();
  47897. // We cache the current evaluation for the current frame
  47898. if (condition._evaluationId === currentRenderId) {
  47899. if (!condition._currentResult) {
  47900. return;
  47901. }
  47902. }
  47903. else {
  47904. condition._evaluationId = currentRenderId;
  47905. if (!condition.isValid()) {
  47906. condition._currentResult = false;
  47907. return;
  47908. }
  47909. condition._currentResult = true;
  47910. }
  47911. }
  47912. this.onBeforeExecuteObservable.notifyObservers(this);
  47913. this._nextActiveAction.execute(evt);
  47914. this.skipToNextActiveAction();
  47915. };
  47916. Action.prototype.execute = function (evt) {
  47917. };
  47918. Action.prototype.skipToNextActiveAction = function () {
  47919. if (this._nextActiveAction._child) {
  47920. if (!this._nextActiveAction._child._actionManager) {
  47921. this._nextActiveAction._child._actionManager = this._actionManager;
  47922. }
  47923. this._nextActiveAction = this._nextActiveAction._child;
  47924. }
  47925. else {
  47926. this._nextActiveAction = this;
  47927. }
  47928. };
  47929. Action.prototype.then = function (action) {
  47930. this._child = action;
  47931. action._actionManager = this._actionManager;
  47932. action._prepare();
  47933. return action;
  47934. };
  47935. Action.prototype._getProperty = function (propertyPath) {
  47936. return this._actionManager._getProperty(propertyPath);
  47937. };
  47938. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47939. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47940. };
  47941. Action.prototype.serialize = function (parent) {
  47942. };
  47943. // Called by BABYLON.Action objects in serialize(...). Internal use
  47944. Action.prototype._serialize = function (serializedAction, parent) {
  47945. var serializationObject = {
  47946. type: 1,
  47947. children: [],
  47948. name: serializedAction.name,
  47949. properties: serializedAction.properties || []
  47950. };
  47951. // Serialize child
  47952. if (this._child) {
  47953. this._child.serialize(serializationObject);
  47954. }
  47955. // Check if "this" has a condition
  47956. if (this._condition) {
  47957. var serializedCondition = this._condition.serialize();
  47958. serializedCondition.children.push(serializationObject);
  47959. if (parent) {
  47960. parent.children.push(serializedCondition);
  47961. }
  47962. return serializedCondition;
  47963. }
  47964. if (parent) {
  47965. parent.children.push(serializationObject);
  47966. }
  47967. return serializationObject;
  47968. };
  47969. Action._SerializeValueAsString = function (value) {
  47970. if (typeof value === "number") {
  47971. return value.toString();
  47972. }
  47973. if (typeof value === "boolean") {
  47974. return value ? "true" : "false";
  47975. }
  47976. if (value instanceof BABYLON.Vector2) {
  47977. return value.x + ", " + value.y;
  47978. }
  47979. if (value instanceof BABYLON.Vector3) {
  47980. return value.x + ", " + value.y + ", " + value.z;
  47981. }
  47982. if (value instanceof BABYLON.Color3) {
  47983. return value.r + ", " + value.g + ", " + value.b;
  47984. }
  47985. if (value instanceof BABYLON.Color4) {
  47986. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47987. }
  47988. return value; // string
  47989. };
  47990. Action._GetTargetProperty = function (target) {
  47991. return {
  47992. name: "target",
  47993. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47994. : target instanceof BABYLON.Light ? "LightProperties"
  47995. : target instanceof BABYLON.Camera ? "CameraProperties"
  47996. : "SceneProperties",
  47997. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47998. };
  47999. };
  48000. return Action;
  48001. }());
  48002. BABYLON.Action = Action;
  48003. })(BABYLON || (BABYLON = {}));
  48004. //# sourceMappingURL=babylon.action.js.map
  48005. var BABYLON;
  48006. (function (BABYLON) {
  48007. /**
  48008. * ActionEvent is the event beint sent when an action is triggered.
  48009. */
  48010. var ActionEvent = /** @class */ (function () {
  48011. /**
  48012. * @param source The mesh or sprite that triggered the action.
  48013. * @param pointerX The X mouse cursor position at the time of the event
  48014. * @param pointerY The Y mouse cursor position at the time of the event
  48015. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48016. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48017. */
  48018. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48019. this.source = source;
  48020. this.pointerX = pointerX;
  48021. this.pointerY = pointerY;
  48022. this.meshUnderPointer = meshUnderPointer;
  48023. this.sourceEvent = sourceEvent;
  48024. this.additionalData = additionalData;
  48025. }
  48026. /**
  48027. * Helper function to auto-create an ActionEvent from a source mesh.
  48028. * @param source The source mesh that triggered the event
  48029. * @param evt {Event} The original (browser) event
  48030. */
  48031. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48032. var scene = source.getScene();
  48033. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48034. };
  48035. /**
  48036. * Helper function to auto-create an ActionEvent from a source mesh.
  48037. * @param source The source sprite that triggered the event
  48038. * @param scene Scene associated with the sprite
  48039. * @param evt {Event} The original (browser) event
  48040. */
  48041. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48042. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48043. };
  48044. /**
  48045. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48046. * @param scene the scene where the event occurred
  48047. * @param evt {Event} The original (browser) event
  48048. */
  48049. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48050. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48051. };
  48052. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48053. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48054. };
  48055. return ActionEvent;
  48056. }());
  48057. BABYLON.ActionEvent = ActionEvent;
  48058. /**
  48059. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48060. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48061. */
  48062. var ActionManager = /** @class */ (function () {
  48063. function ActionManager(scene) {
  48064. // Members
  48065. this.actions = new Array();
  48066. this.hoverCursor = '';
  48067. this._scene = scene;
  48068. scene._actionManagers.push(this);
  48069. }
  48070. Object.defineProperty(ActionManager, "NothingTrigger", {
  48071. get: function () {
  48072. return ActionManager._NothingTrigger;
  48073. },
  48074. enumerable: true,
  48075. configurable: true
  48076. });
  48077. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48078. get: function () {
  48079. return ActionManager._OnPickTrigger;
  48080. },
  48081. enumerable: true,
  48082. configurable: true
  48083. });
  48084. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48085. get: function () {
  48086. return ActionManager._OnLeftPickTrigger;
  48087. },
  48088. enumerable: true,
  48089. configurable: true
  48090. });
  48091. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48092. get: function () {
  48093. return ActionManager._OnRightPickTrigger;
  48094. },
  48095. enumerable: true,
  48096. configurable: true
  48097. });
  48098. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48099. get: function () {
  48100. return ActionManager._OnCenterPickTrigger;
  48101. },
  48102. enumerable: true,
  48103. configurable: true
  48104. });
  48105. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48106. get: function () {
  48107. return ActionManager._OnPickDownTrigger;
  48108. },
  48109. enumerable: true,
  48110. configurable: true
  48111. });
  48112. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48113. get: function () {
  48114. return ActionManager._OnDoublePickTrigger;
  48115. },
  48116. enumerable: true,
  48117. configurable: true
  48118. });
  48119. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48120. get: function () {
  48121. return ActionManager._OnPickUpTrigger;
  48122. },
  48123. enumerable: true,
  48124. configurable: true
  48125. });
  48126. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48127. /// This trigger will only be raised if you also declared a OnPickDown
  48128. get: function () {
  48129. return ActionManager._OnPickOutTrigger;
  48130. },
  48131. enumerable: true,
  48132. configurable: true
  48133. });
  48134. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48135. get: function () {
  48136. return ActionManager._OnLongPressTrigger;
  48137. },
  48138. enumerable: true,
  48139. configurable: true
  48140. });
  48141. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48142. get: function () {
  48143. return ActionManager._OnPointerOverTrigger;
  48144. },
  48145. enumerable: true,
  48146. configurable: true
  48147. });
  48148. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48149. get: function () {
  48150. return ActionManager._OnPointerOutTrigger;
  48151. },
  48152. enumerable: true,
  48153. configurable: true
  48154. });
  48155. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48156. get: function () {
  48157. return ActionManager._OnEveryFrameTrigger;
  48158. },
  48159. enumerable: true,
  48160. configurable: true
  48161. });
  48162. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48163. get: function () {
  48164. return ActionManager._OnIntersectionEnterTrigger;
  48165. },
  48166. enumerable: true,
  48167. configurable: true
  48168. });
  48169. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48170. get: function () {
  48171. return ActionManager._OnIntersectionExitTrigger;
  48172. },
  48173. enumerable: true,
  48174. configurable: true
  48175. });
  48176. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48177. get: function () {
  48178. return ActionManager._OnKeyDownTrigger;
  48179. },
  48180. enumerable: true,
  48181. configurable: true
  48182. });
  48183. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48184. get: function () {
  48185. return ActionManager._OnKeyUpTrigger;
  48186. },
  48187. enumerable: true,
  48188. configurable: true
  48189. });
  48190. // Methods
  48191. ActionManager.prototype.dispose = function () {
  48192. var index = this._scene._actionManagers.indexOf(this);
  48193. for (var i = 0; i < this.actions.length; i++) {
  48194. var action = this.actions[i];
  48195. ActionManager.Triggers[action.trigger]--;
  48196. if (ActionManager.Triggers[action.trigger] === 0) {
  48197. delete ActionManager.Triggers[action.trigger];
  48198. }
  48199. }
  48200. if (index > -1) {
  48201. this._scene._actionManagers.splice(index, 1);
  48202. }
  48203. };
  48204. ActionManager.prototype.getScene = function () {
  48205. return this._scene;
  48206. };
  48207. /**
  48208. * Does this action manager handles actions of any of the given triggers
  48209. * @param {number[]} triggers - the triggers to be tested
  48210. * @return {boolean} whether one (or more) of the triggers is handeled
  48211. */
  48212. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48213. for (var index = 0; index < this.actions.length; index++) {
  48214. var action = this.actions[index];
  48215. if (triggers.indexOf(action.trigger) > -1) {
  48216. return true;
  48217. }
  48218. }
  48219. return false;
  48220. };
  48221. /**
  48222. * Does this action manager handles actions of a given trigger
  48223. * @param {number} trigger - the trigger to be tested
  48224. * @return {boolean} whether the trigger is handeled
  48225. */
  48226. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48227. for (var index = 0; index < this.actions.length; index++) {
  48228. var action = this.actions[index];
  48229. if (action.trigger === trigger) {
  48230. return true;
  48231. }
  48232. }
  48233. return false;
  48234. };
  48235. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48236. /**
  48237. * Does this action manager has pointer triggers
  48238. * @return {boolean} whether or not it has pointer triggers
  48239. */
  48240. get: function () {
  48241. for (var index = 0; index < this.actions.length; index++) {
  48242. var action = this.actions[index];
  48243. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48244. return true;
  48245. }
  48246. }
  48247. return false;
  48248. },
  48249. enumerable: true,
  48250. configurable: true
  48251. });
  48252. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48253. /**
  48254. * Does this action manager has pick triggers
  48255. * @return {boolean} whether or not it has pick triggers
  48256. */
  48257. get: function () {
  48258. for (var index = 0; index < this.actions.length; index++) {
  48259. var action = this.actions[index];
  48260. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48261. return true;
  48262. }
  48263. }
  48264. return false;
  48265. },
  48266. enumerable: true,
  48267. configurable: true
  48268. });
  48269. Object.defineProperty(ActionManager, "HasTriggers", {
  48270. /**
  48271. * Does exist one action manager with at least one trigger
  48272. * @return {boolean} whether or not it exists one action manager with one trigger
  48273. **/
  48274. get: function () {
  48275. for (var t in ActionManager.Triggers) {
  48276. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48277. return true;
  48278. }
  48279. }
  48280. return false;
  48281. },
  48282. enumerable: true,
  48283. configurable: true
  48284. });
  48285. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48286. /**
  48287. * Does exist one action manager with at least one pick trigger
  48288. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48289. **/
  48290. get: function () {
  48291. for (var t in ActionManager.Triggers) {
  48292. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48293. var t_int = parseInt(t);
  48294. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48295. return true;
  48296. }
  48297. }
  48298. }
  48299. return false;
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. /**
  48305. * Does exist one action manager that handles actions of a given trigger
  48306. * @param {number} trigger - the trigger to be tested
  48307. * @return {boolean} whether the trigger is handeled by at least one action manager
  48308. **/
  48309. ActionManager.HasSpecificTrigger = function (trigger) {
  48310. for (var t in ActionManager.Triggers) {
  48311. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48312. var t_int = parseInt(t);
  48313. if (t_int === trigger) {
  48314. return true;
  48315. }
  48316. }
  48317. }
  48318. return false;
  48319. };
  48320. /**
  48321. * Registers an action to this action manager
  48322. * @param {BABYLON.Action} action - the action to be registered
  48323. * @return {BABYLON.Action} the action amended (prepared) after registration
  48324. */
  48325. ActionManager.prototype.registerAction = function (action) {
  48326. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48327. if (this.getScene().actionManager !== this) {
  48328. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48329. return null;
  48330. }
  48331. }
  48332. this.actions.push(action);
  48333. if (ActionManager.Triggers[action.trigger]) {
  48334. ActionManager.Triggers[action.trigger]++;
  48335. }
  48336. else {
  48337. ActionManager.Triggers[action.trigger] = 1;
  48338. }
  48339. action._actionManager = this;
  48340. action._prepare();
  48341. return action;
  48342. };
  48343. /**
  48344. * Unregisters an action to this action manager
  48345. * @param action The action to be unregistered
  48346. * @return whether the action has been unregistered
  48347. */
  48348. ActionManager.prototype.unregisterAction = function (action) {
  48349. var index = this.actions.indexOf(action);
  48350. if (index !== -1) {
  48351. this.actions.splice(index, 1);
  48352. ActionManager.Triggers[action.trigger] -= 1;
  48353. if (ActionManager.Triggers[action.trigger] === 0) {
  48354. delete ActionManager.Triggers[action.trigger];
  48355. }
  48356. delete action._actionManager;
  48357. return true;
  48358. }
  48359. return false;
  48360. };
  48361. /**
  48362. * Process a specific trigger
  48363. * @param {number} trigger - the trigger to process
  48364. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48365. */
  48366. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48367. for (var index = 0; index < this.actions.length; index++) {
  48368. var action = this.actions[index];
  48369. if (action.trigger === trigger) {
  48370. if (evt) {
  48371. if (trigger === ActionManager.OnKeyUpTrigger
  48372. || trigger === ActionManager.OnKeyDownTrigger) {
  48373. var parameter = action.getTriggerParameter();
  48374. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48375. if (!parameter.toLowerCase) {
  48376. continue;
  48377. }
  48378. var lowerCase = parameter.toLowerCase();
  48379. if (lowerCase !== evt.sourceEvent.key) {
  48380. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48381. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48382. if (actualkey !== lowerCase) {
  48383. continue;
  48384. }
  48385. }
  48386. }
  48387. }
  48388. }
  48389. action._executeCurrent(evt);
  48390. }
  48391. }
  48392. };
  48393. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48394. var properties = propertyPath.split(".");
  48395. for (var index = 0; index < properties.length - 1; index++) {
  48396. target = target[properties[index]];
  48397. }
  48398. return target;
  48399. };
  48400. ActionManager.prototype._getProperty = function (propertyPath) {
  48401. var properties = propertyPath.split(".");
  48402. return properties[properties.length - 1];
  48403. };
  48404. ActionManager.prototype.serialize = function (name) {
  48405. var root = {
  48406. children: new Array(),
  48407. name: name,
  48408. type: 3,
  48409. properties: new Array() // Empty for root but required
  48410. };
  48411. for (var i = 0; i < this.actions.length; i++) {
  48412. var triggerObject = {
  48413. type: 0,
  48414. children: new Array(),
  48415. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48416. properties: new Array()
  48417. };
  48418. var triggerOptions = this.actions[i].triggerOptions;
  48419. if (triggerOptions && typeof triggerOptions !== "number") {
  48420. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48421. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48422. }
  48423. else {
  48424. var parameter = {};
  48425. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48426. if (triggerOptions.parameter.mesh) {
  48427. parameter._meshId = triggerOptions.parameter.mesh.id;
  48428. }
  48429. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48430. }
  48431. }
  48432. // Serialize child action, recursively
  48433. this.actions[i].serialize(triggerObject);
  48434. // Add serialized trigger
  48435. root.children.push(triggerObject);
  48436. }
  48437. return root;
  48438. };
  48439. ActionManager.Parse = function (parsedActions, object, scene) {
  48440. var actionManager = new ActionManager(scene);
  48441. if (object === null)
  48442. scene.actionManager = actionManager;
  48443. else
  48444. object.actionManager = actionManager;
  48445. // instanciate a new object
  48446. var instanciate = function (name, params) {
  48447. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48448. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48449. newInstance.constructor.apply(newInstance, params);
  48450. return newInstance;
  48451. };
  48452. var parseParameter = function (name, value, target, propertyPath) {
  48453. if (propertyPath === null) {
  48454. // String, boolean or float
  48455. var floatValue = parseFloat(value);
  48456. if (value === "true" || value === "false")
  48457. return value === "true";
  48458. else
  48459. return isNaN(floatValue) ? value : floatValue;
  48460. }
  48461. var effectiveTarget = propertyPath.split(".");
  48462. var values = value.split(",");
  48463. // Get effective Target
  48464. for (var i = 0; i < effectiveTarget.length; i++) {
  48465. target = target[effectiveTarget[i]];
  48466. }
  48467. // Return appropriate value with its type
  48468. if (typeof (target) === "boolean")
  48469. return values[0] === "true";
  48470. if (typeof (target) === "string")
  48471. return values[0];
  48472. // Parameters with multiple values such as Vector3 etc.
  48473. var split = new Array();
  48474. for (var i = 0; i < values.length; i++)
  48475. split.push(parseFloat(values[i]));
  48476. if (target instanceof BABYLON.Vector3)
  48477. return BABYLON.Vector3.FromArray(split);
  48478. if (target instanceof BABYLON.Vector4)
  48479. return BABYLON.Vector4.FromArray(split);
  48480. if (target instanceof BABYLON.Color3)
  48481. return BABYLON.Color3.FromArray(split);
  48482. if (target instanceof BABYLON.Color4)
  48483. return BABYLON.Color4.FromArray(split);
  48484. return parseFloat(values[0]);
  48485. };
  48486. // traverse graph per trigger
  48487. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48488. if (combineArray === void 0) { combineArray = null; }
  48489. if (parsedAction.detached)
  48490. return;
  48491. var parameters = new Array();
  48492. var target = null;
  48493. var propertyPath = null;
  48494. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48495. // Parameters
  48496. if (parsedAction.type === 2)
  48497. parameters.push(actionManager);
  48498. else
  48499. parameters.push(trigger);
  48500. if (combine) {
  48501. var actions = new Array();
  48502. for (var j = 0; j < parsedAction.combine.length; j++) {
  48503. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48504. }
  48505. parameters.push(actions);
  48506. }
  48507. else {
  48508. for (var i = 0; i < parsedAction.properties.length; i++) {
  48509. var value = parsedAction.properties[i].value;
  48510. var name = parsedAction.properties[i].name;
  48511. var targetType = parsedAction.properties[i].targetType;
  48512. if (name === "target")
  48513. if (targetType !== null && targetType === "SceneProperties")
  48514. value = target = scene;
  48515. else
  48516. value = target = scene.getNodeByName(value);
  48517. else if (name === "parent")
  48518. value = scene.getNodeByName(value);
  48519. else if (name === "sound")
  48520. value = scene.getSoundByName(value);
  48521. else if (name !== "propertyPath") {
  48522. if (parsedAction.type === 2 && name === "operator")
  48523. value = BABYLON.ValueCondition[value];
  48524. else
  48525. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48526. }
  48527. else {
  48528. propertyPath = value;
  48529. }
  48530. parameters.push(value);
  48531. }
  48532. }
  48533. if (combineArray === null) {
  48534. parameters.push(condition);
  48535. }
  48536. else {
  48537. parameters.push(null);
  48538. }
  48539. // If interpolate value action
  48540. if (parsedAction.name === "InterpolateValueAction") {
  48541. var param = parameters[parameters.length - 2];
  48542. parameters[parameters.length - 1] = param;
  48543. parameters[parameters.length - 2] = condition;
  48544. }
  48545. // Action or condition(s) and not CombineAction
  48546. var newAction = instanciate(parsedAction.name, parameters);
  48547. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48548. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48549. if (action)
  48550. action.then(nothing);
  48551. else
  48552. actionManager.registerAction(nothing);
  48553. action = nothing;
  48554. }
  48555. if (combineArray === null) {
  48556. if (newAction instanceof BABYLON.Condition) {
  48557. condition = newAction;
  48558. newAction = action;
  48559. }
  48560. else {
  48561. condition = null;
  48562. if (action)
  48563. action.then(newAction);
  48564. else
  48565. actionManager.registerAction(newAction);
  48566. }
  48567. }
  48568. else {
  48569. combineArray.push(newAction);
  48570. }
  48571. for (var i = 0; i < parsedAction.children.length; i++)
  48572. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48573. };
  48574. // triggers
  48575. for (var i = 0; i < parsedActions.children.length; i++) {
  48576. var triggerParams;
  48577. var trigger = parsedActions.children[i];
  48578. if (trigger.properties.length > 0) {
  48579. var param = trigger.properties[0].value;
  48580. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48581. if (value._meshId) {
  48582. value.mesh = scene.getMeshByID(value._meshId);
  48583. }
  48584. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48585. }
  48586. else
  48587. triggerParams = ActionManager[trigger.name];
  48588. for (var j = 0; j < trigger.children.length; j++) {
  48589. if (!trigger.detached)
  48590. traverse(trigger.children[j], triggerParams, null, null);
  48591. }
  48592. }
  48593. };
  48594. ActionManager.GetTriggerName = function (trigger) {
  48595. switch (trigger) {
  48596. case 0: return "NothingTrigger";
  48597. case 1: return "OnPickTrigger";
  48598. case 2: return "OnLeftPickTrigger";
  48599. case 3: return "OnRightPickTrigger";
  48600. case 4: return "OnCenterPickTrigger";
  48601. case 5: return "OnPickDownTrigger";
  48602. case 6: return "OnPickUpTrigger";
  48603. case 7: return "OnLongPressTrigger";
  48604. case 8: return "OnPointerOverTrigger";
  48605. case 9: return "OnPointerOutTrigger";
  48606. case 10: return "OnEveryFrameTrigger";
  48607. case 11: return "OnIntersectionEnterTrigger";
  48608. case 12: return "OnIntersectionExitTrigger";
  48609. case 13: return "OnKeyDownTrigger";
  48610. case 14: return "OnKeyUpTrigger";
  48611. case 15: return "OnPickOutTrigger";
  48612. default: return "";
  48613. }
  48614. };
  48615. // Statics
  48616. ActionManager._NothingTrigger = 0;
  48617. ActionManager._OnPickTrigger = 1;
  48618. ActionManager._OnLeftPickTrigger = 2;
  48619. ActionManager._OnRightPickTrigger = 3;
  48620. ActionManager._OnCenterPickTrigger = 4;
  48621. ActionManager._OnPickDownTrigger = 5;
  48622. ActionManager._OnDoublePickTrigger = 6;
  48623. ActionManager._OnPickUpTrigger = 7;
  48624. ActionManager._OnLongPressTrigger = 8;
  48625. ActionManager._OnPointerOverTrigger = 9;
  48626. ActionManager._OnPointerOutTrigger = 10;
  48627. ActionManager._OnEveryFrameTrigger = 11;
  48628. ActionManager._OnIntersectionEnterTrigger = 12;
  48629. ActionManager._OnIntersectionExitTrigger = 13;
  48630. ActionManager._OnKeyDownTrigger = 14;
  48631. ActionManager._OnKeyUpTrigger = 15;
  48632. ActionManager._OnPickOutTrigger = 16;
  48633. ActionManager.Triggers = {};
  48634. return ActionManager;
  48635. }());
  48636. BABYLON.ActionManager = ActionManager;
  48637. })(BABYLON || (BABYLON = {}));
  48638. //# sourceMappingURL=babylon.actionManager.js.map
  48639. var BABYLON;
  48640. (function (BABYLON) {
  48641. var InterpolateValueAction = /** @class */ (function (_super) {
  48642. __extends(InterpolateValueAction, _super);
  48643. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48644. if (duration === void 0) { duration = 1000; }
  48645. var _this = _super.call(this, triggerOptions, condition) || this;
  48646. _this.propertyPath = propertyPath;
  48647. _this.value = value;
  48648. _this.duration = duration;
  48649. _this.stopOtherAnimations = stopOtherAnimations;
  48650. _this.onInterpolationDone = onInterpolationDone;
  48651. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48652. _this._target = _this._effectiveTarget = target;
  48653. return _this;
  48654. }
  48655. InterpolateValueAction.prototype._prepare = function () {
  48656. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48657. this._property = this._getProperty(this.propertyPath);
  48658. };
  48659. InterpolateValueAction.prototype.execute = function () {
  48660. var _this = this;
  48661. var scene = this._actionManager.getScene();
  48662. var keys = [
  48663. {
  48664. frame: 0,
  48665. value: this._effectiveTarget[this._property]
  48666. }, {
  48667. frame: 100,
  48668. value: this.value
  48669. }
  48670. ];
  48671. var dataType;
  48672. if (typeof this.value === "number") {
  48673. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48674. }
  48675. else if (this.value instanceof BABYLON.Color3) {
  48676. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48677. }
  48678. else if (this.value instanceof BABYLON.Vector3) {
  48679. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48680. }
  48681. else if (this.value instanceof BABYLON.Matrix) {
  48682. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48683. }
  48684. else if (this.value instanceof BABYLON.Quaternion) {
  48685. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48686. }
  48687. else {
  48688. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48689. return;
  48690. }
  48691. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48692. animation.setKeys(keys);
  48693. if (this.stopOtherAnimations) {
  48694. scene.stopAnimation(this._effectiveTarget);
  48695. }
  48696. var wrapper = function () {
  48697. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48698. if (_this.onInterpolationDone) {
  48699. _this.onInterpolationDone();
  48700. }
  48701. };
  48702. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48703. };
  48704. InterpolateValueAction.prototype.serialize = function (parent) {
  48705. return _super.prototype._serialize.call(this, {
  48706. name: "InterpolateValueAction",
  48707. properties: [
  48708. BABYLON.Action._GetTargetProperty(this._target),
  48709. { name: "propertyPath", value: this.propertyPath },
  48710. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48711. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48712. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48713. ]
  48714. }, parent);
  48715. };
  48716. return InterpolateValueAction;
  48717. }(BABYLON.Action));
  48718. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48719. })(BABYLON || (BABYLON = {}));
  48720. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48721. var BABYLON;
  48722. (function (BABYLON) {
  48723. var SwitchBooleanAction = /** @class */ (function (_super) {
  48724. __extends(SwitchBooleanAction, _super);
  48725. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48726. var _this = _super.call(this, triggerOptions, condition) || this;
  48727. _this.propertyPath = propertyPath;
  48728. _this._target = _this._effectiveTarget = target;
  48729. return _this;
  48730. }
  48731. SwitchBooleanAction.prototype._prepare = function () {
  48732. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48733. this._property = this._getProperty(this.propertyPath);
  48734. };
  48735. SwitchBooleanAction.prototype.execute = function () {
  48736. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48737. };
  48738. SwitchBooleanAction.prototype.serialize = function (parent) {
  48739. return _super.prototype._serialize.call(this, {
  48740. name: "SwitchBooleanAction",
  48741. properties: [
  48742. BABYLON.Action._GetTargetProperty(this._target),
  48743. { name: "propertyPath", value: this.propertyPath }
  48744. ]
  48745. }, parent);
  48746. };
  48747. return SwitchBooleanAction;
  48748. }(BABYLON.Action));
  48749. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48750. var SetStateAction = /** @class */ (function (_super) {
  48751. __extends(SetStateAction, _super);
  48752. function SetStateAction(triggerOptions, target, value, condition) {
  48753. var _this = _super.call(this, triggerOptions, condition) || this;
  48754. _this.value = value;
  48755. _this._target = target;
  48756. return _this;
  48757. }
  48758. SetStateAction.prototype.execute = function () {
  48759. this._target.state = this.value;
  48760. };
  48761. SetStateAction.prototype.serialize = function (parent) {
  48762. return _super.prototype._serialize.call(this, {
  48763. name: "SetStateAction",
  48764. properties: [
  48765. BABYLON.Action._GetTargetProperty(this._target),
  48766. { name: "value", value: this.value }
  48767. ]
  48768. }, parent);
  48769. };
  48770. return SetStateAction;
  48771. }(BABYLON.Action));
  48772. BABYLON.SetStateAction = SetStateAction;
  48773. var SetValueAction = /** @class */ (function (_super) {
  48774. __extends(SetValueAction, _super);
  48775. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48776. var _this = _super.call(this, triggerOptions, condition) || this;
  48777. _this.propertyPath = propertyPath;
  48778. _this.value = value;
  48779. _this._target = _this._effectiveTarget = target;
  48780. return _this;
  48781. }
  48782. SetValueAction.prototype._prepare = function () {
  48783. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48784. this._property = this._getProperty(this.propertyPath);
  48785. };
  48786. SetValueAction.prototype.execute = function () {
  48787. this._effectiveTarget[this._property] = this.value;
  48788. if (this._target.markAsDirty) {
  48789. this._target.markAsDirty(this._property);
  48790. }
  48791. };
  48792. SetValueAction.prototype.serialize = function (parent) {
  48793. return _super.prototype._serialize.call(this, {
  48794. name: "SetValueAction",
  48795. properties: [
  48796. BABYLON.Action._GetTargetProperty(this._target),
  48797. { name: "propertyPath", value: this.propertyPath },
  48798. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48799. ]
  48800. }, parent);
  48801. };
  48802. return SetValueAction;
  48803. }(BABYLON.Action));
  48804. BABYLON.SetValueAction = SetValueAction;
  48805. var IncrementValueAction = /** @class */ (function (_super) {
  48806. __extends(IncrementValueAction, _super);
  48807. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48808. var _this = _super.call(this, triggerOptions, condition) || this;
  48809. _this.propertyPath = propertyPath;
  48810. _this.value = value;
  48811. _this._target = _this._effectiveTarget = target;
  48812. return _this;
  48813. }
  48814. IncrementValueAction.prototype._prepare = function () {
  48815. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48816. this._property = this._getProperty(this.propertyPath);
  48817. if (typeof this._effectiveTarget[this._property] !== "number") {
  48818. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48819. }
  48820. };
  48821. IncrementValueAction.prototype.execute = function () {
  48822. this._effectiveTarget[this._property] += this.value;
  48823. if (this._target.markAsDirty) {
  48824. this._target.markAsDirty(this._property);
  48825. }
  48826. };
  48827. IncrementValueAction.prototype.serialize = function (parent) {
  48828. return _super.prototype._serialize.call(this, {
  48829. name: "IncrementValueAction",
  48830. properties: [
  48831. BABYLON.Action._GetTargetProperty(this._target),
  48832. { name: "propertyPath", value: this.propertyPath },
  48833. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48834. ]
  48835. }, parent);
  48836. };
  48837. return IncrementValueAction;
  48838. }(BABYLON.Action));
  48839. BABYLON.IncrementValueAction = IncrementValueAction;
  48840. var PlayAnimationAction = /** @class */ (function (_super) {
  48841. __extends(PlayAnimationAction, _super);
  48842. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48843. var _this = _super.call(this, triggerOptions, condition) || this;
  48844. _this.from = from;
  48845. _this.to = to;
  48846. _this.loop = loop;
  48847. _this._target = target;
  48848. return _this;
  48849. }
  48850. PlayAnimationAction.prototype._prepare = function () {
  48851. };
  48852. PlayAnimationAction.prototype.execute = function () {
  48853. var scene = this._actionManager.getScene();
  48854. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48855. };
  48856. PlayAnimationAction.prototype.serialize = function (parent) {
  48857. return _super.prototype._serialize.call(this, {
  48858. name: "PlayAnimationAction",
  48859. properties: [
  48860. BABYLON.Action._GetTargetProperty(this._target),
  48861. { name: "from", value: String(this.from) },
  48862. { name: "to", value: String(this.to) },
  48863. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48864. ]
  48865. }, parent);
  48866. };
  48867. return PlayAnimationAction;
  48868. }(BABYLON.Action));
  48869. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48870. var StopAnimationAction = /** @class */ (function (_super) {
  48871. __extends(StopAnimationAction, _super);
  48872. function StopAnimationAction(triggerOptions, target, condition) {
  48873. var _this = _super.call(this, triggerOptions, condition) || this;
  48874. _this._target = target;
  48875. return _this;
  48876. }
  48877. StopAnimationAction.prototype._prepare = function () {
  48878. };
  48879. StopAnimationAction.prototype.execute = function () {
  48880. var scene = this._actionManager.getScene();
  48881. scene.stopAnimation(this._target);
  48882. };
  48883. StopAnimationAction.prototype.serialize = function (parent) {
  48884. return _super.prototype._serialize.call(this, {
  48885. name: "StopAnimationAction",
  48886. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48887. }, parent);
  48888. };
  48889. return StopAnimationAction;
  48890. }(BABYLON.Action));
  48891. BABYLON.StopAnimationAction = StopAnimationAction;
  48892. var DoNothingAction = /** @class */ (function (_super) {
  48893. __extends(DoNothingAction, _super);
  48894. function DoNothingAction(triggerOptions, condition) {
  48895. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48896. return _super.call(this, triggerOptions, condition) || this;
  48897. }
  48898. DoNothingAction.prototype.execute = function () {
  48899. };
  48900. DoNothingAction.prototype.serialize = function (parent) {
  48901. return _super.prototype._serialize.call(this, {
  48902. name: "DoNothingAction",
  48903. properties: []
  48904. }, parent);
  48905. };
  48906. return DoNothingAction;
  48907. }(BABYLON.Action));
  48908. BABYLON.DoNothingAction = DoNothingAction;
  48909. var CombineAction = /** @class */ (function (_super) {
  48910. __extends(CombineAction, _super);
  48911. function CombineAction(triggerOptions, children, condition) {
  48912. var _this = _super.call(this, triggerOptions, condition) || this;
  48913. _this.children = children;
  48914. return _this;
  48915. }
  48916. CombineAction.prototype._prepare = function () {
  48917. for (var index = 0; index < this.children.length; index++) {
  48918. this.children[index]._actionManager = this._actionManager;
  48919. this.children[index]._prepare();
  48920. }
  48921. };
  48922. CombineAction.prototype.execute = function (evt) {
  48923. for (var index = 0; index < this.children.length; index++) {
  48924. this.children[index].execute(evt);
  48925. }
  48926. };
  48927. CombineAction.prototype.serialize = function (parent) {
  48928. var serializationObject = _super.prototype._serialize.call(this, {
  48929. name: "CombineAction",
  48930. properties: [],
  48931. combine: []
  48932. }, parent);
  48933. for (var i = 0; i < this.children.length; i++) {
  48934. serializationObject.combine.push(this.children[i].serialize(null));
  48935. }
  48936. return serializationObject;
  48937. };
  48938. return CombineAction;
  48939. }(BABYLON.Action));
  48940. BABYLON.CombineAction = CombineAction;
  48941. var ExecuteCodeAction = /** @class */ (function (_super) {
  48942. __extends(ExecuteCodeAction, _super);
  48943. function ExecuteCodeAction(triggerOptions, func, condition) {
  48944. var _this = _super.call(this, triggerOptions, condition) || this;
  48945. _this.func = func;
  48946. return _this;
  48947. }
  48948. ExecuteCodeAction.prototype.execute = function (evt) {
  48949. this.func(evt);
  48950. };
  48951. return ExecuteCodeAction;
  48952. }(BABYLON.Action));
  48953. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48954. var SetParentAction = /** @class */ (function (_super) {
  48955. __extends(SetParentAction, _super);
  48956. function SetParentAction(triggerOptions, target, parent, condition) {
  48957. var _this = _super.call(this, triggerOptions, condition) || this;
  48958. _this._target = target;
  48959. _this._parent = parent;
  48960. return _this;
  48961. }
  48962. SetParentAction.prototype._prepare = function () {
  48963. };
  48964. SetParentAction.prototype.execute = function () {
  48965. if (this._target.parent === this._parent) {
  48966. return;
  48967. }
  48968. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48969. invertParentWorldMatrix.invert();
  48970. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48971. this._target.parent = this._parent;
  48972. };
  48973. SetParentAction.prototype.serialize = function (parent) {
  48974. return _super.prototype._serialize.call(this, {
  48975. name: "SetParentAction",
  48976. properties: [
  48977. BABYLON.Action._GetTargetProperty(this._target),
  48978. BABYLON.Action._GetTargetProperty(this._parent),
  48979. ]
  48980. }, parent);
  48981. };
  48982. return SetParentAction;
  48983. }(BABYLON.Action));
  48984. BABYLON.SetParentAction = SetParentAction;
  48985. var PlaySoundAction = /** @class */ (function (_super) {
  48986. __extends(PlaySoundAction, _super);
  48987. function PlaySoundAction(triggerOptions, sound, condition) {
  48988. var _this = _super.call(this, triggerOptions, condition) || this;
  48989. _this._sound = sound;
  48990. return _this;
  48991. }
  48992. PlaySoundAction.prototype._prepare = function () {
  48993. };
  48994. PlaySoundAction.prototype.execute = function () {
  48995. if (this._sound !== undefined)
  48996. this._sound.play();
  48997. };
  48998. PlaySoundAction.prototype.serialize = function (parent) {
  48999. return _super.prototype._serialize.call(this, {
  49000. name: "PlaySoundAction",
  49001. properties: [{ name: "sound", value: this._sound.name }]
  49002. }, parent);
  49003. };
  49004. return PlaySoundAction;
  49005. }(BABYLON.Action));
  49006. BABYLON.PlaySoundAction = PlaySoundAction;
  49007. var StopSoundAction = /** @class */ (function (_super) {
  49008. __extends(StopSoundAction, _super);
  49009. function StopSoundAction(triggerOptions, sound, condition) {
  49010. var _this = _super.call(this, triggerOptions, condition) || this;
  49011. _this._sound = sound;
  49012. return _this;
  49013. }
  49014. StopSoundAction.prototype._prepare = function () {
  49015. };
  49016. StopSoundAction.prototype.execute = function () {
  49017. if (this._sound !== undefined)
  49018. this._sound.stop();
  49019. };
  49020. StopSoundAction.prototype.serialize = function (parent) {
  49021. return _super.prototype._serialize.call(this, {
  49022. name: "StopSoundAction",
  49023. properties: [{ name: "sound", value: this._sound.name }]
  49024. }, parent);
  49025. };
  49026. return StopSoundAction;
  49027. }(BABYLON.Action));
  49028. BABYLON.StopSoundAction = StopSoundAction;
  49029. })(BABYLON || (BABYLON = {}));
  49030. //# sourceMappingURL=babylon.directActions.js.map
  49031. var BABYLON;
  49032. (function (BABYLON) {
  49033. var SpriteManager = /** @class */ (function () {
  49034. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49035. if (epsilon === void 0) { epsilon = 0.01; }
  49036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49037. this.name = name;
  49038. this.sprites = new Array();
  49039. this.renderingGroupId = 0;
  49040. this.layerMask = 0x0FFFFFFF;
  49041. this.fogEnabled = true;
  49042. this.isPickable = false;
  49043. /**
  49044. * An event triggered when the manager is disposed.
  49045. * @type {BABYLON.Observable}
  49046. */
  49047. this.onDisposeObservable = new BABYLON.Observable();
  49048. this._vertexBuffers = {};
  49049. this._capacity = capacity;
  49050. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49051. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49052. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49053. if (cellSize.width && cellSize.height) {
  49054. this.cellWidth = cellSize.width;
  49055. this.cellHeight = cellSize.height;
  49056. }
  49057. else if (cellSize !== undefined) {
  49058. this.cellWidth = cellSize;
  49059. this.cellHeight = cellSize;
  49060. }
  49061. else {
  49062. return;
  49063. }
  49064. this._epsilon = epsilon;
  49065. this._scene = scene;
  49066. this._scene.spriteManagers.push(this);
  49067. var indices = [];
  49068. var index = 0;
  49069. for (var count = 0; count < capacity; count++) {
  49070. indices.push(index);
  49071. indices.push(index + 1);
  49072. indices.push(index + 2);
  49073. indices.push(index);
  49074. indices.push(index + 2);
  49075. indices.push(index + 3);
  49076. index += 4;
  49077. }
  49078. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49079. // VBO
  49080. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49081. this._vertexData = new Float32Array(capacity * 16 * 4);
  49082. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49083. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49084. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49085. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49086. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49088. this._vertexBuffers["options"] = options;
  49089. this._vertexBuffers["cellInfo"] = cellInfo;
  49090. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49091. // Effects
  49092. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49093. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49094. }
  49095. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49096. set: function (callback) {
  49097. if (this._onDisposeObserver) {
  49098. this.onDisposeObservable.remove(this._onDisposeObserver);
  49099. }
  49100. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49101. },
  49102. enumerable: true,
  49103. configurable: true
  49104. });
  49105. Object.defineProperty(SpriteManager.prototype, "texture", {
  49106. get: function () {
  49107. return this._spriteTexture;
  49108. },
  49109. set: function (value) {
  49110. this._spriteTexture = value;
  49111. },
  49112. enumerable: true,
  49113. configurable: true
  49114. });
  49115. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49116. var arrayOffset = index * 16;
  49117. if (offsetX === 0)
  49118. offsetX = this._epsilon;
  49119. else if (offsetX === 1)
  49120. offsetX = 1 - this._epsilon;
  49121. if (offsetY === 0)
  49122. offsetY = this._epsilon;
  49123. else if (offsetY === 1)
  49124. offsetY = 1 - this._epsilon;
  49125. this._vertexData[arrayOffset] = sprite.position.x;
  49126. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49127. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49128. this._vertexData[arrayOffset + 3] = sprite.angle;
  49129. this._vertexData[arrayOffset + 4] = sprite.width;
  49130. this._vertexData[arrayOffset + 5] = sprite.height;
  49131. this._vertexData[arrayOffset + 6] = offsetX;
  49132. this._vertexData[arrayOffset + 7] = offsetY;
  49133. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49134. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49135. var offset = (sprite.cellIndex / rowSize) >> 0;
  49136. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49137. this._vertexData[arrayOffset + 11] = offset;
  49138. // Color
  49139. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49140. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49141. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49142. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49143. };
  49144. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49145. var count = Math.min(this._capacity, this.sprites.length);
  49146. var min = BABYLON.Vector3.Zero();
  49147. var max = BABYLON.Vector3.Zero();
  49148. var distance = Number.MAX_VALUE;
  49149. var currentSprite = null;
  49150. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49151. var cameraView = camera.getViewMatrix();
  49152. for (var index = 0; index < count; index++) {
  49153. var sprite = this.sprites[index];
  49154. if (!sprite) {
  49155. continue;
  49156. }
  49157. if (predicate) {
  49158. if (!predicate(sprite)) {
  49159. continue;
  49160. }
  49161. }
  49162. else if (!sprite.isPickable) {
  49163. continue;
  49164. }
  49165. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49166. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49167. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49168. if (ray.intersectsBoxMinMax(min, max)) {
  49169. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49170. if (distance > currentDistance) {
  49171. distance = currentDistance;
  49172. currentSprite = sprite;
  49173. if (fastCheck) {
  49174. break;
  49175. }
  49176. }
  49177. }
  49178. }
  49179. if (currentSprite) {
  49180. var result = new BABYLON.PickingInfo();
  49181. result.hit = true;
  49182. result.pickedSprite = currentSprite;
  49183. result.distance = distance;
  49184. return result;
  49185. }
  49186. return null;
  49187. };
  49188. SpriteManager.prototype.render = function () {
  49189. // Check
  49190. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49191. return;
  49192. var engine = this._scene.getEngine();
  49193. var baseSize = this._spriteTexture.getBaseSize();
  49194. // Sprites
  49195. var deltaTime = engine.getDeltaTime();
  49196. var max = Math.min(this._capacity, this.sprites.length);
  49197. var rowSize = baseSize.width / this.cellWidth;
  49198. var offset = 0;
  49199. for (var index = 0; index < max; index++) {
  49200. var sprite = this.sprites[index];
  49201. if (!sprite) {
  49202. continue;
  49203. }
  49204. sprite._animate(deltaTime);
  49205. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49206. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49207. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49208. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49209. }
  49210. this._buffer.update(this._vertexData);
  49211. // Render
  49212. var effect = this._effectBase;
  49213. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49214. effect = this._effectFog;
  49215. }
  49216. engine.enableEffect(effect);
  49217. var viewMatrix = this._scene.getViewMatrix();
  49218. effect.setTexture("diffuseSampler", this._spriteTexture);
  49219. effect.setMatrix("view", viewMatrix);
  49220. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49221. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49222. // Fog
  49223. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49224. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49225. effect.setColor3("vFogColor", this._scene.fogColor);
  49226. }
  49227. // VBOs
  49228. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49229. // Draw order
  49230. engine.setDepthFunctionToLessOrEqual();
  49231. effect.setBool("alphaTest", true);
  49232. engine.setColorWrite(false);
  49233. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49234. engine.setColorWrite(true);
  49235. effect.setBool("alphaTest", false);
  49236. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49237. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49238. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49239. };
  49240. SpriteManager.prototype.dispose = function () {
  49241. if (this._buffer) {
  49242. this._buffer.dispose();
  49243. this._buffer = null;
  49244. }
  49245. if (this._indexBuffer) {
  49246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49247. this._indexBuffer = null;
  49248. }
  49249. if (this._spriteTexture) {
  49250. this._spriteTexture.dispose();
  49251. this._spriteTexture = null;
  49252. }
  49253. // Remove from scene
  49254. var index = this._scene.spriteManagers.indexOf(this);
  49255. this._scene.spriteManagers.splice(index, 1);
  49256. // Callback
  49257. this.onDisposeObservable.notifyObservers(this);
  49258. this.onDisposeObservable.clear();
  49259. };
  49260. return SpriteManager;
  49261. }());
  49262. BABYLON.SpriteManager = SpriteManager;
  49263. })(BABYLON || (BABYLON = {}));
  49264. //# sourceMappingURL=babylon.spriteManager.js.map
  49265. var BABYLON;
  49266. (function (BABYLON) {
  49267. var Sprite = /** @class */ (function () {
  49268. function Sprite(name, manager) {
  49269. this.name = name;
  49270. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49271. this.width = 1.0;
  49272. this.height = 1.0;
  49273. this.angle = 0;
  49274. this.cellIndex = 0;
  49275. this.invertU = 0;
  49276. this.invertV = 0;
  49277. this.animations = new Array();
  49278. this.isPickable = false;
  49279. this._animationStarted = false;
  49280. this._loopAnimation = false;
  49281. this._fromIndex = 0;
  49282. this._toIndex = 0;
  49283. this._delay = 0;
  49284. this._direction = 1;
  49285. this._time = 0;
  49286. this._manager = manager;
  49287. this._manager.sprites.push(this);
  49288. this.position = BABYLON.Vector3.Zero();
  49289. }
  49290. Object.defineProperty(Sprite.prototype, "size", {
  49291. get: function () {
  49292. return this.width;
  49293. },
  49294. set: function (value) {
  49295. this.width = value;
  49296. this.height = value;
  49297. },
  49298. enumerable: true,
  49299. configurable: true
  49300. });
  49301. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49302. this._fromIndex = from;
  49303. this._toIndex = to;
  49304. this._loopAnimation = loop;
  49305. this._delay = delay;
  49306. this._animationStarted = true;
  49307. this._direction = from < to ? 1 : -1;
  49308. this.cellIndex = from;
  49309. this._time = 0;
  49310. this._onAnimationEnd = onAnimationEnd;
  49311. };
  49312. Sprite.prototype.stopAnimation = function () {
  49313. this._animationStarted = false;
  49314. };
  49315. Sprite.prototype._animate = function (deltaTime) {
  49316. if (!this._animationStarted)
  49317. return;
  49318. this._time += deltaTime;
  49319. if (this._time > this._delay) {
  49320. this._time = this._time % this._delay;
  49321. this.cellIndex += this._direction;
  49322. if (this.cellIndex > this._toIndex) {
  49323. if (this._loopAnimation) {
  49324. this.cellIndex = this._fromIndex;
  49325. }
  49326. else {
  49327. this.cellIndex = this._toIndex;
  49328. this._animationStarted = false;
  49329. if (this._onAnimationEnd) {
  49330. this._onAnimationEnd();
  49331. }
  49332. if (this.disposeWhenFinishedAnimating) {
  49333. this.dispose();
  49334. }
  49335. }
  49336. }
  49337. }
  49338. };
  49339. Sprite.prototype.dispose = function () {
  49340. for (var i = 0; i < this._manager.sprites.length; i++) {
  49341. if (this._manager.sprites[i] == this) {
  49342. this._manager.sprites.splice(i, 1);
  49343. }
  49344. }
  49345. };
  49346. return Sprite;
  49347. }());
  49348. BABYLON.Sprite = Sprite;
  49349. })(BABYLON || (BABYLON = {}));
  49350. //# sourceMappingURL=babylon.sprite.js.map
  49351. var BABYLON;
  49352. (function (BABYLON) {
  49353. var IntersectionInfo = /** @class */ (function () {
  49354. function IntersectionInfo(bu, bv, distance) {
  49355. this.bu = bu;
  49356. this.bv = bv;
  49357. this.distance = distance;
  49358. this.faceId = 0;
  49359. this.subMeshId = 0;
  49360. }
  49361. return IntersectionInfo;
  49362. }());
  49363. BABYLON.IntersectionInfo = IntersectionInfo;
  49364. var PickingInfo = /** @class */ (function () {
  49365. function PickingInfo() {
  49366. this.hit = false;
  49367. this.distance = 0;
  49368. this.pickedPoint = null;
  49369. this.pickedMesh = null;
  49370. this.bu = 0;
  49371. this.bv = 0;
  49372. this.faceId = -1;
  49373. this.subMeshId = 0;
  49374. this.pickedSprite = null;
  49375. }
  49376. // Methods
  49377. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49378. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49379. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49380. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49381. return null;
  49382. }
  49383. var indices = this.pickedMesh.getIndices();
  49384. if (!indices) {
  49385. return null;
  49386. }
  49387. var result;
  49388. if (useVerticesNormals) {
  49389. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49390. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49391. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49392. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49393. normal0 = normal0.scale(this.bu);
  49394. normal1 = normal1.scale(this.bv);
  49395. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49396. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49397. }
  49398. else {
  49399. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49400. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49401. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49402. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49403. var p1p2 = vertex1.subtract(vertex2);
  49404. var p3p2 = vertex3.subtract(vertex2);
  49405. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49406. }
  49407. if (useWorldCoordinates) {
  49408. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49409. }
  49410. return BABYLON.Vector3.Normalize(result);
  49411. };
  49412. PickingInfo.prototype.getTextureCoordinates = function () {
  49413. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49414. return null;
  49415. }
  49416. var indices = this.pickedMesh.getIndices();
  49417. if (!indices) {
  49418. return null;
  49419. }
  49420. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49421. if (!uvs) {
  49422. return null;
  49423. }
  49424. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49425. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49426. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49427. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49428. uv1 = uv1.scale(this.bu);
  49429. uv2 = uv2.scale(this.bv);
  49430. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49431. };
  49432. return PickingInfo;
  49433. }());
  49434. BABYLON.PickingInfo = PickingInfo;
  49435. })(BABYLON || (BABYLON = {}));
  49436. //# sourceMappingURL=babylon.pickingInfo.js.map
  49437. var BABYLON;
  49438. (function (BABYLON) {
  49439. var Ray = /** @class */ (function () {
  49440. function Ray(origin, direction, length) {
  49441. if (length === void 0) { length = Number.MAX_VALUE; }
  49442. this.origin = origin;
  49443. this.direction = direction;
  49444. this.length = length;
  49445. }
  49446. // Methods
  49447. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49448. var d = 0.0;
  49449. var maxValue = Number.MAX_VALUE;
  49450. var inv;
  49451. var min;
  49452. var max;
  49453. var temp;
  49454. if (Math.abs(this.direction.x) < 0.0000001) {
  49455. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49456. return false;
  49457. }
  49458. }
  49459. else {
  49460. inv = 1.0 / this.direction.x;
  49461. min = (minimum.x - this.origin.x) * inv;
  49462. max = (maximum.x - this.origin.x) * inv;
  49463. if (max === -Infinity) {
  49464. max = Infinity;
  49465. }
  49466. if (min > max) {
  49467. temp = min;
  49468. min = max;
  49469. max = temp;
  49470. }
  49471. d = Math.max(min, d);
  49472. maxValue = Math.min(max, maxValue);
  49473. if (d > maxValue) {
  49474. return false;
  49475. }
  49476. }
  49477. if (Math.abs(this.direction.y) < 0.0000001) {
  49478. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49479. return false;
  49480. }
  49481. }
  49482. else {
  49483. inv = 1.0 / this.direction.y;
  49484. min = (minimum.y - this.origin.y) * inv;
  49485. max = (maximum.y - this.origin.y) * inv;
  49486. if (max === -Infinity) {
  49487. max = Infinity;
  49488. }
  49489. if (min > max) {
  49490. temp = min;
  49491. min = max;
  49492. max = temp;
  49493. }
  49494. d = Math.max(min, d);
  49495. maxValue = Math.min(max, maxValue);
  49496. if (d > maxValue) {
  49497. return false;
  49498. }
  49499. }
  49500. if (Math.abs(this.direction.z) < 0.0000001) {
  49501. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49502. return false;
  49503. }
  49504. }
  49505. else {
  49506. inv = 1.0 / this.direction.z;
  49507. min = (minimum.z - this.origin.z) * inv;
  49508. max = (maximum.z - this.origin.z) * inv;
  49509. if (max === -Infinity) {
  49510. max = Infinity;
  49511. }
  49512. if (min > max) {
  49513. temp = min;
  49514. min = max;
  49515. max = temp;
  49516. }
  49517. d = Math.max(min, d);
  49518. maxValue = Math.min(max, maxValue);
  49519. if (d > maxValue) {
  49520. return false;
  49521. }
  49522. }
  49523. return true;
  49524. };
  49525. Ray.prototype.intersectsBox = function (box) {
  49526. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49527. };
  49528. Ray.prototype.intersectsSphere = function (sphere) {
  49529. var x = sphere.center.x - this.origin.x;
  49530. var y = sphere.center.y - this.origin.y;
  49531. var z = sphere.center.z - this.origin.z;
  49532. var pyth = (x * x) + (y * y) + (z * z);
  49533. var rr = sphere.radius * sphere.radius;
  49534. if (pyth <= rr) {
  49535. return true;
  49536. }
  49537. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49538. if (dot < 0.0) {
  49539. return false;
  49540. }
  49541. var temp = pyth - (dot * dot);
  49542. return temp <= rr;
  49543. };
  49544. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49545. if (!this._edge1) {
  49546. this._edge1 = BABYLON.Vector3.Zero();
  49547. this._edge2 = BABYLON.Vector3.Zero();
  49548. this._pvec = BABYLON.Vector3.Zero();
  49549. this._tvec = BABYLON.Vector3.Zero();
  49550. this._qvec = BABYLON.Vector3.Zero();
  49551. }
  49552. vertex1.subtractToRef(vertex0, this._edge1);
  49553. vertex2.subtractToRef(vertex0, this._edge2);
  49554. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49555. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49556. if (det === 0) {
  49557. return null;
  49558. }
  49559. var invdet = 1 / det;
  49560. this.origin.subtractToRef(vertex0, this._tvec);
  49561. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49562. if (bu < 0 || bu > 1.0) {
  49563. return null;
  49564. }
  49565. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49566. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49567. if (bv < 0 || bu + bv > 1.0) {
  49568. return null;
  49569. }
  49570. //check if the distance is longer than the predefined length.
  49571. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49572. if (distance > this.length) {
  49573. return null;
  49574. }
  49575. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49576. };
  49577. Ray.prototype.intersectsPlane = function (plane) {
  49578. var distance;
  49579. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49580. if (Math.abs(result1) < 9.99999997475243E-07) {
  49581. return null;
  49582. }
  49583. else {
  49584. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49585. distance = (-plane.d - result2) / result1;
  49586. if (distance < 0.0) {
  49587. if (distance < -9.99999997475243E-07) {
  49588. return null;
  49589. }
  49590. else {
  49591. return 0;
  49592. }
  49593. }
  49594. return distance;
  49595. }
  49596. };
  49597. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49598. var tm = BABYLON.Tmp.Matrix[0];
  49599. mesh.getWorldMatrix().invertToRef(tm);
  49600. if (this._tmpRay) {
  49601. Ray.TransformToRef(this, tm, this._tmpRay);
  49602. }
  49603. else {
  49604. this._tmpRay = Ray.Transform(this, tm);
  49605. }
  49606. return mesh.intersects(this._tmpRay, fastCheck);
  49607. };
  49608. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49609. if (results) {
  49610. results.length = 0;
  49611. }
  49612. else {
  49613. results = [];
  49614. }
  49615. for (var i = 0; i < meshes.length; i++) {
  49616. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49617. if (pickInfo.hit) {
  49618. results.push(pickInfo);
  49619. }
  49620. }
  49621. results.sort(this._comparePickingInfo);
  49622. return results;
  49623. };
  49624. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49625. if (pickingInfoA.distance < pickingInfoB.distance) {
  49626. return -1;
  49627. }
  49628. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49629. return 1;
  49630. }
  49631. else {
  49632. return 0;
  49633. }
  49634. };
  49635. /**
  49636. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49637. * @param sega the first point of the segment to test the intersection against
  49638. * @param segb the second point of the segment to test the intersection against
  49639. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49640. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49641. */
  49642. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49643. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49644. var u = segb.subtract(sega);
  49645. var v = rsegb.subtract(this.origin);
  49646. var w = sega.subtract(this.origin);
  49647. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49648. var b = BABYLON.Vector3.Dot(u, v);
  49649. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49650. var d = BABYLON.Vector3.Dot(u, w);
  49651. var e = BABYLON.Vector3.Dot(v, w);
  49652. var D = a * c - b * b; // always >= 0
  49653. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49654. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49655. // compute the line parameters of the two closest points
  49656. if (D < Ray.smallnum) {
  49657. sN = 0.0; // force using point P0 on segment S1
  49658. sD = 1.0; // to prevent possible division by 0.0 later
  49659. tN = e;
  49660. tD = c;
  49661. }
  49662. else {
  49663. sN = (b * e - c * d);
  49664. tN = (a * e - b * d);
  49665. if (sN < 0.0) {
  49666. sN = 0.0;
  49667. tN = e;
  49668. tD = c;
  49669. }
  49670. else if (sN > sD) {
  49671. sN = sD;
  49672. tN = e + b;
  49673. tD = c;
  49674. }
  49675. }
  49676. if (tN < 0.0) {
  49677. tN = 0.0;
  49678. // recompute sc for this edge
  49679. if (-d < 0.0) {
  49680. sN = 0.0;
  49681. }
  49682. else if (-d > a)
  49683. sN = sD;
  49684. else {
  49685. sN = -d;
  49686. sD = a;
  49687. }
  49688. }
  49689. else if (tN > tD) {
  49690. tN = tD;
  49691. // recompute sc for this edge
  49692. if ((-d + b) < 0.0) {
  49693. sN = 0;
  49694. }
  49695. else if ((-d + b) > a) {
  49696. sN = sD;
  49697. }
  49698. else {
  49699. sN = (-d + b);
  49700. sD = a;
  49701. }
  49702. }
  49703. // finally do the division to get sc and tc
  49704. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49705. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49706. // get the difference of the two closest points
  49707. var qtc = v.multiplyByFloats(tc, tc, tc);
  49708. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49709. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49710. if (isIntersected) {
  49711. return qtc.length();
  49712. }
  49713. return -1;
  49714. };
  49715. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49716. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49717. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49718. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49719. this.direction.normalize();
  49720. return this;
  49721. };
  49722. // Statics
  49723. Ray.Zero = function () {
  49724. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49725. };
  49726. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49727. var result = Ray.Zero();
  49728. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49729. };
  49730. /**
  49731. * 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
  49732. * transformed to the given world matrix.
  49733. * @param origin The origin point
  49734. * @param end The end point
  49735. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49736. */
  49737. Ray.CreateNewFromTo = function (origin, end, world) {
  49738. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49739. var direction = end.subtract(origin);
  49740. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49741. direction.normalize();
  49742. return Ray.Transform(new Ray(origin, direction, length), world);
  49743. };
  49744. Ray.Transform = function (ray, matrix) {
  49745. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49746. Ray.TransformToRef(ray, matrix, result);
  49747. return result;
  49748. };
  49749. Ray.TransformToRef = function (ray, matrix, result) {
  49750. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49751. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49752. result.length = ray.length;
  49753. var dir = result.direction;
  49754. var len = dir.length();
  49755. if (!(len === 0 || len === 1)) {
  49756. var num = 1.0 / len;
  49757. dir.x *= num;
  49758. dir.y *= num;
  49759. dir.z *= num;
  49760. result.length *= len;
  49761. }
  49762. };
  49763. Ray.smallnum = 0.00000001;
  49764. Ray.rayl = 10e8;
  49765. return Ray;
  49766. }());
  49767. BABYLON.Ray = Ray;
  49768. })(BABYLON || (BABYLON = {}));
  49769. //# sourceMappingURL=babylon.ray.js.map
  49770. var BABYLON;
  49771. (function (BABYLON) {
  49772. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49773. if (boxMin.x > sphereCenter.x + sphereRadius)
  49774. return false;
  49775. if (sphereCenter.x - sphereRadius > boxMax.x)
  49776. return false;
  49777. if (boxMin.y > sphereCenter.y + sphereRadius)
  49778. return false;
  49779. if (sphereCenter.y - sphereRadius > boxMax.y)
  49780. return false;
  49781. if (boxMin.z > sphereCenter.z + sphereRadius)
  49782. return false;
  49783. if (sphereCenter.z - sphereRadius > boxMax.z)
  49784. return false;
  49785. return true;
  49786. };
  49787. var getLowestRoot = (function () {
  49788. var result = { root: 0, found: false };
  49789. return function (a, b, c, maxR) {
  49790. result.root = 0;
  49791. result.found = false;
  49792. var determinant = b * b - 4.0 * a * c;
  49793. if (determinant < 0)
  49794. return result;
  49795. var sqrtD = Math.sqrt(determinant);
  49796. var r1 = (-b - sqrtD) / (2.0 * a);
  49797. var r2 = (-b + sqrtD) / (2.0 * a);
  49798. if (r1 > r2) {
  49799. var temp = r2;
  49800. r2 = r1;
  49801. r1 = temp;
  49802. }
  49803. if (r1 > 0 && r1 < maxR) {
  49804. result.root = r1;
  49805. result.found = true;
  49806. return result;
  49807. }
  49808. if (r2 > 0 && r2 < maxR) {
  49809. result.root = r2;
  49810. result.found = true;
  49811. return result;
  49812. }
  49813. return result;
  49814. };
  49815. })();
  49816. var Collider = /** @class */ (function () {
  49817. function Collider() {
  49818. this._collisionPoint = BABYLON.Vector3.Zero();
  49819. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49820. this._tempVector = BABYLON.Vector3.Zero();
  49821. this._tempVector2 = BABYLON.Vector3.Zero();
  49822. this._tempVector3 = BABYLON.Vector3.Zero();
  49823. this._tempVector4 = BABYLON.Vector3.Zero();
  49824. this._edge = BABYLON.Vector3.Zero();
  49825. this._baseToVertex = BABYLON.Vector3.Zero();
  49826. this._destinationPoint = BABYLON.Vector3.Zero();
  49827. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49828. this._displacementVector = BABYLON.Vector3.Zero();
  49829. this._radius = BABYLON.Vector3.One();
  49830. this._retry = 0;
  49831. this._basePointWorld = BABYLON.Vector3.Zero();
  49832. this._velocityWorld = BABYLON.Vector3.Zero();
  49833. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49834. this._collisionMask = -1;
  49835. }
  49836. Object.defineProperty(Collider.prototype, "collisionMask", {
  49837. get: function () {
  49838. return this._collisionMask;
  49839. },
  49840. set: function (mask) {
  49841. this._collisionMask = !isNaN(mask) ? mask : -1;
  49842. },
  49843. enumerable: true,
  49844. configurable: true
  49845. });
  49846. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49847. /**
  49848. * Gets the plane normal used to compute the sliding response (in local space)
  49849. */
  49850. get: function () {
  49851. return this._slidePlaneNormal;
  49852. },
  49853. enumerable: true,
  49854. configurable: true
  49855. });
  49856. // Methods
  49857. Collider.prototype._initialize = function (source, dir, e) {
  49858. this._velocity = dir;
  49859. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49860. this._basePoint = source;
  49861. source.multiplyToRef(this._radius, this._basePointWorld);
  49862. dir.multiplyToRef(this._radius, this._velocityWorld);
  49863. this._velocityWorldLength = this._velocityWorld.length();
  49864. this._epsilon = e;
  49865. this.collisionFound = false;
  49866. };
  49867. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49868. pa.subtractToRef(point, this._tempVector);
  49869. pb.subtractToRef(point, this._tempVector2);
  49870. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49871. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49872. if (d < 0)
  49873. return false;
  49874. pc.subtractToRef(point, this._tempVector3);
  49875. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49876. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49877. if (d < 0)
  49878. return false;
  49879. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49880. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49881. return d >= 0;
  49882. };
  49883. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49884. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49885. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49886. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49887. return false;
  49888. }
  49889. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49890. return false;
  49891. return true;
  49892. };
  49893. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49894. var t0;
  49895. var embeddedInPlane = false;
  49896. //defensive programming, actually not needed.
  49897. if (!trianglePlaneArray) {
  49898. trianglePlaneArray = [];
  49899. }
  49900. if (!trianglePlaneArray[faceIndex]) {
  49901. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49902. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49903. }
  49904. var trianglePlane = trianglePlaneArray[faceIndex];
  49905. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49906. return;
  49907. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49908. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49909. if (normalDotVelocity == 0) {
  49910. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49911. return;
  49912. embeddedInPlane = true;
  49913. t0 = 0;
  49914. }
  49915. else {
  49916. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49917. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49918. if (t0 > t1) {
  49919. var temp = t1;
  49920. t1 = t0;
  49921. t0 = temp;
  49922. }
  49923. if (t0 > 1.0 || t1 < 0.0)
  49924. return;
  49925. if (t0 < 0)
  49926. t0 = 0;
  49927. if (t0 > 1.0)
  49928. t0 = 1.0;
  49929. }
  49930. this._collisionPoint.copyFromFloats(0, 0, 0);
  49931. var found = false;
  49932. var t = 1.0;
  49933. if (!embeddedInPlane) {
  49934. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49935. this._velocity.scaleToRef(t0, this._tempVector);
  49936. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49937. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49938. found = true;
  49939. t = t0;
  49940. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49941. }
  49942. }
  49943. if (!found) {
  49944. var velocitySquaredLength = this._velocity.lengthSquared();
  49945. var a = velocitySquaredLength;
  49946. this._basePoint.subtractToRef(p1, this._tempVector);
  49947. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49948. var c = this._tempVector.lengthSquared() - 1.0;
  49949. var lowestRoot = getLowestRoot(a, b, c, t);
  49950. if (lowestRoot.found) {
  49951. t = lowestRoot.root;
  49952. found = true;
  49953. this._collisionPoint.copyFrom(p1);
  49954. }
  49955. this._basePoint.subtractToRef(p2, this._tempVector);
  49956. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49957. c = this._tempVector.lengthSquared() - 1.0;
  49958. lowestRoot = getLowestRoot(a, b, c, t);
  49959. if (lowestRoot.found) {
  49960. t = lowestRoot.root;
  49961. found = true;
  49962. this._collisionPoint.copyFrom(p2);
  49963. }
  49964. this._basePoint.subtractToRef(p3, this._tempVector);
  49965. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49966. c = this._tempVector.lengthSquared() - 1.0;
  49967. lowestRoot = getLowestRoot(a, b, c, t);
  49968. if (lowestRoot.found) {
  49969. t = lowestRoot.root;
  49970. found = true;
  49971. this._collisionPoint.copyFrom(p3);
  49972. }
  49973. p2.subtractToRef(p1, this._edge);
  49974. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49975. var edgeSquaredLength = this._edge.lengthSquared();
  49976. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49977. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49978. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49979. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49980. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49981. lowestRoot = getLowestRoot(a, b, c, t);
  49982. if (lowestRoot.found) {
  49983. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49984. if (f >= 0.0 && f <= 1.0) {
  49985. t = lowestRoot.root;
  49986. found = true;
  49987. this._edge.scaleInPlace(f);
  49988. p1.addToRef(this._edge, this._collisionPoint);
  49989. }
  49990. }
  49991. p3.subtractToRef(p2, this._edge);
  49992. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49993. edgeSquaredLength = this._edge.lengthSquared();
  49994. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49995. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49996. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49997. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49998. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49999. lowestRoot = getLowestRoot(a, b, c, t);
  50000. if (lowestRoot.found) {
  50001. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50002. if (f >= 0.0 && f <= 1.0) {
  50003. t = lowestRoot.root;
  50004. found = true;
  50005. this._edge.scaleInPlace(f);
  50006. p2.addToRef(this._edge, this._collisionPoint);
  50007. }
  50008. }
  50009. p1.subtractToRef(p3, this._edge);
  50010. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50011. edgeSquaredLength = this._edge.lengthSquared();
  50012. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50013. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50014. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50015. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50016. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50017. lowestRoot = getLowestRoot(a, b, c, t);
  50018. if (lowestRoot.found) {
  50019. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50020. if (f >= 0.0 && f <= 1.0) {
  50021. t = lowestRoot.root;
  50022. found = true;
  50023. this._edge.scaleInPlace(f);
  50024. p3.addToRef(this._edge, this._collisionPoint);
  50025. }
  50026. }
  50027. }
  50028. if (found) {
  50029. var distToCollision = t * this._velocity.length();
  50030. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50031. if (!this.intersectionPoint) {
  50032. this.intersectionPoint = this._collisionPoint.clone();
  50033. }
  50034. else {
  50035. this.intersectionPoint.copyFrom(this._collisionPoint);
  50036. }
  50037. this._nearestDistance = distToCollision;
  50038. this.collisionFound = true;
  50039. }
  50040. }
  50041. };
  50042. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50043. for (var i = indexStart; i < indexEnd; i += 3) {
  50044. var p1 = pts[indices[i] - decal];
  50045. var p2 = pts[indices[i + 1] - decal];
  50046. var p3 = pts[indices[i + 2] - decal];
  50047. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50048. }
  50049. };
  50050. Collider.prototype._getResponse = function (pos, vel) {
  50051. pos.addToRef(vel, this._destinationPoint);
  50052. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50053. this._basePoint.addToRef(vel, pos);
  50054. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50055. this._slidePlaneNormal.normalize();
  50056. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50057. pos.addInPlace(this._displacementVector);
  50058. this.intersectionPoint.addInPlace(this._displacementVector);
  50059. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50060. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50061. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50062. };
  50063. return Collider;
  50064. }());
  50065. BABYLON.Collider = Collider;
  50066. })(BABYLON || (BABYLON = {}));
  50067. //# sourceMappingURL=babylon.collider.js.map
  50068. var BABYLON;
  50069. (function (BABYLON) {
  50070. //WebWorker code will be inserted to this variable.
  50071. BABYLON.CollisionWorker = "";
  50072. var WorkerTaskType;
  50073. (function (WorkerTaskType) {
  50074. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50075. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50076. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50077. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50078. var WorkerReplyType;
  50079. (function (WorkerReplyType) {
  50080. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50081. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50082. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50083. var CollisionCoordinatorWorker = /** @class */ (function () {
  50084. function CollisionCoordinatorWorker() {
  50085. var _this = this;
  50086. this._scaledPosition = BABYLON.Vector3.Zero();
  50087. this._scaledVelocity = BABYLON.Vector3.Zero();
  50088. this.onMeshUpdated = function (transformNode) {
  50089. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50090. };
  50091. this.onGeometryUpdated = function (geometry) {
  50092. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50093. };
  50094. this._afterRender = function () {
  50095. if (!_this._init)
  50096. return;
  50097. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50098. return;
  50099. }
  50100. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50101. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50102. if (_this._runningUpdated > 4) {
  50103. return;
  50104. }
  50105. ++_this._runningUpdated;
  50106. var payload = {
  50107. updatedMeshes: _this._addUpdateMeshesList,
  50108. updatedGeometries: _this._addUpdateGeometriesList,
  50109. removedGeometries: _this._toRemoveGeometryArray,
  50110. removedMeshes: _this._toRemoveMeshesArray
  50111. };
  50112. var message = {
  50113. payload: payload,
  50114. taskType: WorkerTaskType.UPDATE
  50115. };
  50116. var serializable = [];
  50117. for (var id in payload.updatedGeometries) {
  50118. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50119. //prepare transferables
  50120. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50121. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50122. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50123. }
  50124. }
  50125. _this._worker.postMessage(message, serializable);
  50126. _this._addUpdateMeshesList = {};
  50127. _this._addUpdateGeometriesList = {};
  50128. _this._toRemoveGeometryArray = [];
  50129. _this._toRemoveMeshesArray = [];
  50130. };
  50131. this._onMessageFromWorker = function (e) {
  50132. var returnData = e.data;
  50133. if (returnData.error != WorkerReplyType.SUCCESS) {
  50134. //TODO what errors can be returned from the worker?
  50135. BABYLON.Tools.Warn("error returned from worker!");
  50136. return;
  50137. }
  50138. switch (returnData.taskType) {
  50139. case WorkerTaskType.INIT:
  50140. _this._init = true;
  50141. //Update the worked with ALL of the scene's current state
  50142. _this._scene.meshes.forEach(function (mesh) {
  50143. _this.onMeshAdded(mesh);
  50144. });
  50145. _this._scene.getGeometries().forEach(function (geometry) {
  50146. _this.onGeometryAdded(geometry);
  50147. });
  50148. break;
  50149. case WorkerTaskType.UPDATE:
  50150. _this._runningUpdated--;
  50151. break;
  50152. case WorkerTaskType.COLLIDE:
  50153. var returnPayload = returnData.payload;
  50154. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50155. return;
  50156. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50157. if (callback) {
  50158. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50159. if (mesh) {
  50160. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50161. }
  50162. }
  50163. //cleanup
  50164. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50165. break;
  50166. }
  50167. };
  50168. this._collisionsCallbackArray = [];
  50169. this._init = false;
  50170. this._runningUpdated = 0;
  50171. this._addUpdateMeshesList = {};
  50172. this._addUpdateGeometriesList = {};
  50173. this._toRemoveGeometryArray = [];
  50174. this._toRemoveMeshesArray = [];
  50175. }
  50176. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50177. if (!this._init)
  50178. return;
  50179. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50180. return;
  50181. position.divideToRef(collider._radius, this._scaledPosition);
  50182. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50183. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50184. var payload = {
  50185. collider: {
  50186. position: this._scaledPosition.asArray(),
  50187. velocity: this._scaledVelocity.asArray(),
  50188. radius: collider._radius.asArray()
  50189. },
  50190. collisionId: collisionIndex,
  50191. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50192. maximumRetry: maximumRetry
  50193. };
  50194. var message = {
  50195. payload: payload,
  50196. taskType: WorkerTaskType.COLLIDE
  50197. };
  50198. this._worker.postMessage(message);
  50199. };
  50200. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50201. this._scene = scene;
  50202. this._scene.registerAfterRender(this._afterRender);
  50203. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50204. this._worker = new Worker(workerUrl);
  50205. this._worker.onmessage = this._onMessageFromWorker;
  50206. var message = {
  50207. payload: {},
  50208. taskType: WorkerTaskType.INIT
  50209. };
  50210. this._worker.postMessage(message);
  50211. };
  50212. CollisionCoordinatorWorker.prototype.destroy = function () {
  50213. this._scene.unregisterAfterRender(this._afterRender);
  50214. this._worker.terminate();
  50215. };
  50216. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50217. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50218. this.onMeshUpdated(mesh);
  50219. };
  50220. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50221. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50222. };
  50223. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50224. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50225. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50226. this.onGeometryUpdated(geometry);
  50227. };
  50228. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50229. this._toRemoveGeometryArray.push(geometry.id);
  50230. };
  50231. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50232. var submeshes = [];
  50233. if (mesh.subMeshes) {
  50234. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50235. var boundingInfo = sm.getBoundingInfo();
  50236. return {
  50237. position: idx,
  50238. verticesStart: sm.verticesStart,
  50239. verticesCount: sm.verticesCount,
  50240. indexStart: sm.indexStart,
  50241. indexCount: sm.indexCount,
  50242. hasMaterial: !!sm.getMaterial(),
  50243. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50244. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50245. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50246. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50247. };
  50248. });
  50249. }
  50250. var geometryId = null;
  50251. if (mesh instanceof BABYLON.Mesh) {
  50252. var geometry = mesh.geometry;
  50253. geometryId = geometry ? geometry.id : null;
  50254. }
  50255. else if (mesh instanceof BABYLON.InstancedMesh) {
  50256. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50257. geometryId = geometry ? geometry.id : null;
  50258. }
  50259. var boundingInfo = mesh.getBoundingInfo();
  50260. return {
  50261. uniqueId: mesh.uniqueId,
  50262. id: mesh.id,
  50263. name: mesh.name,
  50264. geometryId: geometryId,
  50265. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50266. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50267. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50268. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50269. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50270. subMeshes: submeshes,
  50271. checkCollisions: mesh.checkCollisions
  50272. };
  50273. };
  50274. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50275. return {
  50276. id: geometry.id,
  50277. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50278. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50279. indices: new Uint32Array(geometry.getIndices() || []),
  50280. };
  50281. };
  50282. return CollisionCoordinatorWorker;
  50283. }());
  50284. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50285. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50286. function CollisionCoordinatorLegacy() {
  50287. this._scaledPosition = BABYLON.Vector3.Zero();
  50288. this._scaledVelocity = BABYLON.Vector3.Zero();
  50289. this._finalPosition = BABYLON.Vector3.Zero();
  50290. }
  50291. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50292. position.divideToRef(collider._radius, this._scaledPosition);
  50293. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50294. collider.collidedMesh = null;
  50295. collider._retry = 0;
  50296. collider._initialVelocity = this._scaledVelocity;
  50297. collider._initialPosition = this._scaledPosition;
  50298. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50299. this._finalPosition.multiplyInPlace(collider._radius);
  50300. //run the callback
  50301. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50302. };
  50303. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50304. this._scene = scene;
  50305. };
  50306. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50307. //Legacy need no destruction method.
  50308. };
  50309. //No update in legacy mode
  50310. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50311. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50312. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50313. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50314. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50315. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50316. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50317. if (excludedMesh === void 0) { excludedMesh = null; }
  50318. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50319. if (collider._retry >= maximumRetry) {
  50320. finalPosition.copyFrom(position);
  50321. return;
  50322. }
  50323. // Check if this is a mesh else camera or -1
  50324. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50325. collider._initialize(position, velocity, closeDistance);
  50326. // Check all meshes
  50327. for (var index = 0; index < this._scene.meshes.length; index++) {
  50328. var mesh = this._scene.meshes[index];
  50329. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50330. mesh._checkCollision(collider);
  50331. }
  50332. }
  50333. if (!collider.collisionFound) {
  50334. position.addToRef(velocity, finalPosition);
  50335. return;
  50336. }
  50337. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50338. collider._getResponse(position, velocity);
  50339. }
  50340. if (velocity.length() <= closeDistance) {
  50341. finalPosition.copyFrom(position);
  50342. return;
  50343. }
  50344. collider._retry++;
  50345. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50346. };
  50347. return CollisionCoordinatorLegacy;
  50348. }());
  50349. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50350. })(BABYLON || (BABYLON = {}));
  50351. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50352. var BABYLON;
  50353. (function (BABYLON) {
  50354. /**
  50355. * A particle represents one of the element emitted by a particle system.
  50356. * This is mainly define by its coordinates, direction, velocity and age.
  50357. */
  50358. var Particle = /** @class */ (function () {
  50359. /**
  50360. * Creates a new instance of @see Particle
  50361. * @param particleSystem the particle system the particle belongs to
  50362. */
  50363. function Particle(particleSystem) {
  50364. this.particleSystem = particleSystem;
  50365. /**
  50366. * The world position of the particle in the scene.
  50367. */
  50368. this.position = BABYLON.Vector3.Zero();
  50369. /**
  50370. * The world direction of the particle in the scene.
  50371. */
  50372. this.direction = BABYLON.Vector3.Zero();
  50373. /**
  50374. * The color of the particle.
  50375. */
  50376. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50377. /**
  50378. * The color change of the particle per step.
  50379. */
  50380. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50381. /**
  50382. * Defines how long will the life of the particle be.
  50383. */
  50384. this.lifeTime = 1.0;
  50385. /**
  50386. * The current age of the particle.
  50387. */
  50388. this.age = 0;
  50389. /**
  50390. * The current size of the particle.
  50391. */
  50392. this.size = 0;
  50393. /**
  50394. * The current angle of the particle.
  50395. */
  50396. this.angle = 0;
  50397. /**
  50398. * Defines how fast is the angle changing.
  50399. */
  50400. this.angularSpeed = 0;
  50401. /**
  50402. * Defines the cell index used by the particle to be rendered from a sprite.
  50403. */
  50404. this.cellIndex = 0;
  50405. this._currentFrameCounter = 0;
  50406. if (!this.particleSystem.isAnimationSheetEnabled) {
  50407. return;
  50408. }
  50409. this.cellIndex = this.particleSystem.startSpriteCellID;
  50410. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50411. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50412. }
  50413. else {
  50414. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50415. }
  50416. }
  50417. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50418. // (ageOffset / scaledUpdateSpeed) / available cells
  50419. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50420. this._currentFrameCounter += scaledUpdateSpeed;
  50421. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50422. this._currentFrameCounter = 0;
  50423. this.cellIndex++;
  50424. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50425. this.cellIndex = this.particleSystem.endSpriteCellID;
  50426. }
  50427. }
  50428. };
  50429. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50430. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50431. this.cellIndex++;
  50432. this._currentFrameCounter = 0;
  50433. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50434. if (this.particleSystem.spriteCellLoop) {
  50435. this.cellIndex = this.particleSystem.startSpriteCellID;
  50436. }
  50437. else {
  50438. this.cellIndex = this.particleSystem.endSpriteCellID;
  50439. }
  50440. }
  50441. }
  50442. else {
  50443. this._currentFrameCounter++;
  50444. }
  50445. };
  50446. /**
  50447. * Copy the properties of particle to another one.
  50448. * @param other the particle to copy the information to.
  50449. */
  50450. Particle.prototype.copyTo = function (other) {
  50451. other.position.copyFrom(this.position);
  50452. other.direction.copyFrom(this.direction);
  50453. other.color.copyFrom(this.color);
  50454. other.colorStep.copyFrom(this.colorStep);
  50455. other.lifeTime = this.lifeTime;
  50456. other.age = this.age;
  50457. other.size = this.size;
  50458. other.angle = this.angle;
  50459. other.angularSpeed = this.angularSpeed;
  50460. other.particleSystem = this.particleSystem;
  50461. other.cellIndex = this.cellIndex;
  50462. };
  50463. return Particle;
  50464. }());
  50465. BABYLON.Particle = Particle;
  50466. })(BABYLON || (BABYLON = {}));
  50467. //# sourceMappingURL=babylon.particle.js.map
  50468. var BABYLON;
  50469. (function (BABYLON) {
  50470. /**
  50471. * This represents a particle system in Babylon.
  50472. * 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.
  50473. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50474. * @example https://doc.babylonjs.com/babylon101/particles
  50475. */
  50476. var ParticleSystem = /** @class */ (function () {
  50477. /**
  50478. * Instantiates a particle system.
  50479. * 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.
  50480. * @param name The name of the particle system
  50481. * @param capacity The max number of particles alive at the same time
  50482. * @param scene The scene the particle system belongs to
  50483. * @param customEffect a custom effect used to change the way particles are rendered by default
  50484. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50485. * @param epsilon Offset used to render the particles
  50486. */
  50487. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50488. if (customEffect === void 0) { customEffect = null; }
  50489. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50490. if (epsilon === void 0) { epsilon = 0.01; }
  50491. var _this = this;
  50492. /**
  50493. * List of animations used by the particle system.
  50494. */
  50495. this.animations = [];
  50496. /**
  50497. * The rendering group used by the Particle system to chose when to render.
  50498. */
  50499. this.renderingGroupId = 0;
  50500. /**
  50501. * The emitter represents the Mesh or position we are attaching the particle system to.
  50502. */
  50503. this.emitter = null;
  50504. /**
  50505. * The maximum number of particles to emit per frame
  50506. */
  50507. this.emitRate = 10;
  50508. /**
  50509. * If you want to launch only a few particles at once, that can be done, as well.
  50510. */
  50511. this.manualEmitCount = -1;
  50512. /**
  50513. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50514. */
  50515. this.updateSpeed = 0.01;
  50516. /**
  50517. * The amount of time the particle system is running (depends of the overall update speed).
  50518. */
  50519. this.targetStopDuration = 0;
  50520. /**
  50521. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50522. */
  50523. this.disposeOnStop = false;
  50524. /**
  50525. * Minimum power of emitting particles.
  50526. */
  50527. this.minEmitPower = 1;
  50528. /**
  50529. * Maximum power of emitting particles.
  50530. */
  50531. this.maxEmitPower = 1;
  50532. /**
  50533. * Minimum life time of emitting particles.
  50534. */
  50535. this.minLifeTime = 1;
  50536. /**
  50537. * Maximum life time of emitting particles.
  50538. */
  50539. this.maxLifeTime = 1;
  50540. /**
  50541. * Minimum Size of emitting particles.
  50542. */
  50543. this.minSize = 1;
  50544. /**
  50545. * Maximum Size of emitting particles.
  50546. */
  50547. this.maxSize = 1;
  50548. /**
  50549. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50550. */
  50551. this.minAngularSpeed = 0;
  50552. /**
  50553. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50554. */
  50555. this.maxAngularSpeed = 0;
  50556. /**
  50557. * The layer mask we are rendering the particles through.
  50558. */
  50559. this.layerMask = 0x0FFFFFFF;
  50560. /**
  50561. * This can help using your own shader to render the particle system.
  50562. * The according effect will be created
  50563. */
  50564. this.customShader = null;
  50565. /**
  50566. * By default particle system starts as soon as they are created. This prevents the
  50567. * automatic start to happen and let you decide when to start emitting particles.
  50568. */
  50569. this.preventAutoStart = false;
  50570. /**
  50571. * Callback triggered when the particle animation is ending.
  50572. */
  50573. this.onAnimationEnd = null;
  50574. /**
  50575. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50576. */
  50577. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50578. /**
  50579. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50580. * to override the particles.
  50581. */
  50582. this.forceDepthWrite = false;
  50583. /**
  50584. * You can use gravity if you want to give an orientation to your particles.
  50585. */
  50586. this.gravity = BABYLON.Vector3.Zero();
  50587. /**
  50588. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50589. */
  50590. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50591. /**
  50592. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50593. */
  50594. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50595. /**
  50596. * Color the particle will have at the end of its lifetime.
  50597. */
  50598. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50599. /**
  50600. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50601. */
  50602. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50603. /**
  50604. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50605. */
  50606. this.spriteCellLoop = true;
  50607. /**
  50608. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50609. */
  50610. this.spriteCellChangeSpeed = 0;
  50611. /**
  50612. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50613. */
  50614. this.startSpriteCellID = 0;
  50615. /**
  50616. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50617. */
  50618. this.endSpriteCellID = 0;
  50619. /**
  50620. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50621. */
  50622. this.spriteCellWidth = 0;
  50623. /**
  50624. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50625. */
  50626. this.spriteCellHeight = 0;
  50627. /**
  50628. * An event triggered when the system is disposed.
  50629. */
  50630. this.onDisposeObservable = new BABYLON.Observable();
  50631. this._particles = new Array();
  50632. this._stockParticles = new Array();
  50633. this._newPartsExcess = 0;
  50634. this._vertexBuffers = {};
  50635. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50636. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50637. this._scaledDirection = BABYLON.Vector3.Zero();
  50638. this._scaledGravity = BABYLON.Vector3.Zero();
  50639. this._currentRenderId = -1;
  50640. this._started = false;
  50641. this._stopped = false;
  50642. this._actualFrame = 0;
  50643. this._vertexBufferSize = 11;
  50644. this._appendParticleVertexes = null;
  50645. this.id = name;
  50646. this.name = name;
  50647. this._capacity = capacity;
  50648. this._epsilon = epsilon;
  50649. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50650. if (isAnimationSheetEnabled) {
  50651. this._vertexBufferSize = 12;
  50652. }
  50653. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50654. this._customEffect = customEffect;
  50655. scene.particleSystems.push(this);
  50656. this._createIndexBuffer();
  50657. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50658. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50659. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50660. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50661. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50662. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50663. if (this._isAnimationSheetEnabled) {
  50664. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50665. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50666. }
  50667. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50668. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50669. this._vertexBuffers["options"] = options;
  50670. // Default emitter type
  50671. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50672. this.updateFunction = function (particles) {
  50673. for (var index = 0; index < particles.length; index++) {
  50674. var particle = particles[index];
  50675. particle.age += _this._scaledUpdateSpeed;
  50676. if (particle.age >= particle.lifeTime) {
  50677. _this.recycleParticle(particle);
  50678. index--;
  50679. continue;
  50680. }
  50681. else {
  50682. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50683. particle.color.addInPlace(_this._scaledColorStep);
  50684. if (particle.color.a < 0)
  50685. particle.color.a = 0;
  50686. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50687. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50688. particle.position.addInPlace(_this._scaledDirection);
  50689. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50690. particle.direction.addInPlace(_this._scaledGravity);
  50691. if (_this._isAnimationSheetEnabled) {
  50692. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50693. }
  50694. }
  50695. }
  50696. };
  50697. }
  50698. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50699. /**
  50700. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50701. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50702. */
  50703. get: function () {
  50704. if (this.particleEmitterType.direction1) {
  50705. return this.particleEmitterType.direction1;
  50706. }
  50707. return BABYLON.Vector3.Zero();
  50708. },
  50709. set: function (value) {
  50710. if (this.particleEmitterType.direction1) {
  50711. this.particleEmitterType.direction1 = value;
  50712. }
  50713. },
  50714. enumerable: true,
  50715. configurable: true
  50716. });
  50717. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50718. /**
  50719. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50720. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50721. */
  50722. get: function () {
  50723. if (this.particleEmitterType.direction2) {
  50724. return this.particleEmitterType.direction2;
  50725. }
  50726. return BABYLON.Vector3.Zero();
  50727. },
  50728. set: function (value) {
  50729. if (this.particleEmitterType.direction2) {
  50730. this.particleEmitterType.direction2 = value;
  50731. }
  50732. },
  50733. enumerable: true,
  50734. configurable: true
  50735. });
  50736. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50737. /**
  50738. * 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.
  50739. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50740. */
  50741. get: function () {
  50742. if (this.particleEmitterType.minEmitBox) {
  50743. return this.particleEmitterType.minEmitBox;
  50744. }
  50745. return BABYLON.Vector3.Zero();
  50746. },
  50747. set: function (value) {
  50748. if (this.particleEmitterType.minEmitBox) {
  50749. this.particleEmitterType.minEmitBox = value;
  50750. }
  50751. },
  50752. enumerable: true,
  50753. configurable: true
  50754. });
  50755. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50756. /**
  50757. * 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.
  50758. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50759. */
  50760. get: function () {
  50761. if (this.particleEmitterType.maxEmitBox) {
  50762. return this.particleEmitterType.maxEmitBox;
  50763. }
  50764. return BABYLON.Vector3.Zero();
  50765. },
  50766. set: function (value) {
  50767. if (this.particleEmitterType.maxEmitBox) {
  50768. this.particleEmitterType.maxEmitBox = value;
  50769. }
  50770. },
  50771. enumerable: true,
  50772. configurable: true
  50773. });
  50774. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50775. /**
  50776. * Sets a callback that will be triggered when the system is disposed.
  50777. */
  50778. set: function (callback) {
  50779. if (this._onDisposeObserver) {
  50780. this.onDisposeObservable.remove(this._onDisposeObserver);
  50781. }
  50782. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50783. },
  50784. enumerable: true,
  50785. configurable: true
  50786. });
  50787. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50788. /**
  50789. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50790. */
  50791. get: function () {
  50792. return this._isAnimationSheetEnabled;
  50793. },
  50794. enumerable: true,
  50795. configurable: true
  50796. });
  50797. Object.defineProperty(ParticleSystem.prototype, "particles", {
  50798. /**
  50799. * Gets the current list of active particles
  50800. */
  50801. get: function () {
  50802. return this._particles;
  50803. },
  50804. enumerable: true,
  50805. configurable: true
  50806. });
  50807. /**
  50808. * Returns the string "ParticleSystem"
  50809. * @returns a string containing the class name
  50810. */
  50811. ParticleSystem.prototype.getClassName = function () {
  50812. return "ParticleSystem";
  50813. };
  50814. ParticleSystem.prototype._createIndexBuffer = function () {
  50815. var indices = [];
  50816. var index = 0;
  50817. for (var count = 0; count < this._capacity; count++) {
  50818. indices.push(index);
  50819. indices.push(index + 1);
  50820. indices.push(index + 2);
  50821. indices.push(index);
  50822. indices.push(index + 2);
  50823. indices.push(index + 3);
  50824. index += 4;
  50825. }
  50826. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50827. };
  50828. /**
  50829. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50830. * Its lifetime will start back at 0.
  50831. * @param particle The particle to recycle
  50832. */
  50833. ParticleSystem.prototype.recycleParticle = function (particle) {
  50834. var lastParticle = this._particles.pop();
  50835. if (lastParticle !== particle) {
  50836. lastParticle.copyTo(particle);
  50837. this._stockParticles.push(lastParticle);
  50838. }
  50839. };
  50840. /**
  50841. * Gets the maximum number of particles active at the same time.
  50842. * @returns The max number of active particles.
  50843. */
  50844. ParticleSystem.prototype.getCapacity = function () {
  50845. return this._capacity;
  50846. };
  50847. /**
  50848. * Gets Wether there are still active particles in the system.
  50849. * @returns True if it is alive, otherwise false.
  50850. */
  50851. ParticleSystem.prototype.isAlive = function () {
  50852. return this._alive;
  50853. };
  50854. /**
  50855. * Gets Wether the system has been started.
  50856. * @returns True if it has been started, otherwise false.
  50857. */
  50858. ParticleSystem.prototype.isStarted = function () {
  50859. return this._started;
  50860. };
  50861. /**
  50862. * Starts the particle system and begins to emit.
  50863. */
  50864. ParticleSystem.prototype.start = function () {
  50865. this._started = true;
  50866. this._stopped = false;
  50867. this._actualFrame = 0;
  50868. };
  50869. /**
  50870. * Stops the particle system.
  50871. */
  50872. ParticleSystem.prototype.stop = function () {
  50873. this._stopped = true;
  50874. };
  50875. /**
  50876. * Remove all active particles
  50877. */
  50878. ParticleSystem.prototype.reset = function () {
  50879. this._stockParticles = [];
  50880. this._particles = [];
  50881. };
  50882. /**
  50883. * @ignore (for internal use only)
  50884. */
  50885. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50886. var offset = index * this._vertexBufferSize;
  50887. this._vertexData[offset] = particle.position.x;
  50888. this._vertexData[offset + 1] = particle.position.y;
  50889. this._vertexData[offset + 2] = particle.position.z;
  50890. this._vertexData[offset + 3] = particle.color.r;
  50891. this._vertexData[offset + 4] = particle.color.g;
  50892. this._vertexData[offset + 5] = particle.color.b;
  50893. this._vertexData[offset + 6] = particle.color.a;
  50894. this._vertexData[offset + 7] = particle.angle;
  50895. this._vertexData[offset + 8] = particle.size;
  50896. this._vertexData[offset + 9] = offsetX;
  50897. this._vertexData[offset + 10] = offsetY;
  50898. };
  50899. /**
  50900. * @ignore (for internal use only)
  50901. */
  50902. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50903. if (offsetX === 0)
  50904. offsetX = this._epsilon;
  50905. else if (offsetX === 1)
  50906. offsetX = 1 - this._epsilon;
  50907. if (offsetY === 0)
  50908. offsetY = this._epsilon;
  50909. else if (offsetY === 1)
  50910. offsetY = 1 - this._epsilon;
  50911. var offset = index * this._vertexBufferSize;
  50912. this._vertexData[offset] = particle.position.x;
  50913. this._vertexData[offset + 1] = particle.position.y;
  50914. this._vertexData[offset + 2] = particle.position.z;
  50915. this._vertexData[offset + 3] = particle.color.r;
  50916. this._vertexData[offset + 4] = particle.color.g;
  50917. this._vertexData[offset + 5] = particle.color.b;
  50918. this._vertexData[offset + 6] = particle.color.a;
  50919. this._vertexData[offset + 7] = particle.angle;
  50920. this._vertexData[offset + 8] = particle.size;
  50921. this._vertexData[offset + 9] = offsetX;
  50922. this._vertexData[offset + 10] = offsetY;
  50923. this._vertexData[offset + 11] = particle.cellIndex;
  50924. };
  50925. ParticleSystem.prototype._update = function (newParticles) {
  50926. // Update current
  50927. this._alive = this._particles.length > 0;
  50928. this.updateFunction(this._particles);
  50929. // Add new ones
  50930. var worldMatrix;
  50931. if (this.emitter.position) {
  50932. var emitterMesh = this.emitter;
  50933. worldMatrix = emitterMesh.getWorldMatrix();
  50934. }
  50935. else {
  50936. var emitterPosition = this.emitter;
  50937. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50938. }
  50939. var particle;
  50940. for (var index = 0; index < newParticles; index++) {
  50941. if (this._particles.length === this._capacity) {
  50942. break;
  50943. }
  50944. if (this._stockParticles.length !== 0) {
  50945. particle = this._stockParticles.pop();
  50946. particle.age = 0;
  50947. particle.cellIndex = this.startSpriteCellID;
  50948. }
  50949. else {
  50950. particle = new BABYLON.Particle(this);
  50951. }
  50952. this._particles.push(particle);
  50953. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50954. if (this.startPositionFunction) {
  50955. this.startPositionFunction(worldMatrix, particle.position, particle);
  50956. }
  50957. else {
  50958. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50959. }
  50960. if (this.startDirectionFunction) {
  50961. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50962. }
  50963. else {
  50964. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50965. }
  50966. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50967. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50968. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50969. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50970. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50971. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50972. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50973. }
  50974. };
  50975. ParticleSystem.prototype._getEffect = function () {
  50976. if (this._customEffect) {
  50977. return this._customEffect;
  50978. }
  50979. ;
  50980. var defines = [];
  50981. if (this._scene.clipPlane) {
  50982. defines.push("#define CLIPPLANE");
  50983. }
  50984. if (this._isAnimationSheetEnabled) {
  50985. defines.push("#define ANIMATESHEET");
  50986. }
  50987. // Effect
  50988. var join = defines.join("\n");
  50989. if (this._cachedDefines !== join) {
  50990. this._cachedDefines = join;
  50991. var attributesNamesOrOptions;
  50992. var effectCreationOption;
  50993. if (this._isAnimationSheetEnabled) {
  50994. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50995. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50996. }
  50997. else {
  50998. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50999. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51000. }
  51001. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51002. }
  51003. return this._effect;
  51004. };
  51005. /**
  51006. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51007. */
  51008. ParticleSystem.prototype.animate = function () {
  51009. if (!this._started)
  51010. return;
  51011. var effect = this._getEffect();
  51012. // Check
  51013. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51014. return;
  51015. if (this._currentRenderId === this._scene.getRenderId()) {
  51016. return;
  51017. }
  51018. this._currentRenderId = this._scene.getRenderId();
  51019. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51020. // determine the number of particles we need to create
  51021. var newParticles;
  51022. if (this.manualEmitCount > -1) {
  51023. newParticles = this.manualEmitCount;
  51024. this._newPartsExcess = 0;
  51025. this.manualEmitCount = 0;
  51026. }
  51027. else {
  51028. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51029. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51030. }
  51031. if (this._newPartsExcess > 1.0) {
  51032. newParticles += this._newPartsExcess >> 0;
  51033. this._newPartsExcess -= this._newPartsExcess >> 0;
  51034. }
  51035. this._alive = false;
  51036. if (!this._stopped) {
  51037. this._actualFrame += this._scaledUpdateSpeed;
  51038. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51039. this.stop();
  51040. }
  51041. else {
  51042. newParticles = 0;
  51043. }
  51044. this._update(newParticles);
  51045. // Stopped?
  51046. if (this._stopped) {
  51047. if (!this._alive) {
  51048. this._started = false;
  51049. if (this.onAnimationEnd) {
  51050. this.onAnimationEnd();
  51051. }
  51052. if (this.disposeOnStop) {
  51053. this._scene._toBeDisposed.push(this);
  51054. }
  51055. }
  51056. }
  51057. // Animation sheet
  51058. if (this._isAnimationSheetEnabled) {
  51059. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51060. }
  51061. else {
  51062. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51063. }
  51064. // Update VBO
  51065. var offset = 0;
  51066. for (var index = 0; index < this._particles.length; index++) {
  51067. var particle = this._particles[index];
  51068. this._appendParticleVertexes(offset, particle);
  51069. offset += 4;
  51070. }
  51071. if (this._vertexBuffer) {
  51072. this._vertexBuffer.update(this._vertexData);
  51073. }
  51074. };
  51075. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51076. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51077. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51078. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51079. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51080. };
  51081. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51082. this._appendParticleVertex(offset++, particle, 0, 0);
  51083. this._appendParticleVertex(offset++, particle, 1, 0);
  51084. this._appendParticleVertex(offset++, particle, 1, 1);
  51085. this._appendParticleVertex(offset++, particle, 0, 1);
  51086. };
  51087. /**
  51088. * Rebuilds the particle system.
  51089. */
  51090. ParticleSystem.prototype.rebuild = function () {
  51091. this._createIndexBuffer();
  51092. if (this._vertexBuffer) {
  51093. this._vertexBuffer._rebuild();
  51094. }
  51095. };
  51096. /**
  51097. * Renders the particle system in its current state.
  51098. * @returns the current number of particles
  51099. */
  51100. ParticleSystem.prototype.render = function () {
  51101. var effect = this._getEffect();
  51102. // Check
  51103. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  51104. return 0;
  51105. }
  51106. var engine = this._scene.getEngine();
  51107. // Render
  51108. engine.enableEffect(effect);
  51109. engine.setState(false);
  51110. var viewMatrix = this._scene.getViewMatrix();
  51111. effect.setTexture("diffuseSampler", this.particleTexture);
  51112. effect.setMatrix("view", viewMatrix);
  51113. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51114. if (this._isAnimationSheetEnabled) {
  51115. var baseSize = this.particleTexture.getBaseSize();
  51116. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51117. }
  51118. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51119. if (this._scene.clipPlane) {
  51120. var clipPlane = this._scene.clipPlane;
  51121. var invView = viewMatrix.clone();
  51122. invView.invert();
  51123. effect.setMatrix("invView", invView);
  51124. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51125. }
  51126. // VBOs
  51127. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51128. // Draw order
  51129. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51130. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51131. }
  51132. else {
  51133. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51134. }
  51135. if (this.forceDepthWrite) {
  51136. engine.setDepthWrite(true);
  51137. }
  51138. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51139. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51140. return this._particles.length;
  51141. };
  51142. /**
  51143. * Disposes the particle system and free the associated resources
  51144. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51145. */
  51146. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51147. if (disposeTexture === void 0) { disposeTexture = true; }
  51148. if (this._vertexBuffer) {
  51149. this._vertexBuffer.dispose();
  51150. this._vertexBuffer = null;
  51151. }
  51152. if (this._indexBuffer) {
  51153. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51154. this._indexBuffer = null;
  51155. }
  51156. if (disposeTexture && this.particleTexture) {
  51157. this.particleTexture.dispose();
  51158. this.particleTexture = null;
  51159. }
  51160. // Remove from scene
  51161. var index = this._scene.particleSystems.indexOf(this);
  51162. if (index > -1) {
  51163. this._scene.particleSystems.splice(index, 1);
  51164. }
  51165. // Callback
  51166. this.onDisposeObservable.notifyObservers(this);
  51167. this.onDisposeObservable.clear();
  51168. };
  51169. /**
  51170. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51171. * @param radius The radius of the sphere to emit from
  51172. * @returns the emitter
  51173. */
  51174. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51175. if (radius === void 0) { radius = 1; }
  51176. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51177. this.particleEmitterType = particleEmitter;
  51178. return particleEmitter;
  51179. };
  51180. /**
  51181. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51182. * @param radius The radius of the sphere to emit from
  51183. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51184. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51185. * @returns the emitter
  51186. */
  51187. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51188. if (radius === void 0) { radius = 1; }
  51189. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51190. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51191. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51192. this.particleEmitterType = particleEmitter;
  51193. return particleEmitter;
  51194. };
  51195. /**
  51196. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51197. * @param radius The radius of the cone to emit from
  51198. * @param angle The base angle of the cone
  51199. * @returns the emitter
  51200. */
  51201. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51202. if (radius === void 0) { radius = 1; }
  51203. if (angle === void 0) { angle = Math.PI / 4; }
  51204. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51205. this.particleEmitterType = particleEmitter;
  51206. return particleEmitter;
  51207. };
  51208. // 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.
  51209. /**
  51210. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51211. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51212. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51213. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51214. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51215. * @returns the emitter
  51216. */
  51217. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51218. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51219. this.direction1 = direction1;
  51220. this.direction2 = direction2;
  51221. this.minEmitBox = minEmitBox;
  51222. this.maxEmitBox = maxEmitBox;
  51223. this.particleEmitterType = particleEmitter;
  51224. return particleEmitter;
  51225. };
  51226. /**
  51227. * Clones the particle system.
  51228. * @param name The name of the cloned object
  51229. * @param newEmitter The new emitter to use
  51230. * @returns the cloned particle system
  51231. */
  51232. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51233. var custom = null;
  51234. var program = null;
  51235. if (this.customShader != null) {
  51236. program = this.customShader;
  51237. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51238. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51239. }
  51240. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51241. result.customShader = program;
  51242. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51243. if (newEmitter === undefined) {
  51244. newEmitter = this.emitter;
  51245. }
  51246. result.emitter = newEmitter;
  51247. if (this.particleTexture) {
  51248. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51249. }
  51250. if (!this.preventAutoStart) {
  51251. result.start();
  51252. }
  51253. return result;
  51254. };
  51255. /**
  51256. * Serializes the particle system to a JSON object.
  51257. * @returns the JSON object
  51258. */
  51259. ParticleSystem.prototype.serialize = function () {
  51260. var serializationObject = {};
  51261. serializationObject.name = this.name;
  51262. serializationObject.id = this.id;
  51263. // Emitter
  51264. if (this.emitter.position) {
  51265. var emitterMesh = this.emitter;
  51266. serializationObject.emitterId = emitterMesh.id;
  51267. }
  51268. else {
  51269. var emitterPosition = this.emitter;
  51270. serializationObject.emitter = emitterPosition.asArray();
  51271. }
  51272. serializationObject.capacity = this.getCapacity();
  51273. if (this.particleTexture) {
  51274. serializationObject.textureName = this.particleTexture.name;
  51275. }
  51276. // Animations
  51277. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51278. // Particle system
  51279. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51280. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51281. serializationObject.minSize = this.minSize;
  51282. serializationObject.maxSize = this.maxSize;
  51283. serializationObject.minEmitPower = this.minEmitPower;
  51284. serializationObject.maxEmitPower = this.maxEmitPower;
  51285. serializationObject.minLifeTime = this.minLifeTime;
  51286. serializationObject.maxLifeTime = this.maxLifeTime;
  51287. serializationObject.emitRate = this.emitRate;
  51288. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51289. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51290. serializationObject.gravity = this.gravity.asArray();
  51291. serializationObject.direction1 = this.direction1.asArray();
  51292. serializationObject.direction2 = this.direction2.asArray();
  51293. serializationObject.color1 = this.color1.asArray();
  51294. serializationObject.color2 = this.color2.asArray();
  51295. serializationObject.colorDead = this.colorDead.asArray();
  51296. serializationObject.updateSpeed = this.updateSpeed;
  51297. serializationObject.targetStopDuration = this.targetStopDuration;
  51298. serializationObject.textureMask = this.textureMask.asArray();
  51299. serializationObject.blendMode = this.blendMode;
  51300. serializationObject.customShader = this.customShader;
  51301. serializationObject.preventAutoStart = this.preventAutoStart;
  51302. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51303. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51304. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51305. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51306. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51307. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51308. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51309. // Emitter
  51310. if (this.particleEmitterType) {
  51311. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51312. }
  51313. return serializationObject;
  51314. };
  51315. /**
  51316. * Parses a JSON object to create a particle system.
  51317. * @param parsedParticleSystem The JSON object to parse
  51318. * @param scene The scene to create the particle system in
  51319. * @param rootUrl The root url to use to load external dependencies like texture
  51320. * @returns the Parsed particle system
  51321. */
  51322. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51323. var name = parsedParticleSystem.name;
  51324. var custom = null;
  51325. var program = null;
  51326. if (parsedParticleSystem.customShader) {
  51327. program = parsedParticleSystem.customShader;
  51328. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51329. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51330. }
  51331. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51332. particleSystem.customShader = program;
  51333. if (parsedParticleSystem.id) {
  51334. particleSystem.id = parsedParticleSystem.id;
  51335. }
  51336. // Auto start
  51337. if (parsedParticleSystem.preventAutoStart) {
  51338. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51339. }
  51340. // Texture
  51341. if (parsedParticleSystem.textureName) {
  51342. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51343. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51344. }
  51345. // Emitter
  51346. if (parsedParticleSystem.emitterId) {
  51347. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51348. }
  51349. else {
  51350. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51351. }
  51352. // Animations
  51353. if (parsedParticleSystem.animations) {
  51354. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51355. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51356. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51357. }
  51358. }
  51359. if (parsedParticleSystem.autoAnimate) {
  51360. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51361. }
  51362. // Particle system
  51363. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51364. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51365. particleSystem.minSize = parsedParticleSystem.minSize;
  51366. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51367. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51368. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51369. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51370. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51371. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51372. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51373. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51374. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51375. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51376. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51377. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51378. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51379. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51380. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51381. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51382. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51383. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51384. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51385. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51386. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51387. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51388. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51389. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51390. if (!particleSystem.preventAutoStart) {
  51391. particleSystem.start();
  51392. }
  51393. return particleSystem;
  51394. };
  51395. /**
  51396. * Source color is added to the destination color without alpha affecting the result.
  51397. */
  51398. ParticleSystem.BLENDMODE_ONEONE = 0;
  51399. /**
  51400. * Blend current color and particle color using particle’s alpha.
  51401. */
  51402. ParticleSystem.BLENDMODE_STANDARD = 1;
  51403. return ParticleSystem;
  51404. }());
  51405. BABYLON.ParticleSystem = ParticleSystem;
  51406. })(BABYLON || (BABYLON = {}));
  51407. //# sourceMappingURL=babylon.particleSystem.js.map
  51408. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51409. var BABYLON;
  51410. (function (BABYLON) {
  51411. /**
  51412. * Particle emitter emitting particles from the inside of a box.
  51413. * It emits the particles randomly between 2 given directions.
  51414. */
  51415. var BoxParticleEmitter = /** @class */ (function () {
  51416. /**
  51417. * Creates a new instance of @see BoxParticleEmitter
  51418. */
  51419. function BoxParticleEmitter() {
  51420. /**
  51421. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51422. */
  51423. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51424. /**
  51425. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51426. */
  51427. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51428. /**
  51429. * 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.
  51430. */
  51431. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51432. /**
  51433. * 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.
  51434. */
  51435. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51436. }
  51437. /**
  51438. * Called by the particle System when the direction is computed for the created particle.
  51439. * @param emitPower is the power of the particle (speed)
  51440. * @param worldMatrix is the world matrix of the particle system
  51441. * @param directionToUpdate is the direction vector to update with the result
  51442. * @param particle is the particle we are computed the direction for
  51443. */
  51444. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51445. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51446. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51447. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51448. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51449. };
  51450. /**
  51451. * Called by the particle System when the position is computed for the created particle.
  51452. * @param worldMatrix is the world matrix of the particle system
  51453. * @param positionToUpdate is the position vector to update with the result
  51454. * @param particle is the particle we are computed the position for
  51455. */
  51456. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51457. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51458. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51459. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51461. };
  51462. /**
  51463. * Clones the current emitter and returns a copy of it
  51464. * @returns the new emitter
  51465. */
  51466. BoxParticleEmitter.prototype.clone = function () {
  51467. var newOne = new BoxParticleEmitter();
  51468. BABYLON.Tools.DeepCopy(this, newOne);
  51469. return newOne;
  51470. };
  51471. /**
  51472. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51473. * @param effect defines the update shader
  51474. */
  51475. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51476. effect.setVector3("direction1", this.direction1);
  51477. effect.setVector3("direction2", this.direction2);
  51478. effect.setVector3("minEmitBox", this.minEmitBox);
  51479. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51480. };
  51481. /**
  51482. * Returns a string to use to update the GPU particles update shader
  51483. * @returns a string containng the defines string
  51484. */
  51485. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51486. return "#define BOXEMITTER";
  51487. };
  51488. /**
  51489. * Returns the string "BoxEmitter"
  51490. * @returns a string containing the class name
  51491. */
  51492. BoxParticleEmitter.prototype.getClassName = function () {
  51493. return "BoxEmitter";
  51494. };
  51495. /**
  51496. * Serializes the particle system to a JSON object.
  51497. * @returns the JSON object
  51498. */
  51499. BoxParticleEmitter.prototype.serialize = function () {
  51500. var serializationObject = {};
  51501. serializationObject.type = this.getClassName();
  51502. serializationObject.direction1 = this.direction1.asArray();
  51503. ;
  51504. serializationObject.direction2 = this.direction2.asArray();
  51505. ;
  51506. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51507. ;
  51508. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51509. ;
  51510. return serializationObject;
  51511. };
  51512. /**
  51513. * Parse properties from a JSON object
  51514. * @param serializationObject defines the JSON object
  51515. */
  51516. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51517. this.direction1.copyFrom(serializationObject.direction1);
  51518. this.direction2.copyFrom(serializationObject.direction2);
  51519. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51520. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51521. };
  51522. return BoxParticleEmitter;
  51523. }());
  51524. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51525. })(BABYLON || (BABYLON = {}));
  51526. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51527. var BABYLON;
  51528. (function (BABYLON) {
  51529. /**
  51530. * Particle emitter emitting particles from the inside of a cone.
  51531. * It emits the particles alongside the cone volume from the base to the particle.
  51532. * The emission direction might be randomized.
  51533. */
  51534. var ConeParticleEmitter = /** @class */ (function () {
  51535. /**
  51536. * Creates a new instance of @see ConeParticleEmitter
  51537. * @param radius the radius of the emission cone (1 by default)
  51538. * @param angles the cone base angle (PI by default)
  51539. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51540. */
  51541. function ConeParticleEmitter(radius,
  51542. /**
  51543. * The radius of the emission cone.
  51544. */
  51545. angle,
  51546. /**
  51547. * The cone base angle.
  51548. */
  51549. directionRandomizer) {
  51550. if (radius === void 0) { radius = 1; }
  51551. if (angle === void 0) { angle = Math.PI; }
  51552. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51553. this.angle = angle;
  51554. this.directionRandomizer = directionRandomizer;
  51555. this.radius = radius;
  51556. }
  51557. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51558. /**
  51559. * Gets the radius of the emission cone.
  51560. */
  51561. get: function () {
  51562. return this._radius;
  51563. },
  51564. /**
  51565. * Sets the radius of the emission cone.
  51566. */
  51567. set: function (value) {
  51568. this._radius = value;
  51569. if (this.angle !== 0) {
  51570. this._height = value / Math.tan(this.angle / 2);
  51571. }
  51572. else {
  51573. this._height = 1;
  51574. }
  51575. },
  51576. enumerable: true,
  51577. configurable: true
  51578. });
  51579. /**
  51580. * Called by the particle System when the direction is computed for the created particle.
  51581. * @param emitPower is the power of the particle (speed)
  51582. * @param worldMatrix is the world matrix of the particle system
  51583. * @param directionToUpdate is the direction vector to update with the result
  51584. * @param particle is the particle we are computed the direction for
  51585. */
  51586. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51587. if (this.angle === 0) {
  51588. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51589. }
  51590. else {
  51591. // measure the direction Vector from the emitter to the particle.
  51592. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51593. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51594. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51595. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51596. direction.x += randX;
  51597. direction.y += randY;
  51598. direction.z += randZ;
  51599. direction.normalize();
  51600. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51601. }
  51602. };
  51603. /**
  51604. * Called by the particle System when the position is computed for the created particle.
  51605. * @param worldMatrix is the world matrix of the particle system
  51606. * @param positionToUpdate is the position vector to update with the result
  51607. * @param particle is the particle we are computed the position for
  51608. */
  51609. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51610. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51611. var h = BABYLON.Scalar.RandomRange(0, 1);
  51612. // Better distribution in a cone at normal angles.
  51613. h = 1 - h * h;
  51614. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51615. radius = radius * h / this._height;
  51616. var randX = radius * Math.sin(s);
  51617. var randZ = radius * Math.cos(s);
  51618. var randY = h * this._height;
  51619. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51620. };
  51621. /**
  51622. * Clones the current emitter and returns a copy of it
  51623. * @returns the new emitter
  51624. */
  51625. ConeParticleEmitter.prototype.clone = function () {
  51626. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51627. BABYLON.Tools.DeepCopy(this, newOne);
  51628. return newOne;
  51629. };
  51630. /**
  51631. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51632. * @param effect defines the update shader
  51633. */
  51634. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51635. effect.setFloat("radius", this.radius);
  51636. effect.setFloat("angle", this.angle);
  51637. effect.setFloat("height", this._height);
  51638. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51639. };
  51640. /**
  51641. * Returns a string to use to update the GPU particles update shader
  51642. * @returns a string containng the defines string
  51643. */
  51644. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51645. return "#define CONEEMITTER";
  51646. };
  51647. /**
  51648. * Returns the string "BoxEmitter"
  51649. * @returns a string containing the class name
  51650. */
  51651. ConeParticleEmitter.prototype.getClassName = function () {
  51652. return "ConeEmitter";
  51653. };
  51654. /**
  51655. * Serializes the particle system to a JSON object.
  51656. * @returns the JSON object
  51657. */
  51658. ConeParticleEmitter.prototype.serialize = function () {
  51659. var serializationObject = {};
  51660. serializationObject.type = this.getClassName();
  51661. serializationObject.radius = this.radius;
  51662. serializationObject.angle = this.angle;
  51663. serializationObject.directionRandomizer = this.directionRandomizer;
  51664. return serializationObject;
  51665. };
  51666. /**
  51667. * Parse properties from a JSON object
  51668. * @param serializationObject defines the JSON object
  51669. */
  51670. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51671. this.radius = serializationObject.radius;
  51672. this.angle = serializationObject.angle;
  51673. this.directionRandomizer = serializationObject.directionRandomizer;
  51674. };
  51675. return ConeParticleEmitter;
  51676. }());
  51677. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51678. })(BABYLON || (BABYLON = {}));
  51679. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51680. var BABYLON;
  51681. (function (BABYLON) {
  51682. /**
  51683. * Particle emitter emitting particles from the inside of a sphere.
  51684. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51685. */
  51686. var SphereParticleEmitter = /** @class */ (function () {
  51687. /**
  51688. * Creates a new instance of @see SphereParticleEmitter
  51689. * @param radius the radius of the emission sphere (1 by default)
  51690. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51691. */
  51692. function SphereParticleEmitter(
  51693. /**
  51694. * The radius of the emission sphere.
  51695. */
  51696. radius,
  51697. /**
  51698. * How much to randomize the particle direction [0-1].
  51699. */
  51700. directionRandomizer) {
  51701. if (radius === void 0) { radius = 1; }
  51702. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51703. this.radius = radius;
  51704. this.directionRandomizer = directionRandomizer;
  51705. }
  51706. /**
  51707. * Called by the particle System when the direction is computed for the created particle.
  51708. * @param emitPower is the power of the particle (speed)
  51709. * @param worldMatrix is the world matrix of the particle system
  51710. * @param directionToUpdate is the direction vector to update with the result
  51711. * @param particle is the particle we are computed the direction for
  51712. */
  51713. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51714. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51715. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51716. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51717. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51718. direction.x += randX;
  51719. direction.y += randY;
  51720. direction.z += randZ;
  51721. direction.normalize();
  51722. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51723. };
  51724. /**
  51725. * Called by the particle System when the position is computed for the created particle.
  51726. * @param worldMatrix is the world matrix of the particle system
  51727. * @param positionToUpdate is the position vector to update with the result
  51728. * @param particle is the particle we are computed the position for
  51729. */
  51730. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51731. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51732. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51733. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51734. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51735. var randY = randRadius * Math.cos(theta);
  51736. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51737. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51738. };
  51739. /**
  51740. * Clones the current emitter and returns a copy of it
  51741. * @returns the new emitter
  51742. */
  51743. SphereParticleEmitter.prototype.clone = function () {
  51744. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51745. BABYLON.Tools.DeepCopy(this, newOne);
  51746. return newOne;
  51747. };
  51748. /**
  51749. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51750. * @param effect defines the update shader
  51751. */
  51752. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51753. effect.setFloat("radius", this.radius);
  51754. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51755. };
  51756. /**
  51757. * Returns a string to use to update the GPU particles update shader
  51758. * @returns a string containng the defines string
  51759. */
  51760. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51761. return "#define SPHEREEMITTER";
  51762. };
  51763. /**
  51764. * Returns the string "SphereParticleEmitter"
  51765. * @returns a string containing the class name
  51766. */
  51767. SphereParticleEmitter.prototype.getClassName = function () {
  51768. return "SphereParticleEmitter";
  51769. };
  51770. /**
  51771. * Serializes the particle system to a JSON object.
  51772. * @returns the JSON object
  51773. */
  51774. SphereParticleEmitter.prototype.serialize = function () {
  51775. var serializationObject = {};
  51776. serializationObject.type = this.getClassName();
  51777. serializationObject.radius = this.radius;
  51778. serializationObject.directionRandomizer = this.directionRandomizer;
  51779. return serializationObject;
  51780. };
  51781. /**
  51782. * Parse properties from a JSON object
  51783. * @param serializationObject defines the JSON object
  51784. */
  51785. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51786. this.radius = serializationObject.radius;
  51787. this.directionRandomizer = serializationObject.directionRandomizer;
  51788. };
  51789. return SphereParticleEmitter;
  51790. }());
  51791. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51792. /**
  51793. * Particle emitter emitting particles from the inside of a sphere.
  51794. * It emits the particles randomly between two vectors.
  51795. */
  51796. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51797. __extends(SphereDirectedParticleEmitter, _super);
  51798. /**
  51799. * Creates a new instance of @see SphereDirectedParticleEmitter
  51800. * @param radius the radius of the emission sphere (1 by default)
  51801. * @param direction1 the min limit of the emission direction (up vector by default)
  51802. * @param direction2 the max limit of the emission direction (up vector by default)
  51803. */
  51804. function SphereDirectedParticleEmitter(radius,
  51805. /**
  51806. * The min limit of the emission direction.
  51807. */
  51808. direction1,
  51809. /**
  51810. * The max limit of the emission direction.
  51811. */
  51812. direction2) {
  51813. if (radius === void 0) { radius = 1; }
  51814. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51815. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51816. var _this = _super.call(this, radius) || this;
  51817. _this.direction1 = direction1;
  51818. _this.direction2 = direction2;
  51819. return _this;
  51820. }
  51821. /**
  51822. * Called by the particle System when the direction is computed for the created particle.
  51823. * @param emitPower is the power of the particle (speed)
  51824. * @param worldMatrix is the world matrix of the particle system
  51825. * @param directionToUpdate is the direction vector to update with the result
  51826. * @param particle is the particle we are computed the direction for
  51827. */
  51828. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51829. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51830. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51831. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51832. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51833. };
  51834. /**
  51835. * Clones the current emitter and returns a copy of it
  51836. * @returns the new emitter
  51837. */
  51838. SphereDirectedParticleEmitter.prototype.clone = function () {
  51839. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51840. BABYLON.Tools.DeepCopy(this, newOne);
  51841. return newOne;
  51842. };
  51843. /**
  51844. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51845. * @param effect defines the update shader
  51846. */
  51847. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51848. effect.setFloat("radius", this.radius);
  51849. effect.setVector3("direction1", this.direction1);
  51850. effect.setVector3("direction2", this.direction2);
  51851. };
  51852. /**
  51853. * Returns a string to use to update the GPU particles update shader
  51854. * @returns a string containng the defines string
  51855. */
  51856. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51857. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51858. };
  51859. /**
  51860. * Returns the string "SphereDirectedParticleEmitter"
  51861. * @returns a string containing the class name
  51862. */
  51863. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51864. return "SphereDirectedParticleEmitter";
  51865. };
  51866. /**
  51867. * Serializes the particle system to a JSON object.
  51868. * @returns the JSON object
  51869. */
  51870. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51871. var serializationObject = _super.prototype.serialize.call(this);
  51872. ;
  51873. serializationObject.direction1 = this.direction1.asArray();
  51874. ;
  51875. serializationObject.direction2 = this.direction2.asArray();
  51876. ;
  51877. return serializationObject;
  51878. };
  51879. /**
  51880. * Parse properties from a JSON object
  51881. * @param serializationObject defines the JSON object
  51882. */
  51883. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51884. _super.prototype.parse.call(this, serializationObject);
  51885. this.direction1.copyFrom(serializationObject.direction1);
  51886. this.direction2.copyFrom(serializationObject.direction2);
  51887. };
  51888. return SphereDirectedParticleEmitter;
  51889. }(SphereParticleEmitter));
  51890. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51891. })(BABYLON || (BABYLON = {}));
  51892. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51893. var BABYLON;
  51894. (function (BABYLON) {
  51895. /**
  51896. * Represents one particle of a solid particle system.
  51897. * @see SolidParticleSystem
  51898. */
  51899. var SolidParticle = /** @class */ (function () {
  51900. /**
  51901. * Creates a Solid Particle object.
  51902. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51903. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51904. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51905. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51906. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51907. * @param shapeId (integer) is the model shape identifier in the SPS.
  51908. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51909. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51910. */
  51911. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51912. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51913. /**
  51914. * particle global index
  51915. */
  51916. this.idx = 0;
  51917. /**
  51918. * The color of the particle
  51919. */
  51920. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51921. /**
  51922. * The world space position of the particle.
  51923. */
  51924. this.position = BABYLON.Vector3.Zero();
  51925. /**
  51926. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51927. */
  51928. this.rotation = BABYLON.Vector3.Zero();
  51929. /**
  51930. * The scaling of the particle.
  51931. */
  51932. this.scaling = BABYLON.Vector3.One();
  51933. /**
  51934. * The uvs of the particle.
  51935. */
  51936. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51937. /**
  51938. * The current speed of the particle.
  51939. */
  51940. this.velocity = BABYLON.Vector3.Zero();
  51941. /**
  51942. * The pivot point in the particle local space.
  51943. */
  51944. this.pivot = BABYLON.Vector3.Zero();
  51945. /**
  51946. * Must the particle be translated from its pivot point in its local space ?
  51947. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51948. * Default : false
  51949. */
  51950. this.translateFromPivot = false;
  51951. /**
  51952. * Is the particle active or not ?
  51953. */
  51954. this.alive = true;
  51955. /**
  51956. * Is the particle visible or not ?
  51957. */
  51958. this.isVisible = true;
  51959. /**
  51960. * Index of this particle in the global "positions" array (Internal use)
  51961. */
  51962. this._pos = 0;
  51963. /**
  51964. * Index of this particle in the global "indices" array (Internal use)
  51965. */
  51966. this._ind = 0;
  51967. /**
  51968. * ModelShape id of this particle
  51969. */
  51970. this.shapeId = 0;
  51971. /**
  51972. * Index of the particle in its shape id (Internal use)
  51973. */
  51974. this.idxInShape = 0;
  51975. /**
  51976. * Still set as invisible in order to skip useless computations (Internal use)
  51977. */
  51978. this._stillInvisible = false;
  51979. /**
  51980. * Last computed particle rotation matrix
  51981. */
  51982. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51983. /**
  51984. * Parent particle Id, if any.
  51985. * Default null.
  51986. */
  51987. this.parentId = null;
  51988. /**
  51989. * Internal global position in the SPS.
  51990. */
  51991. this._globalPosition = BABYLON.Vector3.Zero();
  51992. this.idx = particleIndex;
  51993. this._pos = positionIndex;
  51994. this._ind = indiceIndex;
  51995. this._model = model;
  51996. this.shapeId = shapeId;
  51997. this.idxInShape = idxInShape;
  51998. this._sps = sps;
  51999. if (modelBoundingInfo) {
  52000. this._modelBoundingInfo = modelBoundingInfo;
  52001. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52002. }
  52003. }
  52004. Object.defineProperty(SolidParticle.prototype, "scale", {
  52005. /**
  52006. * Legacy support, changed scale to scaling
  52007. */
  52008. get: function () {
  52009. return this.scaling;
  52010. },
  52011. /**
  52012. * Legacy support, changed scale to scaling
  52013. */
  52014. set: function (scale) {
  52015. this.scaling = scale;
  52016. },
  52017. enumerable: true,
  52018. configurable: true
  52019. });
  52020. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52021. /**
  52022. * Legacy support, changed quaternion to rotationQuaternion
  52023. */
  52024. get: function () {
  52025. return this.rotationQuaternion;
  52026. },
  52027. /**
  52028. * Legacy support, changed quaternion to rotationQuaternion
  52029. */
  52030. set: function (q) {
  52031. this.rotationQuaternion = q;
  52032. },
  52033. enumerable: true,
  52034. configurable: true
  52035. });
  52036. /**
  52037. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52038. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52039. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52040. * @returns true if it intersects
  52041. */
  52042. SolidParticle.prototype.intersectsMesh = function (target) {
  52043. if (!this._boundingInfo || !target._boundingInfo) {
  52044. return false;
  52045. }
  52046. if (this._sps._bSphereOnly) {
  52047. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52048. }
  52049. return this._boundingInfo.intersects(target._boundingInfo, false);
  52050. };
  52051. return SolidParticle;
  52052. }());
  52053. BABYLON.SolidParticle = SolidParticle;
  52054. /**
  52055. * Represents the shape of the model used by one particle of a solid particle system.
  52056. * SPS internal tool, don't use it manually.
  52057. * @see SolidParticleSystem
  52058. */
  52059. var ModelShape = /** @class */ (function () {
  52060. /**
  52061. * 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.
  52062. * SPS internal tool, don't use it manually.
  52063. * @ignore
  52064. */
  52065. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52066. /**
  52067. * length of the shape in the model indices array (internal use)
  52068. */
  52069. this._indicesLength = 0;
  52070. this.shapeID = id;
  52071. this._shape = shape;
  52072. this._indicesLength = indicesLength;
  52073. this._shapeUV = shapeUV;
  52074. this._positionFunction = posFunction;
  52075. this._vertexFunction = vtxFunction;
  52076. }
  52077. return ModelShape;
  52078. }());
  52079. BABYLON.ModelShape = ModelShape;
  52080. /**
  52081. * Represents a Depth Sorted Particle in the solid particle system.
  52082. * @see SolidParticleSystem
  52083. */
  52084. var DepthSortedParticle = /** @class */ (function () {
  52085. function DepthSortedParticle() {
  52086. /**
  52087. * Index of the particle in the "indices" array
  52088. */
  52089. this.ind = 0;
  52090. /**
  52091. * Length of the particle shape in the "indices" array
  52092. */
  52093. this.indicesLength = 0;
  52094. /**
  52095. * Squared distance from the particle to the camera
  52096. */
  52097. this.sqDistance = 0.0;
  52098. }
  52099. return DepthSortedParticle;
  52100. }());
  52101. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52102. })(BABYLON || (BABYLON = {}));
  52103. //# sourceMappingURL=babylon.solidParticle.js.map
  52104. var BABYLON;
  52105. (function (BABYLON) {
  52106. /**
  52107. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52108. *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.
  52109. * The SPS is also a particle system. It provides some methods to manage the particles.
  52110. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52111. *
  52112. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52113. */
  52114. var SolidParticleSystem = /** @class */ (function () {
  52115. /**
  52116. * Creates a SPS (Solid Particle System) object.
  52117. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52118. * @param scene (Scene) is the scene in which the SPS is added.
  52119. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52120. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52121. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52122. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52123. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52124. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52125. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52126. */
  52127. function SolidParticleSystem(name, scene, options) {
  52128. /**
  52129. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52130. * Example : var p = SPS.particles[i];
  52131. */
  52132. this.particles = new Array();
  52133. /**
  52134. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52135. */
  52136. this.nbParticles = 0;
  52137. /**
  52138. * If the particles must ever face the camera (default false). Useful for planar particles.
  52139. */
  52140. this.billboard = false;
  52141. /**
  52142. * Recompute normals when adding a shape
  52143. */
  52144. this.recomputeNormals = true;
  52145. /**
  52146. * This a counter ofr your own usage. It's not set by any SPS functions.
  52147. */
  52148. this.counter = 0;
  52149. /**
  52150. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52151. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52152. */
  52153. this.vars = {};
  52154. /**
  52155. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52156. */
  52157. this._bSphereOnly = false;
  52158. /**
  52159. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52160. */
  52161. this._bSphereRadiusFactor = 1.0;
  52162. this._positions = new Array();
  52163. this._indices = new Array();
  52164. this._normals = new Array();
  52165. this._colors = new Array();
  52166. this._uvs = new Array();
  52167. this._index = 0; // indices index
  52168. this._updatable = true;
  52169. this._pickable = false;
  52170. this._isVisibilityBoxLocked = false;
  52171. this._alwaysVisible = false;
  52172. this._depthSort = false;
  52173. this._shapeCounter = 0;
  52174. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52175. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52176. this._computeParticleColor = true;
  52177. this._computeParticleTexture = true;
  52178. this._computeParticleRotation = true;
  52179. this._computeParticleVertex = false;
  52180. this._computeBoundingBox = false;
  52181. this._depthSortParticles = true;
  52182. this._cam_axisZ = BABYLON.Vector3.Zero();
  52183. this._cam_axisY = BABYLON.Vector3.Zero();
  52184. this._cam_axisX = BABYLON.Vector3.Zero();
  52185. this._axisZ = BABYLON.Axis.Z;
  52186. this._camDir = BABYLON.Vector3.Zero();
  52187. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52188. this._rotMatrix = new BABYLON.Matrix();
  52189. this._invertMatrix = new BABYLON.Matrix();
  52190. this._rotated = BABYLON.Vector3.Zero();
  52191. this._quaternion = new BABYLON.Quaternion();
  52192. this._vertex = BABYLON.Vector3.Zero();
  52193. this._normal = BABYLON.Vector3.Zero();
  52194. this._yaw = 0.0;
  52195. this._pitch = 0.0;
  52196. this._roll = 0.0;
  52197. this._halfroll = 0.0;
  52198. this._halfpitch = 0.0;
  52199. this._halfyaw = 0.0;
  52200. this._sinRoll = 0.0;
  52201. this._cosRoll = 0.0;
  52202. this._sinPitch = 0.0;
  52203. this._cosPitch = 0.0;
  52204. this._sinYaw = 0.0;
  52205. this._cosYaw = 0.0;
  52206. this._mustUnrotateFixedNormals = false;
  52207. this._minimum = BABYLON.Vector3.Zero();
  52208. this._maximum = BABYLON.Vector3.Zero();
  52209. this._minBbox = BABYLON.Vector3.Zero();
  52210. this._maxBbox = BABYLON.Vector3.Zero();
  52211. this._particlesIntersect = false;
  52212. this._depthSortFunction = function (p1, p2) {
  52213. return (p2.sqDistance - p1.sqDistance);
  52214. };
  52215. this._needs32Bits = false;
  52216. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52217. this._scaledPivot = BABYLON.Vector3.Zero();
  52218. this._particleHasParent = false;
  52219. this.name = name;
  52220. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52221. this._camera = scene.activeCamera;
  52222. this._pickable = options ? options.isPickable : false;
  52223. this._depthSort = options ? options.enableDepthSort : false;
  52224. this._particlesIntersect = options ? options.particleIntersection : false;
  52225. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52226. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52227. if (options && options.updatable) {
  52228. this._updatable = options.updatable;
  52229. }
  52230. else {
  52231. this._updatable = true;
  52232. }
  52233. if (this._pickable) {
  52234. this.pickedParticles = [];
  52235. }
  52236. if (this._depthSort) {
  52237. this.depthSortedParticles = [];
  52238. }
  52239. }
  52240. /**
  52241. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52242. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52243. * @returns the created mesh
  52244. */
  52245. SolidParticleSystem.prototype.buildMesh = function () {
  52246. if (this.nbParticles === 0) {
  52247. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52248. this.addShape(triangle, 1);
  52249. triangle.dispose();
  52250. }
  52251. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52252. this._positions32 = new Float32Array(this._positions);
  52253. this._uvs32 = new Float32Array(this._uvs);
  52254. this._colors32 = new Float32Array(this._colors);
  52255. if (this.recomputeNormals) {
  52256. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52257. }
  52258. this._normals32 = new Float32Array(this._normals);
  52259. this._fixedNormal32 = new Float32Array(this._normals);
  52260. if (this._mustUnrotateFixedNormals) {
  52261. this._unrotateFixedNormals();
  52262. }
  52263. var vertexData = new BABYLON.VertexData();
  52264. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52265. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52266. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52267. if (this._uvs32) {
  52268. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52269. ;
  52270. }
  52271. if (this._colors32) {
  52272. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52273. }
  52274. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52275. vertexData.applyToMesh(mesh, this._updatable);
  52276. this.mesh = mesh;
  52277. this.mesh.isPickable = this._pickable;
  52278. // free memory
  52279. if (!this._depthSort) {
  52280. this._indices = null;
  52281. }
  52282. this._positions = null;
  52283. this._normals = null;
  52284. this._uvs = null;
  52285. this._colors = null;
  52286. if (!this._updatable) {
  52287. this.particles.length = 0;
  52288. }
  52289. return mesh;
  52290. };
  52291. /**
  52292. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52293. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52294. * Thus the particles generated from `digest()` have their property `position` set yet.
  52295. * @param mesh ( Mesh ) is the mesh to be digested
  52296. * @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
  52297. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52298. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52299. * @returns the current SPS
  52300. */
  52301. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52302. var size = (options && options.facetNb) || 1;
  52303. var number = (options && options.number) || 0;
  52304. var delta = (options && options.delta) || 0;
  52305. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52306. var meshInd = mesh.getIndices();
  52307. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52308. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52309. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52310. var f = 0; // facet counter
  52311. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52312. // compute size from number
  52313. if (number) {
  52314. number = (number > totalFacets) ? totalFacets : number;
  52315. size = Math.round(totalFacets / number);
  52316. delta = 0;
  52317. }
  52318. else {
  52319. size = (size > totalFacets) ? totalFacets : size;
  52320. }
  52321. var facetPos = []; // submesh positions
  52322. var facetInd = []; // submesh indices
  52323. var facetUV = []; // submesh UV
  52324. var facetCol = []; // submesh colors
  52325. var barycenter = BABYLON.Vector3.Zero();
  52326. var sizeO = size;
  52327. while (f < totalFacets) {
  52328. size = sizeO + Math.floor((1 + delta) * Math.random());
  52329. if (f > totalFacets - size) {
  52330. size = totalFacets - f;
  52331. }
  52332. // reset temp arrays
  52333. facetPos.length = 0;
  52334. facetInd.length = 0;
  52335. facetUV.length = 0;
  52336. facetCol.length = 0;
  52337. // iterate over "size" facets
  52338. var fi = 0;
  52339. for (var j = f * 3; j < (f + size) * 3; j++) {
  52340. facetInd.push(fi);
  52341. var i = meshInd[j];
  52342. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52343. if (meshUV) {
  52344. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52345. }
  52346. if (meshCol) {
  52347. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52348. }
  52349. fi++;
  52350. }
  52351. // create a model shape for each single particle
  52352. var idx = this.nbParticles;
  52353. var shape = this._posToShape(facetPos);
  52354. var shapeUV = this._uvsToShapeUV(facetUV);
  52355. // compute the barycenter of the shape
  52356. var v;
  52357. for (v = 0; v < shape.length; v++) {
  52358. barycenter.addInPlace(shape[v]);
  52359. }
  52360. barycenter.scaleInPlace(1 / shape.length);
  52361. // shift the shape from its barycenter to the origin
  52362. for (v = 0; v < shape.length; v++) {
  52363. shape[v].subtractInPlace(barycenter);
  52364. }
  52365. var bInfo;
  52366. if (this._particlesIntersect) {
  52367. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52368. }
  52369. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52370. // add the particle in the SPS
  52371. var currentPos = this._positions.length;
  52372. var currentInd = this._indices.length;
  52373. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52374. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52375. // initialize the particle position
  52376. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52377. this._index += shape.length;
  52378. idx++;
  52379. this.nbParticles++;
  52380. this._shapeCounter++;
  52381. f += size;
  52382. }
  52383. return this;
  52384. };
  52385. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52386. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52387. var index = 0;
  52388. var idx = 0;
  52389. for (var p = 0; p < this.particles.length; p++) {
  52390. this._particle = this.particles[p];
  52391. this._shape = this._particle._model._shape;
  52392. if (this._particle.rotationQuaternion) {
  52393. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52394. }
  52395. else {
  52396. this._yaw = this._particle.rotation.y;
  52397. this._pitch = this._particle.rotation.x;
  52398. this._roll = this._particle.rotation.z;
  52399. this._quaternionRotationYPR();
  52400. }
  52401. this._quaternionToRotationMatrix();
  52402. this._rotMatrix.invertToRef(this._invertMatrix);
  52403. for (var pt = 0; pt < this._shape.length; pt++) {
  52404. idx = index + pt * 3;
  52405. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52406. this._fixedNormal32[idx] = this._normal.x;
  52407. this._fixedNormal32[idx + 1] = this._normal.y;
  52408. this._fixedNormal32[idx + 2] = this._normal.z;
  52409. }
  52410. index = idx + 3;
  52411. }
  52412. };
  52413. //reset copy
  52414. SolidParticleSystem.prototype._resetCopy = function () {
  52415. this._copy.position.x = 0;
  52416. this._copy.position.y = 0;
  52417. this._copy.position.z = 0;
  52418. this._copy.rotation.x = 0;
  52419. this._copy.rotation.y = 0;
  52420. this._copy.rotation.z = 0;
  52421. this._copy.rotationQuaternion = null;
  52422. this._copy.scaling.x = 1.0;
  52423. this._copy.scaling.y = 1.0;
  52424. this._copy.scaling.z = 1.0;
  52425. this._copy.uvs.x = 0;
  52426. this._copy.uvs.y = 0;
  52427. this._copy.uvs.z = 1.0;
  52428. this._copy.uvs.w = 1.0;
  52429. this._copy.color = null;
  52430. this._copy.translateFromPivot = false;
  52431. };
  52432. // _meshBuilder : inserts the shape model in the global SPS mesh
  52433. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52434. var i;
  52435. var u = 0;
  52436. var c = 0;
  52437. var n = 0;
  52438. this._resetCopy();
  52439. if (options && options.positionFunction) {
  52440. options.positionFunction(this._copy, idx, idxInShape);
  52441. this._mustUnrotateFixedNormals = true;
  52442. }
  52443. if (this._copy.rotationQuaternion) {
  52444. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52445. }
  52446. else {
  52447. this._yaw = this._copy.rotation.y;
  52448. this._pitch = this._copy.rotation.x;
  52449. this._roll = this._copy.rotation.z;
  52450. this._quaternionRotationYPR();
  52451. }
  52452. this._quaternionToRotationMatrix();
  52453. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52454. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52455. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52456. if (this._copy.translateFromPivot) {
  52457. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52458. }
  52459. else {
  52460. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52461. }
  52462. for (i = 0; i < shape.length; i++) {
  52463. this._vertex.x = shape[i].x;
  52464. this._vertex.y = shape[i].y;
  52465. this._vertex.z = shape[i].z;
  52466. if (options && options.vertexFunction) {
  52467. options.vertexFunction(this._copy, this._vertex, i);
  52468. }
  52469. this._vertex.x *= this._copy.scaling.x;
  52470. this._vertex.y *= this._copy.scaling.y;
  52471. this._vertex.z *= this._copy.scaling.z;
  52472. this._vertex.x -= this._scaledPivot.x;
  52473. this._vertex.y -= this._scaledPivot.y;
  52474. this._vertex.z -= this._scaledPivot.z;
  52475. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52476. this._rotated.addInPlace(this._pivotBackTranslation);
  52477. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52478. if (meshUV) {
  52479. 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);
  52480. u += 2;
  52481. }
  52482. if (this._copy.color) {
  52483. this._color = this._copy.color;
  52484. }
  52485. else if (meshCol && meshCol[c] !== undefined) {
  52486. this._color.r = meshCol[c];
  52487. this._color.g = meshCol[c + 1];
  52488. this._color.b = meshCol[c + 2];
  52489. this._color.a = meshCol[c + 3];
  52490. }
  52491. else {
  52492. this._color.r = 1.0;
  52493. this._color.g = 1.0;
  52494. this._color.b = 1.0;
  52495. this._color.a = 1.0;
  52496. }
  52497. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52498. c += 4;
  52499. if (!this.recomputeNormals && meshNor) {
  52500. this._normal.x = meshNor[n];
  52501. this._normal.y = meshNor[n + 1];
  52502. this._normal.z = meshNor[n + 2];
  52503. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52504. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52505. n += 3;
  52506. }
  52507. }
  52508. for (i = 0; i < meshInd.length; i++) {
  52509. var current_ind = p + meshInd[i];
  52510. indices.push(current_ind);
  52511. if (current_ind > 65535) {
  52512. this._needs32Bits = true;
  52513. }
  52514. }
  52515. if (this._pickable) {
  52516. var nbfaces = meshInd.length / 3;
  52517. for (i = 0; i < nbfaces; i++) {
  52518. this.pickedParticles.push({ idx: idx, faceId: i });
  52519. }
  52520. }
  52521. if (this._depthSort) {
  52522. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52523. }
  52524. return this._copy;
  52525. };
  52526. // returns a shape array from positions array
  52527. SolidParticleSystem.prototype._posToShape = function (positions) {
  52528. var shape = [];
  52529. for (var i = 0; i < positions.length; i += 3) {
  52530. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52531. }
  52532. return shape;
  52533. };
  52534. // returns a shapeUV array from a Vector4 uvs
  52535. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52536. var shapeUV = [];
  52537. if (uvs) {
  52538. for (var i = 0; i < uvs.length; i++)
  52539. shapeUV.push(uvs[i]);
  52540. }
  52541. return shapeUV;
  52542. };
  52543. // adds a new particle object in the particles array
  52544. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52545. if (bInfo === void 0) { bInfo = null; }
  52546. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52547. this.particles.push(sp);
  52548. return sp;
  52549. };
  52550. /**
  52551. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52552. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52553. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52554. * @param nb (positive integer) the number of particles to be created from this model
  52555. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52556. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52557. * @returns the number of shapes in the system
  52558. */
  52559. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52560. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52561. var meshInd = mesh.getIndices();
  52562. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52563. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52564. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52565. var bbInfo;
  52566. if (this._particlesIntersect) {
  52567. bbInfo = mesh.getBoundingInfo();
  52568. }
  52569. var shape = this._posToShape(meshPos);
  52570. var shapeUV = this._uvsToShapeUV(meshUV);
  52571. var posfunc = options ? options.positionFunction : null;
  52572. var vtxfunc = options ? options.vertexFunction : null;
  52573. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52574. // particles
  52575. var sp;
  52576. var currentCopy;
  52577. var idx = this.nbParticles;
  52578. for (var i = 0; i < nb; i++) {
  52579. var currentPos = this._positions.length;
  52580. var currentInd = this._indices.length;
  52581. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52582. if (this._updatable) {
  52583. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52584. sp.position.copyFrom(currentCopy.position);
  52585. sp.rotation.copyFrom(currentCopy.rotation);
  52586. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52587. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52588. }
  52589. if (currentCopy.color && sp.color) {
  52590. sp.color.copyFrom(currentCopy.color);
  52591. }
  52592. sp.scaling.copyFrom(currentCopy.scaling);
  52593. sp.uvs.copyFrom(currentCopy.uvs);
  52594. }
  52595. this._index += shape.length;
  52596. idx++;
  52597. }
  52598. this.nbParticles += nb;
  52599. this._shapeCounter++;
  52600. return this._shapeCounter - 1;
  52601. };
  52602. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52603. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52604. this._resetCopy();
  52605. if (particle._model._positionFunction) {
  52606. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52607. }
  52608. if (this._copy.rotationQuaternion) {
  52609. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52610. }
  52611. else {
  52612. this._yaw = this._copy.rotation.y;
  52613. this._pitch = this._copy.rotation.x;
  52614. this._roll = this._copy.rotation.z;
  52615. this._quaternionRotationYPR();
  52616. }
  52617. this._quaternionToRotationMatrix();
  52618. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52619. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52620. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52621. if (this._copy.translateFromPivot) {
  52622. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52623. }
  52624. else {
  52625. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52626. }
  52627. this._shape = particle._model._shape;
  52628. for (var pt = 0; pt < this._shape.length; pt++) {
  52629. this._vertex.x = this._shape[pt].x;
  52630. this._vertex.y = this._shape[pt].y;
  52631. this._vertex.z = this._shape[pt].z;
  52632. if (particle._model._vertexFunction) {
  52633. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52634. }
  52635. this._vertex.x *= this._copy.scaling.x;
  52636. this._vertex.y *= this._copy.scaling.y;
  52637. this._vertex.z *= this._copy.scaling.z;
  52638. this._vertex.x -= this._scaledPivot.x;
  52639. this._vertex.y -= this._scaledPivot.y;
  52640. this._vertex.z -= this._scaledPivot.z;
  52641. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52642. this._rotated.addInPlace(this._pivotBackTranslation);
  52643. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52644. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52645. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52646. }
  52647. particle.position.x = 0.0;
  52648. particle.position.y = 0.0;
  52649. particle.position.z = 0.0;
  52650. particle.rotation.x = 0.0;
  52651. particle.rotation.y = 0.0;
  52652. particle.rotation.z = 0.0;
  52653. particle.rotationQuaternion = null;
  52654. particle.scaling.x = 1.0;
  52655. particle.scaling.y = 1.0;
  52656. particle.scaling.z = 1.0;
  52657. particle.uvs.x = 0.0;
  52658. particle.uvs.y = 0.0;
  52659. particle.uvs.z = 1.0;
  52660. particle.uvs.w = 1.0;
  52661. particle.pivot.x = 0.0;
  52662. particle.pivot.y = 0.0;
  52663. particle.pivot.z = 0.0;
  52664. particle.translateFromPivot = false;
  52665. particle.parentId = null;
  52666. };
  52667. /**
  52668. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52669. * @returns the SPS.
  52670. */
  52671. SolidParticleSystem.prototype.rebuildMesh = function () {
  52672. for (var p = 0; p < this.particles.length; p++) {
  52673. this._rebuildParticle(this.particles[p]);
  52674. }
  52675. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52676. return this;
  52677. };
  52678. /**
  52679. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52680. * This method calls `updateParticle()` for each particle of the SPS.
  52681. * For an animated SPS, it is usually called within the render loop.
  52682. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52683. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52684. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52685. * @returns the SPS.
  52686. */
  52687. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52688. if (start === void 0) { start = 0; }
  52689. if (end === void 0) { end = this.nbParticles - 1; }
  52690. if (update === void 0) { update = true; }
  52691. if (!this._updatable) {
  52692. return this;
  52693. }
  52694. // custom beforeUpdate
  52695. this.beforeUpdateParticles(start, end, update);
  52696. this._cam_axisX.x = 1.0;
  52697. this._cam_axisX.y = 0.0;
  52698. this._cam_axisX.z = 0.0;
  52699. this._cam_axisY.x = 0.0;
  52700. this._cam_axisY.y = 1.0;
  52701. this._cam_axisY.z = 0.0;
  52702. this._cam_axisZ.x = 0.0;
  52703. this._cam_axisZ.y = 0.0;
  52704. this._cam_axisZ.z = 1.0;
  52705. // cases when the World Matrix is to be computed first
  52706. if (this.billboard || this._depthSort) {
  52707. this.mesh.computeWorldMatrix(true);
  52708. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52709. }
  52710. // if the particles will always face the camera
  52711. if (this.billboard) {
  52712. // compute the camera position and un-rotate it by the current mesh rotation
  52713. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52714. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52715. this._cam_axisZ.normalize();
  52716. // same for camera up vector extracted from the cam view matrix
  52717. var view = this._camera.getViewMatrix(true);
  52718. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52719. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52720. this._cam_axisY.normalize();
  52721. this._cam_axisX.normalize();
  52722. }
  52723. // if depthSort, compute the camera global position in the mesh local system
  52724. if (this._depthSort) {
  52725. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52726. }
  52727. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52728. var idx = 0; // current position index in the global array positions32
  52729. var index = 0; // position start index in the global array positions32 of the current particle
  52730. var colidx = 0; // current color index in the global array colors32
  52731. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52732. var uvidx = 0; // current uv index in the global array uvs32
  52733. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52734. var pt = 0; // current index in the particle model shape
  52735. if (this.mesh.isFacetDataEnabled) {
  52736. this._computeBoundingBox = true;
  52737. }
  52738. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52739. if (this._computeBoundingBox) {
  52740. if (start == 0 && end == this.nbParticles - 1) {
  52741. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52742. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52743. }
  52744. else {
  52745. if (this.mesh._boundingInfo) {
  52746. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52747. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52748. }
  52749. }
  52750. }
  52751. // particle loop
  52752. index = this.particles[start]._pos;
  52753. var vpos = (index / 3) | 0;
  52754. colorIndex = vpos * 4;
  52755. uvIndex = vpos * 2;
  52756. for (var p = start; p <= end; p++) {
  52757. this._particle = this.particles[p];
  52758. this._shape = this._particle._model._shape;
  52759. this._shapeUV = this._particle._model._shapeUV;
  52760. // call to custom user function to update the particle properties
  52761. this.updateParticle(this._particle);
  52762. // camera-particle distance for depth sorting
  52763. if (this._depthSort && this._depthSortParticles) {
  52764. var dsp = this.depthSortedParticles[p];
  52765. dsp.ind = this._particle._ind;
  52766. dsp.indicesLength = this._particle._model._indicesLength;
  52767. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52768. }
  52769. // skip the computations for inactive or already invisible particles
  52770. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52771. // increment indexes for the next particle
  52772. pt = this._shape.length;
  52773. index += pt * 3;
  52774. colorIndex += pt * 4;
  52775. uvIndex += pt * 2;
  52776. continue;
  52777. }
  52778. if (this._particle.isVisible) {
  52779. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52780. this._particleHasParent = (this._particle.parentId !== null);
  52781. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52782. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52783. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52784. // particle rotation matrix
  52785. if (this.billboard) {
  52786. this._particle.rotation.x = 0.0;
  52787. this._particle.rotation.y = 0.0;
  52788. }
  52789. if (this._computeParticleRotation || this.billboard) {
  52790. if (this._particle.rotationQuaternion) {
  52791. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52792. }
  52793. else {
  52794. this._yaw = this._particle.rotation.y;
  52795. this._pitch = this._particle.rotation.x;
  52796. this._roll = this._particle.rotation.z;
  52797. this._quaternionRotationYPR();
  52798. }
  52799. this._quaternionToRotationMatrix();
  52800. }
  52801. if (this._particleHasParent) {
  52802. this._parent = this.particles[this._particle.parentId];
  52803. 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];
  52804. 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];
  52805. 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];
  52806. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52807. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52808. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52809. if (this._computeParticleRotation || this.billboard) {
  52810. 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];
  52811. 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];
  52812. 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];
  52813. 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];
  52814. 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];
  52815. 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];
  52816. 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];
  52817. 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];
  52818. 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];
  52819. }
  52820. }
  52821. else {
  52822. this._particle._globalPosition.x = this._particle.position.x;
  52823. this._particle._globalPosition.y = this._particle.position.y;
  52824. this._particle._globalPosition.z = this._particle.position.z;
  52825. if (this._computeParticleRotation || this.billboard) {
  52826. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52827. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52828. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52829. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52830. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52831. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52832. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52833. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52834. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52835. }
  52836. }
  52837. if (this._particle.translateFromPivot) {
  52838. this._pivotBackTranslation.x = 0.0;
  52839. this._pivotBackTranslation.y = 0.0;
  52840. this._pivotBackTranslation.z = 0.0;
  52841. }
  52842. else {
  52843. this._pivotBackTranslation.x = this._scaledPivot.x;
  52844. this._pivotBackTranslation.y = this._scaledPivot.y;
  52845. this._pivotBackTranslation.z = this._scaledPivot.z;
  52846. }
  52847. // particle vertex loop
  52848. for (pt = 0; pt < this._shape.length; pt++) {
  52849. idx = index + pt * 3;
  52850. colidx = colorIndex + pt * 4;
  52851. uvidx = uvIndex + pt * 2;
  52852. this._vertex.x = this._shape[pt].x;
  52853. this._vertex.y = this._shape[pt].y;
  52854. this._vertex.z = this._shape[pt].z;
  52855. if (this._computeParticleVertex) {
  52856. this.updateParticleVertex(this._particle, this._vertex, pt);
  52857. }
  52858. // positions
  52859. this._vertex.x *= this._particle.scaling.x;
  52860. this._vertex.y *= this._particle.scaling.y;
  52861. this._vertex.z *= this._particle.scaling.z;
  52862. this._vertex.x -= this._scaledPivot.x;
  52863. this._vertex.y -= this._scaledPivot.y;
  52864. this._vertex.z -= this._scaledPivot.z;
  52865. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52866. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52867. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52868. this._rotated.x += this._pivotBackTranslation.x;
  52869. this._rotated.y += this._pivotBackTranslation.y;
  52870. this._rotated.z += this._pivotBackTranslation.z;
  52871. 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;
  52872. 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;
  52873. 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;
  52874. if (this._computeBoundingBox) {
  52875. if (this._positions32[idx] < this._minimum.x) {
  52876. this._minimum.x = this._positions32[idx];
  52877. }
  52878. if (this._positions32[idx] > this._maximum.x) {
  52879. this._maximum.x = this._positions32[idx];
  52880. }
  52881. if (this._positions32[idx + 1] < this._minimum.y) {
  52882. this._minimum.y = this._positions32[idx + 1];
  52883. }
  52884. if (this._positions32[idx + 1] > this._maximum.y) {
  52885. this._maximum.y = this._positions32[idx + 1];
  52886. }
  52887. if (this._positions32[idx + 2] < this._minimum.z) {
  52888. this._minimum.z = this._positions32[idx + 2];
  52889. }
  52890. if (this._positions32[idx + 2] > this._maximum.z) {
  52891. this._maximum.z = this._positions32[idx + 2];
  52892. }
  52893. }
  52894. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52895. if (!this._computeParticleVertex) {
  52896. this._normal.x = this._fixedNormal32[idx];
  52897. this._normal.y = this._fixedNormal32[idx + 1];
  52898. this._normal.z = this._fixedNormal32[idx + 2];
  52899. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52900. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52901. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52902. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52903. 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;
  52904. 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;
  52905. }
  52906. if (this._computeParticleColor && this._particle.color) {
  52907. this._colors32[colidx] = this._particle.color.r;
  52908. this._colors32[colidx + 1] = this._particle.color.g;
  52909. this._colors32[colidx + 2] = this._particle.color.b;
  52910. this._colors32[colidx + 3] = this._particle.color.a;
  52911. }
  52912. if (this._computeParticleTexture) {
  52913. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52914. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52915. }
  52916. }
  52917. }
  52918. else {
  52919. this._particle._stillInvisible = true; // mark the particle as invisible
  52920. for (pt = 0; pt < this._shape.length; pt++) {
  52921. idx = index + pt * 3;
  52922. colidx = colorIndex + pt * 4;
  52923. uvidx = uvIndex + pt * 2;
  52924. this._positions32[idx] = 0.0;
  52925. this._positions32[idx + 1] = 0.0;
  52926. this._positions32[idx + 2] = 0.0;
  52927. this._normals32[idx] = 0.0;
  52928. this._normals32[idx + 1] = 0.0;
  52929. this._normals32[idx + 2] = 0.0;
  52930. if (this._computeParticleColor && this._particle.color) {
  52931. this._colors32[colidx] = this._particle.color.r;
  52932. this._colors32[colidx + 1] = this._particle.color.g;
  52933. this._colors32[colidx + 2] = this._particle.color.b;
  52934. this._colors32[colidx + 3] = this._particle.color.a;
  52935. }
  52936. if (this._computeParticleTexture) {
  52937. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52938. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52939. }
  52940. }
  52941. }
  52942. // if the particle intersections must be computed : update the bbInfo
  52943. if (this._particlesIntersect) {
  52944. var bInfo = this._particle._boundingInfo;
  52945. var bBox = bInfo.boundingBox;
  52946. var bSphere = bInfo.boundingSphere;
  52947. if (!this._bSphereOnly) {
  52948. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52949. for (var b = 0; b < bBox.vectors.length; b++) {
  52950. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52951. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52952. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52953. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52954. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52955. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52956. 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;
  52957. 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;
  52958. 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;
  52959. }
  52960. bBox._update(this.mesh._worldMatrix);
  52961. }
  52962. // place and scale the particle bouding sphere in the SPS local system, then update it
  52963. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52964. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52965. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52966. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52967. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52968. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52969. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52970. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52971. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52972. 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));
  52973. bSphere._update(this.mesh._worldMatrix);
  52974. }
  52975. // increment indexes for the next particle
  52976. index = idx + 3;
  52977. colorIndex = colidx + 4;
  52978. uvIndex = uvidx + 2;
  52979. }
  52980. // if the VBO must be updated
  52981. if (update) {
  52982. if (this._computeParticleColor) {
  52983. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52984. }
  52985. if (this._computeParticleTexture) {
  52986. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52987. }
  52988. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52989. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52990. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52991. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52992. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52993. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52994. for (var i = 0; i < this._normals32.length; i++) {
  52995. this._fixedNormal32[i] = this._normals32[i];
  52996. }
  52997. }
  52998. if (!this.mesh.areNormalsFrozen) {
  52999. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53000. }
  53001. }
  53002. if (this._depthSort && this._depthSortParticles) {
  53003. this.depthSortedParticles.sort(this._depthSortFunction);
  53004. var dspl = this.depthSortedParticles.length;
  53005. var sorted = 0;
  53006. var lind = 0;
  53007. var sind = 0;
  53008. var sid = 0;
  53009. for (sorted = 0; sorted < dspl; sorted++) {
  53010. lind = this.depthSortedParticles[sorted].indicesLength;
  53011. sind = this.depthSortedParticles[sorted].ind;
  53012. for (var i = 0; i < lind; i++) {
  53013. this._indices32[sid] = this._indices[sind + i];
  53014. sid++;
  53015. }
  53016. }
  53017. this.mesh.updateIndices(this._indices32);
  53018. }
  53019. }
  53020. if (this._computeBoundingBox) {
  53021. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53022. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53023. }
  53024. this.afterUpdateParticles(start, end, update);
  53025. return this;
  53026. };
  53027. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53028. this._halfroll = this._roll * 0.5;
  53029. this._halfpitch = this._pitch * 0.5;
  53030. this._halfyaw = this._yaw * 0.5;
  53031. this._sinRoll = Math.sin(this._halfroll);
  53032. this._cosRoll = Math.cos(this._halfroll);
  53033. this._sinPitch = Math.sin(this._halfpitch);
  53034. this._cosPitch = Math.cos(this._halfpitch);
  53035. this._sinYaw = Math.sin(this._halfyaw);
  53036. this._cosYaw = Math.cos(this._halfyaw);
  53037. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53038. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53039. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53040. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53041. };
  53042. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53043. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53044. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53045. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53046. this._rotMatrix.m[3] = 0;
  53047. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53048. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53049. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53050. this._rotMatrix.m[7] = 0;
  53051. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53052. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53053. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53054. this._rotMatrix.m[11] = 0;
  53055. this._rotMatrix.m[12] = 0;
  53056. this._rotMatrix.m[13] = 0;
  53057. this._rotMatrix.m[14] = 0;
  53058. this._rotMatrix.m[15] = 1.0;
  53059. };
  53060. /**
  53061. * Disposes the SPS.
  53062. */
  53063. SolidParticleSystem.prototype.dispose = function () {
  53064. this.mesh.dispose();
  53065. this.vars = null;
  53066. // drop references to internal big arrays for the GC
  53067. this._positions = null;
  53068. this._indices = null;
  53069. this._normals = null;
  53070. this._uvs = null;
  53071. this._colors = null;
  53072. this._indices32 = null;
  53073. this._positions32 = null;
  53074. this._normals32 = null;
  53075. this._fixedNormal32 = null;
  53076. this._uvs32 = null;
  53077. this._colors32 = null;
  53078. this.pickedParticles = null;
  53079. };
  53080. /**
  53081. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53082. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53083. * @returns the SPS.
  53084. */
  53085. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53086. if (!this._isVisibilityBoxLocked) {
  53087. this.mesh.refreshBoundingInfo();
  53088. }
  53089. return this;
  53090. };
  53091. /**
  53092. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53093. * @param size the size (float) of the visibility box
  53094. * note : this doesn't lock the SPS mesh bounding box.
  53095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53096. */
  53097. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53098. var vis = size / 2;
  53099. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53100. };
  53101. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53102. /**
  53103. * Gets whether the SPS as always visible or not
  53104. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53105. */
  53106. get: function () {
  53107. return this._alwaysVisible;
  53108. },
  53109. /**
  53110. * Sets the SPS as always visible or not
  53111. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53112. */
  53113. set: function (val) {
  53114. this._alwaysVisible = val;
  53115. this.mesh.alwaysSelectAsActiveMesh = val;
  53116. },
  53117. enumerable: true,
  53118. configurable: true
  53119. });
  53120. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53121. /**
  53122. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53123. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53124. */
  53125. get: function () {
  53126. return this._isVisibilityBoxLocked;
  53127. },
  53128. /**
  53129. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53130. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53131. */
  53132. set: function (val) {
  53133. this._isVisibilityBoxLocked = val;
  53134. var boundingInfo = this.mesh.getBoundingInfo();
  53135. boundingInfo.isLocked = val;
  53136. },
  53137. enumerable: true,
  53138. configurable: true
  53139. });
  53140. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53141. /**
  53142. * Gets if `setParticles()` computes the particle rotations or not.
  53143. * Default value : true. The SPS is faster when it's set to false.
  53144. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53145. */
  53146. get: function () {
  53147. return this._computeParticleRotation;
  53148. },
  53149. /**
  53150. * Tells to `setParticles()` to compute the particle rotations or not.
  53151. * Default value : true. The SPS is faster when it's set to false.
  53152. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53153. */
  53154. set: function (val) {
  53155. this._computeParticleRotation = val;
  53156. },
  53157. enumerable: true,
  53158. configurable: true
  53159. });
  53160. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53161. /**
  53162. * Gets if `setParticles()` computes the particle colors or not.
  53163. * Default value : true. The SPS is faster when it's set to false.
  53164. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53165. */
  53166. get: function () {
  53167. return this._computeParticleColor;
  53168. },
  53169. /**
  53170. * Tells to `setParticles()` to compute the particle colors or not.
  53171. * Default value : true. The SPS is faster when it's set to false.
  53172. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53173. */
  53174. set: function (val) {
  53175. this._computeParticleColor = val;
  53176. },
  53177. enumerable: true,
  53178. configurable: true
  53179. });
  53180. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53181. /**
  53182. * Gets if `setParticles()` computes the particle textures or not.
  53183. * Default value : true. The SPS is faster when it's set to false.
  53184. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53185. */
  53186. get: function () {
  53187. return this._computeParticleTexture;
  53188. },
  53189. set: function (val) {
  53190. this._computeParticleTexture = val;
  53191. },
  53192. enumerable: true,
  53193. configurable: true
  53194. });
  53195. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53196. /**
  53197. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53198. * Default value : false. The SPS is faster when it's set to false.
  53199. * Note : the particle custom vertex positions aren't stored values.
  53200. */
  53201. get: function () {
  53202. return this._computeParticleVertex;
  53203. },
  53204. /**
  53205. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53206. * Default value : false. The SPS is faster when it's set to false.
  53207. * Note : the particle custom vertex positions aren't stored values.
  53208. */
  53209. set: function (val) {
  53210. this._computeParticleVertex = val;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53216. /**
  53217. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53218. */
  53219. get: function () {
  53220. return this._computeBoundingBox;
  53221. },
  53222. /**
  53223. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53224. */
  53225. set: function (val) {
  53226. this._computeBoundingBox = val;
  53227. },
  53228. enumerable: true,
  53229. configurable: true
  53230. });
  53231. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53232. /**
  53233. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53234. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53235. * Default : `true`
  53236. */
  53237. get: function () {
  53238. return this._depthSortParticles;
  53239. },
  53240. /**
  53241. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53242. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53243. * Default : `true`
  53244. */
  53245. set: function (val) {
  53246. this._depthSortParticles = val;
  53247. },
  53248. enumerable: true,
  53249. configurable: true
  53250. });
  53251. // =======================================================================
  53252. // Particle behavior logic
  53253. // these following methods may be overwritten by the user to fit his needs
  53254. /**
  53255. * This function does nothing. It may be overwritten to set all the particle first values.
  53256. * The SPS doesn't call this function, you may have to call it by your own.
  53257. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53258. */
  53259. SolidParticleSystem.prototype.initParticles = function () {
  53260. };
  53261. /**
  53262. * This function does nothing. It may be overwritten to recycle a particle.
  53263. * The SPS doesn't call this function, you may have to call it by your own.
  53264. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53265. * @param particle The particle to recycle
  53266. * @returns the recycled particle
  53267. */
  53268. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53269. return particle;
  53270. };
  53271. /**
  53272. * Updates a particle : this function should be overwritten by the user.
  53273. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53274. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53275. * @example : just set a particle position or velocity and recycle conditions
  53276. * @param particle The particle to update
  53277. * @returns the updated particle
  53278. */
  53279. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53280. return particle;
  53281. };
  53282. /**
  53283. * Updates a vertex of a particle : it can be overwritten by the user.
  53284. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53285. * @param particle the current particle
  53286. * @param vertex the current index of the current particle
  53287. * @param pt the index of the current vertex in the particle shape
  53288. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53289. * @example : just set a vertex particle position
  53290. * @returns the updated vertex
  53291. */
  53292. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53293. return vertex;
  53294. };
  53295. /**
  53296. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53297. * This does nothing and may be overwritten by the user.
  53298. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53299. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53300. * @param update the boolean update value actually passed to setParticles()
  53301. */
  53302. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53303. };
  53304. /**
  53305. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53306. * This will be passed three parameters.
  53307. * This does nothing and may be overwritten by the user.
  53308. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53309. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53310. * @param update the boolean update value actually passed to setParticles()
  53311. */
  53312. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53313. };
  53314. return SolidParticleSystem;
  53315. }());
  53316. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53317. })(BABYLON || (BABYLON = {}));
  53318. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53319. var BABYLON;
  53320. (function (BABYLON) {
  53321. var ShaderMaterial = /** @class */ (function (_super) {
  53322. __extends(ShaderMaterial, _super);
  53323. function ShaderMaterial(name, scene, shaderPath, options) {
  53324. var _this = _super.call(this, name, scene) || this;
  53325. _this._textures = {};
  53326. _this._textureArrays = {};
  53327. _this._floats = {};
  53328. _this._ints = {};
  53329. _this._floatsArrays = {};
  53330. _this._colors3 = {};
  53331. _this._colors3Arrays = {};
  53332. _this._colors4 = {};
  53333. _this._vectors2 = {};
  53334. _this._vectors3 = {};
  53335. _this._vectors4 = {};
  53336. _this._matrices = {};
  53337. _this._matrices3x3 = {};
  53338. _this._matrices2x2 = {};
  53339. _this._vectors2Arrays = {};
  53340. _this._vectors3Arrays = {};
  53341. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53342. _this._shaderPath = shaderPath;
  53343. options.needAlphaBlending = options.needAlphaBlending || false;
  53344. options.needAlphaTesting = options.needAlphaTesting || false;
  53345. options.attributes = options.attributes || ["position", "normal", "uv"];
  53346. options.uniforms = options.uniforms || ["worldViewProjection"];
  53347. options.uniformBuffers = options.uniformBuffers || [];
  53348. options.samplers = options.samplers || [];
  53349. options.defines = options.defines || [];
  53350. _this._options = options;
  53351. return _this;
  53352. }
  53353. ShaderMaterial.prototype.getClassName = function () {
  53354. return "ShaderMaterial";
  53355. };
  53356. ShaderMaterial.prototype.needAlphaBlending = function () {
  53357. return this._options.needAlphaBlending;
  53358. };
  53359. ShaderMaterial.prototype.needAlphaTesting = function () {
  53360. return this._options.needAlphaTesting;
  53361. };
  53362. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53363. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53364. this._options.uniforms.push(uniformName);
  53365. }
  53366. };
  53367. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53368. if (this._options.samplers.indexOf(name) === -1) {
  53369. this._options.samplers.push(name);
  53370. }
  53371. this._textures[name] = texture;
  53372. return this;
  53373. };
  53374. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53375. if (this._options.samplers.indexOf(name) === -1) {
  53376. this._options.samplers.push(name);
  53377. }
  53378. this._checkUniform(name);
  53379. this._textureArrays[name] = textures;
  53380. return this;
  53381. };
  53382. ShaderMaterial.prototype.setFloat = function (name, value) {
  53383. this._checkUniform(name);
  53384. this._floats[name] = value;
  53385. return this;
  53386. };
  53387. ShaderMaterial.prototype.setInt = function (name, value) {
  53388. this._checkUniform(name);
  53389. this._ints[name] = value;
  53390. return this;
  53391. };
  53392. ShaderMaterial.prototype.setFloats = function (name, value) {
  53393. this._checkUniform(name);
  53394. this._floatsArrays[name] = value;
  53395. return this;
  53396. };
  53397. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53398. this._checkUniform(name);
  53399. this._colors3[name] = value;
  53400. return this;
  53401. };
  53402. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53403. this._checkUniform(name);
  53404. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53405. color.toArray(arr, arr.length);
  53406. return arr;
  53407. }, []);
  53408. return this;
  53409. };
  53410. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53411. this._checkUniform(name);
  53412. this._colors4[name] = value;
  53413. return this;
  53414. };
  53415. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53416. this._checkUniform(name);
  53417. this._vectors2[name] = value;
  53418. return this;
  53419. };
  53420. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53421. this._checkUniform(name);
  53422. this._vectors3[name] = value;
  53423. return this;
  53424. };
  53425. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53426. this._checkUniform(name);
  53427. this._vectors4[name] = value;
  53428. return this;
  53429. };
  53430. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53431. this._checkUniform(name);
  53432. this._matrices[name] = value;
  53433. return this;
  53434. };
  53435. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53436. this._checkUniform(name);
  53437. this._matrices3x3[name] = value;
  53438. return this;
  53439. };
  53440. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53441. this._checkUniform(name);
  53442. this._matrices2x2[name] = value;
  53443. return this;
  53444. };
  53445. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53446. this._checkUniform(name);
  53447. this._vectors2Arrays[name] = value;
  53448. return this;
  53449. };
  53450. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53451. this._checkUniform(name);
  53452. this._vectors3Arrays[name] = value;
  53453. return this;
  53454. };
  53455. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53456. if (!mesh) {
  53457. return true;
  53458. }
  53459. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53460. return false;
  53461. }
  53462. return false;
  53463. };
  53464. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53465. var scene = this.getScene();
  53466. var engine = scene.getEngine();
  53467. if (!this.checkReadyOnEveryCall) {
  53468. if (this._renderId === scene.getRenderId()) {
  53469. if (this._checkCache(scene, mesh, useInstances)) {
  53470. return true;
  53471. }
  53472. }
  53473. }
  53474. // Instances
  53475. var defines = [];
  53476. var attribs = [];
  53477. var fallbacks = new BABYLON.EffectFallbacks();
  53478. if (useInstances) {
  53479. defines.push("#define INSTANCES");
  53480. }
  53481. for (var index = 0; index < this._options.defines.length; index++) {
  53482. defines.push(this._options.defines[index]);
  53483. }
  53484. for (var index = 0; index < this._options.attributes.length; index++) {
  53485. attribs.push(this._options.attributes[index]);
  53486. }
  53487. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53488. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53489. defines.push("#define VERTEXCOLOR");
  53490. }
  53491. // Bones
  53492. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53493. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53494. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53495. if (mesh.numBoneInfluencers > 4) {
  53496. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53497. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53498. }
  53499. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53500. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53501. fallbacks.addCPUSkinningFallback(0, mesh);
  53502. if (this._options.uniforms.indexOf("mBones") === -1) {
  53503. this._options.uniforms.push("mBones");
  53504. }
  53505. }
  53506. else {
  53507. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53508. }
  53509. // Textures
  53510. for (var name in this._textures) {
  53511. if (!this._textures[name].isReady()) {
  53512. return false;
  53513. }
  53514. }
  53515. // Alpha test
  53516. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53517. defines.push("#define ALPHATEST");
  53518. }
  53519. var previousEffect = this._effect;
  53520. var join = defines.join("\n");
  53521. this._effect = engine.createEffect(this._shaderPath, {
  53522. attributes: attribs,
  53523. uniformsNames: this._options.uniforms,
  53524. uniformBuffersNames: this._options.uniformBuffers,
  53525. samplers: this._options.samplers,
  53526. defines: join,
  53527. fallbacks: fallbacks,
  53528. onCompiled: this.onCompiled,
  53529. onError: this.onError
  53530. }, engine);
  53531. if (!this._effect.isReady()) {
  53532. return false;
  53533. }
  53534. if (previousEffect !== this._effect) {
  53535. scene.resetCachedMaterial();
  53536. }
  53537. this._renderId = scene.getRenderId();
  53538. return true;
  53539. };
  53540. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53541. var scene = this.getScene();
  53542. if (!this._effect) {
  53543. return;
  53544. }
  53545. if (this._options.uniforms.indexOf("world") !== -1) {
  53546. this._effect.setMatrix("world", world);
  53547. }
  53548. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53549. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53550. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53551. }
  53552. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53553. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53554. }
  53555. };
  53556. ShaderMaterial.prototype.bind = function (world, mesh) {
  53557. // Std values
  53558. this.bindOnlyWorldMatrix(world);
  53559. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53560. if (this._options.uniforms.indexOf("view") !== -1) {
  53561. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53562. }
  53563. if (this._options.uniforms.indexOf("projection") !== -1) {
  53564. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53565. }
  53566. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53567. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53568. }
  53569. // Bones
  53570. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53571. var name;
  53572. // Texture
  53573. for (name in this._textures) {
  53574. this._effect.setTexture(name, this._textures[name]);
  53575. }
  53576. // Texture arrays
  53577. for (name in this._textureArrays) {
  53578. this._effect.setTextureArray(name, this._textureArrays[name]);
  53579. }
  53580. // Int
  53581. for (name in this._ints) {
  53582. this._effect.setInt(name, this._ints[name]);
  53583. }
  53584. // Float
  53585. for (name in this._floats) {
  53586. this._effect.setFloat(name, this._floats[name]);
  53587. }
  53588. // Floats
  53589. for (name in this._floatsArrays) {
  53590. this._effect.setArray(name, this._floatsArrays[name]);
  53591. }
  53592. // Color3
  53593. for (name in this._colors3) {
  53594. this._effect.setColor3(name, this._colors3[name]);
  53595. }
  53596. for (name in this._colors3Arrays) {
  53597. this._effect.setArray3(name, this._colors3Arrays[name]);
  53598. }
  53599. // Color4
  53600. for (name in this._colors4) {
  53601. var color = this._colors4[name];
  53602. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53603. }
  53604. // Vector2
  53605. for (name in this._vectors2) {
  53606. this._effect.setVector2(name, this._vectors2[name]);
  53607. }
  53608. // Vector3
  53609. for (name in this._vectors3) {
  53610. this._effect.setVector3(name, this._vectors3[name]);
  53611. }
  53612. // Vector4
  53613. for (name in this._vectors4) {
  53614. this._effect.setVector4(name, this._vectors4[name]);
  53615. }
  53616. // Matrix
  53617. for (name in this._matrices) {
  53618. this._effect.setMatrix(name, this._matrices[name]);
  53619. }
  53620. // Matrix 3x3
  53621. for (name in this._matrices3x3) {
  53622. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53623. }
  53624. // Matrix 2x2
  53625. for (name in this._matrices2x2) {
  53626. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53627. }
  53628. // Vector2Array
  53629. for (name in this._vectors2Arrays) {
  53630. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53631. }
  53632. // Vector3Array
  53633. for (name in this._vectors3Arrays) {
  53634. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53635. }
  53636. }
  53637. this._afterBind(mesh);
  53638. };
  53639. ShaderMaterial.prototype.getActiveTextures = function () {
  53640. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53641. for (var name in this._textures) {
  53642. activeTextures.push(this._textures[name]);
  53643. }
  53644. for (var name in this._textureArrays) {
  53645. var array = this._textureArrays[name];
  53646. for (var index = 0; index < array.length; index++) {
  53647. activeTextures.push(array[index]);
  53648. }
  53649. }
  53650. return activeTextures;
  53651. };
  53652. ShaderMaterial.prototype.hasTexture = function (texture) {
  53653. if (_super.prototype.hasTexture.call(this, texture)) {
  53654. return true;
  53655. }
  53656. for (var name in this._textures) {
  53657. if (this._textures[name] === texture) {
  53658. return true;
  53659. }
  53660. }
  53661. for (var name in this._textureArrays) {
  53662. var array = this._textureArrays[name];
  53663. for (var index = 0; index < array.length; index++) {
  53664. if (array[index] === texture) {
  53665. return true;
  53666. }
  53667. }
  53668. }
  53669. return false;
  53670. };
  53671. ShaderMaterial.prototype.clone = function (name) {
  53672. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53673. return newShaderMaterial;
  53674. };
  53675. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53676. if (forceDisposeTextures) {
  53677. var name;
  53678. for (name in this._textures) {
  53679. this._textures[name].dispose();
  53680. }
  53681. for (name in this._textureArrays) {
  53682. var array = this._textureArrays[name];
  53683. for (var index = 0; index < array.length; index++) {
  53684. array[index].dispose();
  53685. }
  53686. }
  53687. }
  53688. this._textures = {};
  53689. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53690. };
  53691. ShaderMaterial.prototype.serialize = function () {
  53692. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53693. serializationObject.customType = "BABYLON.ShaderMaterial";
  53694. serializationObject.options = this._options;
  53695. serializationObject.shaderPath = this._shaderPath;
  53696. var name;
  53697. // Texture
  53698. serializationObject.textures = {};
  53699. for (name in this._textures) {
  53700. serializationObject.textures[name] = this._textures[name].serialize();
  53701. }
  53702. // Texture arrays
  53703. serializationObject.textureArrays = {};
  53704. for (name in this._textureArrays) {
  53705. serializationObject.textureArrays[name] = [];
  53706. var array = this._textureArrays[name];
  53707. for (var index = 0; index < array.length; index++) {
  53708. serializationObject.textureArrays[name].push(array[index].serialize());
  53709. }
  53710. }
  53711. // Float
  53712. serializationObject.floats = {};
  53713. for (name in this._floats) {
  53714. serializationObject.floats[name] = this._floats[name];
  53715. }
  53716. // Float s
  53717. serializationObject.FloatArrays = {};
  53718. for (name in this._floatsArrays) {
  53719. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53720. }
  53721. // Color3
  53722. serializationObject.colors3 = {};
  53723. for (name in this._colors3) {
  53724. serializationObject.colors3[name] = this._colors3[name].asArray();
  53725. }
  53726. // Color3 array
  53727. serializationObject.colors3Arrays = {};
  53728. for (name in this._colors3Arrays) {
  53729. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53730. }
  53731. // Color4
  53732. serializationObject.colors4 = {};
  53733. for (name in this._colors4) {
  53734. serializationObject.colors4[name] = this._colors4[name].asArray();
  53735. }
  53736. // Vector2
  53737. serializationObject.vectors2 = {};
  53738. for (name in this._vectors2) {
  53739. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53740. }
  53741. // Vector3
  53742. serializationObject.vectors3 = {};
  53743. for (name in this._vectors3) {
  53744. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53745. }
  53746. // Vector4
  53747. serializationObject.vectors4 = {};
  53748. for (name in this._vectors4) {
  53749. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53750. }
  53751. // Matrix
  53752. serializationObject.matrices = {};
  53753. for (name in this._matrices) {
  53754. serializationObject.matrices[name] = this._matrices[name].asArray();
  53755. }
  53756. // Matrix 3x3
  53757. serializationObject.matrices3x3 = {};
  53758. for (name in this._matrices3x3) {
  53759. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53760. }
  53761. // Matrix 2x2
  53762. serializationObject.matrices2x2 = {};
  53763. for (name in this._matrices2x2) {
  53764. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53765. }
  53766. // Vector2Array
  53767. serializationObject.vectors2Arrays = {};
  53768. for (name in this._vectors2Arrays) {
  53769. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53770. }
  53771. // Vector3Array
  53772. serializationObject.vectors3Arrays = {};
  53773. for (name in this._vectors3Arrays) {
  53774. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53775. }
  53776. return serializationObject;
  53777. };
  53778. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53779. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53780. var name;
  53781. // Texture
  53782. for (name in source.textures) {
  53783. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53784. }
  53785. // Texture arrays
  53786. for (name in source.textureArrays) {
  53787. var array = source.textureArrays[name];
  53788. var textureArray = new Array();
  53789. for (var index = 0; index < array.length; index++) {
  53790. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53791. }
  53792. material.setTextureArray(name, textureArray);
  53793. }
  53794. // Float
  53795. for (name in source.floats) {
  53796. material.setFloat(name, source.floats[name]);
  53797. }
  53798. // Float s
  53799. for (name in source.floatsArrays) {
  53800. material.setFloats(name, source.floatsArrays[name]);
  53801. }
  53802. // Color3
  53803. for (name in source.colors3) {
  53804. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53805. }
  53806. // Color3 arrays
  53807. for (name in source.colors3Arrays) {
  53808. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53809. if (i % 3 === 0) {
  53810. arr.push([num]);
  53811. }
  53812. else {
  53813. arr[arr.length - 1].push(num);
  53814. }
  53815. return arr;
  53816. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53817. material.setColor3Array(name, colors);
  53818. }
  53819. // Color4
  53820. for (name in source.colors4) {
  53821. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53822. }
  53823. // Vector2
  53824. for (name in source.vectors2) {
  53825. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53826. }
  53827. // Vector3
  53828. for (name in source.vectors3) {
  53829. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53830. }
  53831. // Vector4
  53832. for (name in source.vectors4) {
  53833. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53834. }
  53835. // Matrix
  53836. for (name in source.matrices) {
  53837. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53838. }
  53839. // Matrix 3x3
  53840. for (name in source.matrices3x3) {
  53841. material.setMatrix3x3(name, source.matrices3x3[name]);
  53842. }
  53843. // Matrix 2x2
  53844. for (name in source.matrices2x2) {
  53845. material.setMatrix2x2(name, source.matrices2x2[name]);
  53846. }
  53847. // Vector2Array
  53848. for (name in source.vectors2Arrays) {
  53849. material.setArray2(name, source.vectors2Arrays[name]);
  53850. }
  53851. // Vector3Array
  53852. for (name in source.vectors3Arrays) {
  53853. material.setArray3(name, source.vectors3Arrays[name]);
  53854. }
  53855. return material;
  53856. };
  53857. return ShaderMaterial;
  53858. }(BABYLON.Material));
  53859. BABYLON.ShaderMaterial = ShaderMaterial;
  53860. })(BABYLON || (BABYLON = {}));
  53861. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53862. var BABYLON;
  53863. (function (BABYLON) {
  53864. var GroundMesh = /** @class */ (function (_super) {
  53865. __extends(GroundMesh, _super);
  53866. function GroundMesh(name, scene) {
  53867. var _this = _super.call(this, name, scene) || this;
  53868. _this.generateOctree = false;
  53869. return _this;
  53870. }
  53871. GroundMesh.prototype.getClassName = function () {
  53872. return "GroundMesh";
  53873. };
  53874. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53875. get: function () {
  53876. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53877. },
  53878. enumerable: true,
  53879. configurable: true
  53880. });
  53881. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53882. get: function () {
  53883. return this._subdivisionsX;
  53884. },
  53885. enumerable: true,
  53886. configurable: true
  53887. });
  53888. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53889. get: function () {
  53890. return this._subdivisionsY;
  53891. },
  53892. enumerable: true,
  53893. configurable: true
  53894. });
  53895. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53896. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53897. this._subdivisionsX = chunksCount;
  53898. this._subdivisionsY = chunksCount;
  53899. this.subdivide(chunksCount);
  53900. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53901. };
  53902. /**
  53903. * Returns a height (y) value in the Worl system :
  53904. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53905. * Returns the ground y position if (x, z) are outside the ground surface.
  53906. */
  53907. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53908. var world = this.getWorldMatrix();
  53909. var invMat = BABYLON.Tmp.Matrix[5];
  53910. world.invertToRef(invMat);
  53911. var tmpVect = BABYLON.Tmp.Vector3[8];
  53912. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53913. x = tmpVect.x;
  53914. z = tmpVect.z;
  53915. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53916. return this.position.y;
  53917. }
  53918. if (!this._heightQuads || this._heightQuads.length == 0) {
  53919. this._initHeightQuads();
  53920. this._computeHeightQuads();
  53921. }
  53922. var facet = this._getFacetAt(x, z);
  53923. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53924. // return y in the World system
  53925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53926. return tmpVect.y;
  53927. };
  53928. /**
  53929. * Returns a normalized vector (Vector3) orthogonal to the ground
  53930. * at the ground coordinates (x, z) expressed in the World system.
  53931. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53932. */
  53933. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53934. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53935. this.getNormalAtCoordinatesToRef(x, z, normal);
  53936. return normal;
  53937. };
  53938. /**
  53939. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53940. * at the ground coordinates (x, z) expressed in the World system.
  53941. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53942. * Returns the GroundMesh.
  53943. */
  53944. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53945. var world = this.getWorldMatrix();
  53946. var tmpMat = BABYLON.Tmp.Matrix[5];
  53947. world.invertToRef(tmpMat);
  53948. var tmpVect = BABYLON.Tmp.Vector3[8];
  53949. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53950. x = tmpVect.x;
  53951. z = tmpVect.z;
  53952. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53953. return this;
  53954. }
  53955. if (!this._heightQuads || this._heightQuads.length == 0) {
  53956. this._initHeightQuads();
  53957. this._computeHeightQuads();
  53958. }
  53959. var facet = this._getFacetAt(x, z);
  53960. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53961. return this;
  53962. };
  53963. /**
  53964. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53965. * if the ground has been updated.
  53966. * This can be used in the render loop.
  53967. * Returns the GroundMesh.
  53968. */
  53969. GroundMesh.prototype.updateCoordinateHeights = function () {
  53970. if (!this._heightQuads || this._heightQuads.length == 0) {
  53971. this._initHeightQuads();
  53972. }
  53973. this._computeHeightQuads();
  53974. return this;
  53975. };
  53976. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53977. GroundMesh.prototype._getFacetAt = function (x, z) {
  53978. // retrieve col and row from x, z coordinates in the ground local system
  53979. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53980. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53981. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53982. var facet;
  53983. if (z < quad.slope.x * x + quad.slope.y) {
  53984. facet = quad.facet1;
  53985. }
  53986. else {
  53987. facet = quad.facet2;
  53988. }
  53989. return facet;
  53990. };
  53991. // Creates and populates the heightMap array with "facet" elements :
  53992. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53993. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53994. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53995. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53996. // Returns the GroundMesh.
  53997. GroundMesh.prototype._initHeightQuads = function () {
  53998. var subdivisionsX = this._subdivisionsX;
  53999. var subdivisionsY = this._subdivisionsY;
  54000. this._heightQuads = new Array();
  54001. for (var row = 0; row < subdivisionsY; row++) {
  54002. for (var col = 0; col < subdivisionsX; col++) {
  54003. 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) };
  54004. this._heightQuads[row * subdivisionsX + col] = quad;
  54005. }
  54006. }
  54007. return this;
  54008. };
  54009. // Compute each quad element values and update the the heightMap array :
  54010. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54011. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54012. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54013. // Returns the GroundMesh.
  54014. GroundMesh.prototype._computeHeightQuads = function () {
  54015. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54016. if (!positions) {
  54017. return this;
  54018. }
  54019. var v1 = BABYLON.Tmp.Vector3[3];
  54020. var v2 = BABYLON.Tmp.Vector3[2];
  54021. var v3 = BABYLON.Tmp.Vector3[1];
  54022. var v4 = BABYLON.Tmp.Vector3[0];
  54023. var v1v2 = BABYLON.Tmp.Vector3[4];
  54024. var v1v3 = BABYLON.Tmp.Vector3[5];
  54025. var v1v4 = BABYLON.Tmp.Vector3[6];
  54026. var norm1 = BABYLON.Tmp.Vector3[7];
  54027. var norm2 = BABYLON.Tmp.Vector3[8];
  54028. var i = 0;
  54029. var j = 0;
  54030. var k = 0;
  54031. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54032. var h = 0;
  54033. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54034. var d2 = 0;
  54035. var subdivisionsX = this._subdivisionsX;
  54036. var subdivisionsY = this._subdivisionsY;
  54037. for (var row = 0; row < subdivisionsY; row++) {
  54038. for (var col = 0; col < subdivisionsX; col++) {
  54039. i = col * 3;
  54040. j = row * (subdivisionsX + 1) * 3;
  54041. k = (row + 1) * (subdivisionsX + 1) * 3;
  54042. v1.x = positions[j + i];
  54043. v1.y = positions[j + i + 1];
  54044. v1.z = positions[j + i + 2];
  54045. v2.x = positions[j + i + 3];
  54046. v2.y = positions[j + i + 4];
  54047. v2.z = positions[j + i + 5];
  54048. v3.x = positions[k + i];
  54049. v3.y = positions[k + i + 1];
  54050. v3.z = positions[k + i + 2];
  54051. v4.x = positions[k + i + 3];
  54052. v4.y = positions[k + i + 4];
  54053. v4.z = positions[k + i + 5];
  54054. // 2D slope V1V4
  54055. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54056. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54057. // facet equations :
  54058. // we compute each facet normal vector
  54059. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54060. // we compute the value d by applying the equation to v1 which belongs to the plane
  54061. // then we store the facet equation in a Vector4
  54062. v2.subtractToRef(v1, v1v2);
  54063. v3.subtractToRef(v1, v1v3);
  54064. v4.subtractToRef(v1, v1v4);
  54065. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54066. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54067. norm1.normalize();
  54068. norm2.normalize();
  54069. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54070. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54071. var quad = this._heightQuads[row * subdivisionsX + col];
  54072. quad.slope.copyFromFloats(cd, h);
  54073. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54074. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54075. }
  54076. }
  54077. return this;
  54078. };
  54079. GroundMesh.prototype.serialize = function (serializationObject) {
  54080. _super.prototype.serialize.call(this, serializationObject);
  54081. serializationObject.subdivisionsX = this._subdivisionsX;
  54082. serializationObject.subdivisionsY = this._subdivisionsY;
  54083. serializationObject.minX = this._minX;
  54084. serializationObject.maxX = this._maxX;
  54085. serializationObject.minZ = this._minZ;
  54086. serializationObject.maxZ = this._maxZ;
  54087. serializationObject.width = this._width;
  54088. serializationObject.height = this._height;
  54089. };
  54090. GroundMesh.Parse = function (parsedMesh, scene) {
  54091. var result = new GroundMesh(parsedMesh.name, scene);
  54092. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54093. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54094. result._minX = parsedMesh.minX;
  54095. result._maxX = parsedMesh.maxX;
  54096. result._minZ = parsedMesh.minZ;
  54097. result._maxZ = parsedMesh.maxZ;
  54098. result._width = parsedMesh.width;
  54099. result._height = parsedMesh.height;
  54100. return result;
  54101. };
  54102. return GroundMesh;
  54103. }(BABYLON.Mesh));
  54104. BABYLON.GroundMesh = GroundMesh;
  54105. })(BABYLON || (BABYLON = {}));
  54106. //# sourceMappingURL=babylon.groundMesh.js.map
  54107. var BABYLON;
  54108. (function (BABYLON) {
  54109. /**
  54110. * Creates an instance based on a source mesh.
  54111. */
  54112. var InstancedMesh = /** @class */ (function (_super) {
  54113. __extends(InstancedMesh, _super);
  54114. function InstancedMesh(name, source) {
  54115. var _this = _super.call(this, name, source.getScene()) || this;
  54116. source.instances.push(_this);
  54117. _this._sourceMesh = source;
  54118. _this.position.copyFrom(source.position);
  54119. _this.rotation.copyFrom(source.rotation);
  54120. _this.scaling.copyFrom(source.scaling);
  54121. if (source.rotationQuaternion) {
  54122. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54123. }
  54124. _this.infiniteDistance = source.infiniteDistance;
  54125. _this.setPivotMatrix(source.getPivotMatrix());
  54126. _this.refreshBoundingInfo();
  54127. _this._syncSubMeshes();
  54128. return _this;
  54129. }
  54130. /**
  54131. * Returns the string "InstancedMesh".
  54132. */
  54133. InstancedMesh.prototype.getClassName = function () {
  54134. return "InstancedMesh";
  54135. };
  54136. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54137. // Methods
  54138. get: function () {
  54139. return this._sourceMesh.receiveShadows;
  54140. },
  54141. enumerable: true,
  54142. configurable: true
  54143. });
  54144. Object.defineProperty(InstancedMesh.prototype, "material", {
  54145. get: function () {
  54146. return this._sourceMesh.material;
  54147. },
  54148. enumerable: true,
  54149. configurable: true
  54150. });
  54151. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54152. get: function () {
  54153. return this._sourceMesh.visibility;
  54154. },
  54155. enumerable: true,
  54156. configurable: true
  54157. });
  54158. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54159. get: function () {
  54160. return this._sourceMesh.skeleton;
  54161. },
  54162. enumerable: true,
  54163. configurable: true
  54164. });
  54165. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54166. get: function () {
  54167. return this._sourceMesh.renderingGroupId;
  54168. },
  54169. enumerable: true,
  54170. configurable: true
  54171. });
  54172. /**
  54173. * Returns the total number of vertices (integer).
  54174. */
  54175. InstancedMesh.prototype.getTotalVertices = function () {
  54176. return this._sourceMesh.getTotalVertices();
  54177. };
  54178. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54179. get: function () {
  54180. return this._sourceMesh;
  54181. },
  54182. enumerable: true,
  54183. configurable: true
  54184. });
  54185. /**
  54186. * Is this node ready to be used/rendered
  54187. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54188. * @return {boolean} is it ready
  54189. */
  54190. InstancedMesh.prototype.isReady = function (completeCheck) {
  54191. if (completeCheck === void 0) { completeCheck = false; }
  54192. return this._sourceMesh.isReady(completeCheck, true);
  54193. };
  54194. /**
  54195. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54196. */
  54197. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54198. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54199. };
  54200. /**
  54201. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54202. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54203. * The `data` are either a numeric array either a Float32Array.
  54204. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54205. * 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).
  54206. * Note that a new underlying VertexBuffer object is created each call.
  54207. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54208. *
  54209. * Possible `kind` values :
  54210. * - BABYLON.VertexBuffer.PositionKind
  54211. * - BABYLON.VertexBuffer.UVKind
  54212. * - BABYLON.VertexBuffer.UV2Kind
  54213. * - BABYLON.VertexBuffer.UV3Kind
  54214. * - BABYLON.VertexBuffer.UV4Kind
  54215. * - BABYLON.VertexBuffer.UV5Kind
  54216. * - BABYLON.VertexBuffer.UV6Kind
  54217. * - BABYLON.VertexBuffer.ColorKind
  54218. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54219. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54220. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54221. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54222. *
  54223. * Returns the Mesh.
  54224. */
  54225. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54226. if (this.sourceMesh) {
  54227. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54228. }
  54229. return this.sourceMesh;
  54230. };
  54231. /**
  54232. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54233. * If the mesh has no geometry, it is simply returned as it is.
  54234. * The `data` are either a numeric array either a Float32Array.
  54235. * No new underlying VertexBuffer object is created.
  54236. * 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.
  54237. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54238. *
  54239. * Possible `kind` values :
  54240. * - BABYLON.VertexBuffer.PositionKind
  54241. * - BABYLON.VertexBuffer.UVKind
  54242. * - BABYLON.VertexBuffer.UV2Kind
  54243. * - BABYLON.VertexBuffer.UV3Kind
  54244. * - BABYLON.VertexBuffer.UV4Kind
  54245. * - BABYLON.VertexBuffer.UV5Kind
  54246. * - BABYLON.VertexBuffer.UV6Kind
  54247. * - BABYLON.VertexBuffer.ColorKind
  54248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54252. *
  54253. * Returns the Mesh.
  54254. */
  54255. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54256. if (this.sourceMesh) {
  54257. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54258. }
  54259. return this.sourceMesh;
  54260. };
  54261. /**
  54262. * Sets the mesh indices.
  54263. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54264. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54265. * This method creates a new index buffer each call.
  54266. * Returns the Mesh.
  54267. */
  54268. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54269. if (totalVertices === void 0) { totalVertices = null; }
  54270. if (this.sourceMesh) {
  54271. this.sourceMesh.setIndices(indices, totalVertices);
  54272. }
  54273. return this.sourceMesh;
  54274. };
  54275. /**
  54276. * Boolean : True if the mesh owns the requested kind of data.
  54277. */
  54278. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54279. return this._sourceMesh.isVerticesDataPresent(kind);
  54280. };
  54281. /**
  54282. * Returns an array of indices (IndicesArray).
  54283. */
  54284. InstancedMesh.prototype.getIndices = function () {
  54285. return this._sourceMesh.getIndices();
  54286. };
  54287. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54288. get: function () {
  54289. return this._sourceMesh._positions;
  54290. },
  54291. enumerable: true,
  54292. configurable: true
  54293. });
  54294. /**
  54295. * Sets a new updated BoundingInfo to the mesh.
  54296. * Returns the mesh.
  54297. */
  54298. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54299. var meshBB = this._sourceMesh.getBoundingInfo();
  54300. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54301. this._updateBoundingInfo();
  54302. return this;
  54303. };
  54304. InstancedMesh.prototype._preActivate = function () {
  54305. if (this._currentLOD) {
  54306. this._currentLOD._preActivate();
  54307. }
  54308. return this;
  54309. };
  54310. InstancedMesh.prototype._activate = function (renderId) {
  54311. if (this._currentLOD) {
  54312. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54313. }
  54314. return this;
  54315. };
  54316. /**
  54317. * Returns the current associated LOD AbstractMesh.
  54318. */
  54319. InstancedMesh.prototype.getLOD = function (camera) {
  54320. if (!camera) {
  54321. return this;
  54322. }
  54323. var boundingInfo = this.getBoundingInfo();
  54324. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54325. if (this._currentLOD === this.sourceMesh) {
  54326. return this;
  54327. }
  54328. return this._currentLOD;
  54329. };
  54330. InstancedMesh.prototype._syncSubMeshes = function () {
  54331. this.releaseSubMeshes();
  54332. if (this._sourceMesh.subMeshes) {
  54333. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54334. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54335. }
  54336. }
  54337. return this;
  54338. };
  54339. InstancedMesh.prototype._generatePointsArray = function () {
  54340. return this._sourceMesh._generatePointsArray();
  54341. };
  54342. /**
  54343. * Creates a new InstancedMesh from the current mesh.
  54344. * - name (string) : the cloned mesh name
  54345. * - newParent (optional Node) : the optional Node to parent the clone to.
  54346. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54347. *
  54348. * Returns the clone.
  54349. */
  54350. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54351. var result = this._sourceMesh.createInstance(name);
  54352. // Deep copy
  54353. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54354. // Bounding info
  54355. this.refreshBoundingInfo();
  54356. // Parent
  54357. if (newParent) {
  54358. result.parent = newParent;
  54359. }
  54360. if (!doNotCloneChildren) {
  54361. // Children
  54362. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54363. var mesh = this.getScene().meshes[index];
  54364. if (mesh.parent === this) {
  54365. mesh.clone(mesh.name, result);
  54366. }
  54367. }
  54368. }
  54369. result.computeWorldMatrix(true);
  54370. return result;
  54371. };
  54372. /**
  54373. * Disposes the InstancedMesh.
  54374. * Returns nothing.
  54375. */
  54376. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54377. // Remove from mesh
  54378. var index = this._sourceMesh.instances.indexOf(this);
  54379. this._sourceMesh.instances.splice(index, 1);
  54380. _super.prototype.dispose.call(this, doNotRecurse);
  54381. };
  54382. return InstancedMesh;
  54383. }(BABYLON.AbstractMesh));
  54384. BABYLON.InstancedMesh = InstancedMesh;
  54385. })(BABYLON || (BABYLON = {}));
  54386. //# sourceMappingURL=babylon.instancedMesh.js.map
  54387. var BABYLON;
  54388. (function (BABYLON) {
  54389. var LinesMesh = /** @class */ (function (_super) {
  54390. __extends(LinesMesh, _super);
  54391. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54392. if (scene === void 0) { scene = null; }
  54393. if (parent === void 0) { parent = null; }
  54394. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54395. _this.useVertexColor = useVertexColor;
  54396. _this.useVertexAlpha = useVertexAlpha;
  54397. _this.color = new BABYLON.Color3(1, 1, 1);
  54398. _this.alpha = 1;
  54399. if (source) {
  54400. _this.color = source.color.clone();
  54401. _this.alpha = source.alpha;
  54402. _this.useVertexColor = source.useVertexColor;
  54403. _this.useVertexAlpha = source.useVertexAlpha;
  54404. }
  54405. _this._intersectionThreshold = 0.1;
  54406. var defines = [];
  54407. var options = {
  54408. attributes: [BABYLON.VertexBuffer.PositionKind],
  54409. uniforms: ["world", "viewProjection"],
  54410. needAlphaBlending: true,
  54411. defines: defines
  54412. };
  54413. if (useVertexAlpha === false) {
  54414. options.needAlphaBlending = false;
  54415. }
  54416. if (!useVertexColor) {
  54417. options.uniforms.push("color");
  54418. }
  54419. else {
  54420. options.defines.push("#define VERTEXCOLOR");
  54421. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54422. }
  54423. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54424. return _this;
  54425. }
  54426. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54427. /**
  54428. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54429. * This margin is expressed in world space coordinates, so its value may vary.
  54430. * Default value is 0.1
  54431. * @returns the intersection Threshold value.
  54432. */
  54433. get: function () {
  54434. return this._intersectionThreshold;
  54435. },
  54436. /**
  54437. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54438. * This margin is expressed in world space coordinates, so its value may vary.
  54439. * @param value the new threshold to apply
  54440. */
  54441. set: function (value) {
  54442. if (this._intersectionThreshold === value) {
  54443. return;
  54444. }
  54445. this._intersectionThreshold = value;
  54446. if (this.geometry) {
  54447. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54448. }
  54449. },
  54450. enumerable: true,
  54451. configurable: true
  54452. });
  54453. /**
  54454. * Returns the string "LineMesh"
  54455. */
  54456. LinesMesh.prototype.getClassName = function () {
  54457. return "LinesMesh";
  54458. };
  54459. Object.defineProperty(LinesMesh.prototype, "material", {
  54460. get: function () {
  54461. return this._colorShader;
  54462. },
  54463. set: function (value) {
  54464. // Do nothing
  54465. },
  54466. enumerable: true,
  54467. configurable: true
  54468. });
  54469. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54470. get: function () {
  54471. return false;
  54472. },
  54473. enumerable: true,
  54474. configurable: true
  54475. });
  54476. LinesMesh.prototype.createInstance = function (name) {
  54477. throw new Error("LinesMeshes do not support createInstance.");
  54478. };
  54479. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54480. if (!this._geometry) {
  54481. return this;
  54482. }
  54483. // VBOs
  54484. this._geometry._bind(this._colorShader.getEffect());
  54485. // Color
  54486. if (!this.useVertexColor) {
  54487. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54488. }
  54489. return this;
  54490. };
  54491. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54492. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54493. return this;
  54494. }
  54495. var engine = this.getScene().getEngine();
  54496. // Draw order
  54497. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54498. return this;
  54499. };
  54500. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54501. this._colorShader.dispose();
  54502. _super.prototype.dispose.call(this, doNotRecurse);
  54503. };
  54504. /**
  54505. * Returns a new LineMesh object cloned from the current one.
  54506. */
  54507. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54508. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54509. };
  54510. return LinesMesh;
  54511. }(BABYLON.Mesh));
  54512. BABYLON.LinesMesh = LinesMesh;
  54513. })(BABYLON || (BABYLON = {}));
  54514. //# sourceMappingURL=babylon.linesMesh.js.map
  54515. var BABYLON;
  54516. (function (BABYLON) {
  54517. var MeshBuilder = /** @class */ (function () {
  54518. function MeshBuilder() {
  54519. }
  54520. MeshBuilder.updateSideOrientation = function (orientation) {
  54521. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54522. return BABYLON.Mesh.DOUBLESIDE;
  54523. }
  54524. if (orientation === undefined || orientation === null) {
  54525. return BABYLON.Mesh.FRONTSIDE;
  54526. }
  54527. return orientation;
  54528. };
  54529. /**
  54530. * Creates a box mesh.
  54531. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54532. * The parameter `size` sets the size (float) of each box side (default 1).
  54533. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54534. * 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).
  54535. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54536. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54537. * 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).
  54538. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54540. */
  54541. MeshBuilder.CreateBox = function (name, options, scene) {
  54542. if (scene === void 0) { scene = null; }
  54543. var box = new BABYLON.Mesh(name, scene);
  54544. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54545. box._originalBuilderSideOrientation = options.sideOrientation;
  54546. var vertexData = BABYLON.VertexData.CreateBox(options);
  54547. vertexData.applyToMesh(box, options.updatable);
  54548. return box;
  54549. };
  54550. /**
  54551. * Creates a sphere mesh.
  54552. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54553. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54554. * 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`).
  54555. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54556. * 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
  54557. * 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).
  54558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54559. * 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).
  54560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54562. */
  54563. MeshBuilder.CreateSphere = function (name, options, scene) {
  54564. var sphere = new BABYLON.Mesh(name, scene);
  54565. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54566. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54567. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54568. vertexData.applyToMesh(sphere, options.updatable);
  54569. return sphere;
  54570. };
  54571. /**
  54572. * Creates a plane polygonal mesh. By default, this is a disc.
  54573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54574. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54575. * 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.
  54576. * 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
  54577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54578. * 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).
  54579. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54581. */
  54582. MeshBuilder.CreateDisc = function (name, options, scene) {
  54583. if (scene === void 0) { scene = null; }
  54584. var disc = new BABYLON.Mesh(name, scene);
  54585. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54586. disc._originalBuilderSideOrientation = options.sideOrientation;
  54587. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54588. vertexData.applyToMesh(disc, options.updatable);
  54589. return disc;
  54590. };
  54591. /**
  54592. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54593. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54594. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54595. * 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`).
  54596. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54597. * 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.
  54598. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54599. * 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).
  54600. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54602. */
  54603. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54604. var sphere = new BABYLON.Mesh(name, scene);
  54605. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54606. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54607. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54608. vertexData.applyToMesh(sphere, options.updatable);
  54609. return sphere;
  54610. };
  54611. ;
  54612. /**
  54613. * Creates a ribbon mesh.
  54614. * 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.
  54615. *
  54616. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54617. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54618. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54619. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54620. * 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.
  54621. * 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.
  54622. * 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
  54623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54624. * 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).
  54625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54626. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54627. * 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.
  54628. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54629. * 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
  54630. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54631. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54633. */
  54634. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54635. if (scene === void 0) { scene = null; }
  54636. var pathArray = options.pathArray;
  54637. var closeArray = options.closeArray;
  54638. var closePath = options.closePath;
  54639. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54640. var instance = options.instance;
  54641. var updatable = options.updatable;
  54642. if (instance) {
  54643. // positionFunction : ribbon case
  54644. // only pathArray and sideOrientation parameters are taken into account for positions update
  54645. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54646. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54647. var positionFunction = function (positions) {
  54648. var minlg = pathArray[0].length;
  54649. var i = 0;
  54650. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54651. for (var si = 1; si <= ns; si++) {
  54652. for (var p = 0; p < pathArray.length; p++) {
  54653. var path = pathArray[p];
  54654. var l = path.length;
  54655. minlg = (minlg < l) ? minlg : l;
  54656. var j = 0;
  54657. while (j < minlg) {
  54658. positions[i] = path[j].x;
  54659. positions[i + 1] = path[j].y;
  54660. positions[i + 2] = path[j].z;
  54661. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54662. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54663. }
  54664. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54665. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54666. }
  54667. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54668. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54669. }
  54670. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54671. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54672. }
  54673. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54674. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54675. }
  54676. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54677. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54678. }
  54679. j++;
  54680. i += 3;
  54681. }
  54682. if (instance._closePath) {
  54683. positions[i] = path[0].x;
  54684. positions[i + 1] = path[0].y;
  54685. positions[i + 2] = path[0].z;
  54686. i += 3;
  54687. }
  54688. }
  54689. }
  54690. };
  54691. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54692. positionFunction(positions);
  54693. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54694. instance._boundingInfo.update(instance._worldMatrix);
  54695. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54696. if (options.colors) {
  54697. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54698. for (var c = 0; c < options.colors.length; c++) {
  54699. colors[c * 4] = options.colors[c].r;
  54700. colors[c * 4 + 1] = options.colors[c].g;
  54701. colors[c * 4 + 2] = options.colors[c].b;
  54702. colors[c * 4 + 3] = options.colors[c].a;
  54703. }
  54704. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54705. }
  54706. if (options.uvs) {
  54707. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54708. for (var i = 0; i < options.uvs.length; i++) {
  54709. uvs[i * 2] = options.uvs[i].x;
  54710. uvs[i * 2 + 1] = options.uvs[i].y;
  54711. }
  54712. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54713. }
  54714. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54715. var indices = instance.getIndices();
  54716. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54717. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54718. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54719. if (instance._closePath) {
  54720. var indexFirst = 0;
  54721. var indexLast = 0;
  54722. for (var p = 0; p < pathArray.length; p++) {
  54723. indexFirst = instance._idx[p] * 3;
  54724. if (p + 1 < pathArray.length) {
  54725. indexLast = (instance._idx[p + 1] - 1) * 3;
  54726. }
  54727. else {
  54728. indexLast = normals.length - 3;
  54729. }
  54730. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54731. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54732. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54733. normals[indexLast] = normals[indexFirst];
  54734. normals[indexLast + 1] = normals[indexFirst + 1];
  54735. normals[indexLast + 2] = normals[indexFirst + 2];
  54736. }
  54737. }
  54738. if (!(instance.areNormalsFrozen)) {
  54739. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54740. }
  54741. }
  54742. return instance;
  54743. }
  54744. else {
  54745. var ribbon = new BABYLON.Mesh(name, scene);
  54746. ribbon._originalBuilderSideOrientation = sideOrientation;
  54747. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54748. if (closePath) {
  54749. ribbon._idx = vertexData._idx;
  54750. }
  54751. ribbon._closePath = closePath;
  54752. ribbon._closeArray = closeArray;
  54753. vertexData.applyToMesh(ribbon, updatable);
  54754. return ribbon;
  54755. }
  54756. };
  54757. /**
  54758. * Creates a cylinder or a cone mesh.
  54759. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54760. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54761. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54762. * 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.
  54763. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54764. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54765. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54766. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54767. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54768. * 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).
  54769. * 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
  54770. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54771. * 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
  54772. * 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.
  54773. * If `enclose` is false, a ring surface is one element.
  54774. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54775. * 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
  54776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54777. * 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).
  54778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54780. */
  54781. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54782. var cylinder = new BABYLON.Mesh(name, scene);
  54783. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54784. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54785. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54786. vertexData.applyToMesh(cylinder, options.updatable);
  54787. return cylinder;
  54788. };
  54789. /**
  54790. * Creates a torus mesh.
  54791. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54792. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54793. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54794. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54796. * 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).
  54797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54799. */
  54800. MeshBuilder.CreateTorus = function (name, options, scene) {
  54801. var torus = new BABYLON.Mesh(name, scene);
  54802. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54803. torus._originalBuilderSideOrientation = options.sideOrientation;
  54804. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54805. vertexData.applyToMesh(torus, options.updatable);
  54806. return torus;
  54807. };
  54808. /**
  54809. * Creates a torus knot mesh.
  54810. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54811. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54812. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54813. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54814. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54815. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54816. * 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).
  54817. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54819. */
  54820. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54821. var torusKnot = new BABYLON.Mesh(name, scene);
  54822. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54823. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54824. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54825. vertexData.applyToMesh(torusKnot, options.updatable);
  54826. return torusKnot;
  54827. };
  54828. /**
  54829. * Creates a line system mesh.
  54830. * A line system is a pool of many lines gathered in a single mesh.
  54831. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54832. * 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.
  54833. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54834. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54835. * 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
  54836. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54837. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54838. * 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
  54839. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54841. */
  54842. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54843. var instance = options.instance;
  54844. var lines = options.lines;
  54845. var colors = options.colors;
  54846. if (instance) {
  54847. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54848. var vertexColor;
  54849. var lineColors;
  54850. if (colors) {
  54851. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54852. }
  54853. var i = 0;
  54854. var c = 0;
  54855. for (var l = 0; l < lines.length; l++) {
  54856. var points = lines[l];
  54857. for (var p = 0; p < points.length; p++) {
  54858. positions[i] = points[p].x;
  54859. positions[i + 1] = points[p].y;
  54860. positions[i + 2] = points[p].z;
  54861. if (colors && vertexColor) {
  54862. lineColors = colors[l];
  54863. vertexColor[c] = lineColors[p].r;
  54864. vertexColor[c + 1] = lineColors[p].g;
  54865. vertexColor[c + 2] = lineColors[p].b;
  54866. vertexColor[c + 3] = lineColors[p].a;
  54867. c += 4;
  54868. }
  54869. i += 3;
  54870. }
  54871. }
  54872. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54873. if (colors && vertexColor) {
  54874. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54875. }
  54876. return instance;
  54877. }
  54878. // line system creation
  54879. var useVertexColor = (colors) ? true : false;
  54880. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54881. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54882. vertexData.applyToMesh(lineSystem, options.updatable);
  54883. return lineSystem;
  54884. };
  54885. /**
  54886. * Creates a line mesh.
  54887. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54888. * 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.
  54889. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54890. * The parameter `points` is an array successive Vector3.
  54891. * 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
  54892. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54893. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54894. * When updating an instance, remember that only point positions can change, not the number of points.
  54895. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54896. */
  54897. MeshBuilder.CreateLines = function (name, options, scene) {
  54898. if (scene === void 0) { scene = null; }
  54899. var colors = (options.colors) ? [options.colors] : null;
  54900. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54901. return lines;
  54902. };
  54903. /**
  54904. * Creates a dashed line mesh.
  54905. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54906. * 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.
  54907. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54908. * The parameter `points` is an array successive Vector3.
  54909. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54910. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54911. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54912. * 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
  54913. * When updating an instance, remember that only point positions can change, not the number of points.
  54914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54915. */
  54916. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54917. if (scene === void 0) { scene = null; }
  54918. var points = options.points;
  54919. var instance = options.instance;
  54920. var gapSize = options.gapSize || 1;
  54921. var dashSize = options.dashSize || 3;
  54922. if (instance) {
  54923. var positionFunction = function (positions) {
  54924. var curvect = BABYLON.Vector3.Zero();
  54925. var nbSeg = positions.length / 6;
  54926. var lg = 0;
  54927. var nb = 0;
  54928. var shft = 0;
  54929. var dashshft = 0;
  54930. var curshft = 0;
  54931. var p = 0;
  54932. var i = 0;
  54933. var j = 0;
  54934. for (i = 0; i < points.length - 1; i++) {
  54935. points[i + 1].subtractToRef(points[i], curvect);
  54936. lg += curvect.length();
  54937. }
  54938. shft = lg / nbSeg;
  54939. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54940. for (i = 0; i < points.length - 1; i++) {
  54941. points[i + 1].subtractToRef(points[i], curvect);
  54942. nb = Math.floor(curvect.length() / shft);
  54943. curvect.normalize();
  54944. j = 0;
  54945. while (j < nb && p < positions.length) {
  54946. curshft = shft * j;
  54947. positions[p] = points[i].x + curshft * curvect.x;
  54948. positions[p + 1] = points[i].y + curshft * curvect.y;
  54949. positions[p + 2] = points[i].z + curshft * curvect.z;
  54950. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54951. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54952. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54953. p += 6;
  54954. j++;
  54955. }
  54956. }
  54957. while (p < positions.length) {
  54958. positions[p] = points[i].x;
  54959. positions[p + 1] = points[i].y;
  54960. positions[p + 2] = points[i].z;
  54961. p += 3;
  54962. }
  54963. };
  54964. instance.updateMeshPositions(positionFunction, false);
  54965. return instance;
  54966. }
  54967. // dashed lines creation
  54968. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54969. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54970. vertexData.applyToMesh(dashedLines, options.updatable);
  54971. dashedLines.dashSize = dashSize;
  54972. dashedLines.gapSize = gapSize;
  54973. return dashedLines;
  54974. };
  54975. /**
  54976. * Creates an extruded shape mesh.
  54977. * 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.
  54978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54979. *
  54980. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54981. * 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
  54982. * extruded along the Z axis.
  54983. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54984. * 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.
  54985. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54986. * 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
  54987. * 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
  54988. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54989. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54990. * 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).
  54991. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54992. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54994. */
  54995. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54996. if (scene === void 0) { scene = null; }
  54997. var path = options.path;
  54998. var shape = options.shape;
  54999. var scale = options.scale || 1;
  55000. var rotation = options.rotation || 0;
  55001. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55002. var updatable = options.updatable;
  55003. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55004. var instance = options.instance || null;
  55005. var invertUV = options.invertUV || false;
  55006. 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);
  55007. };
  55008. /**
  55009. * Creates an custom extruded shape mesh.
  55010. * 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.
  55011. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55012. *
  55013. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55014. * 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
  55015. * extruded along the Z axis.
  55016. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55017. * 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
  55018. * and the distance of this point from the begining of the path :
  55019. * ```javascript
  55020. * var rotationFunction = function(i, distance) {
  55021. * // do things
  55022. * return rotationValue; }
  55023. * ```
  55024. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55025. * 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
  55026. * and the distance of this point from the begining of the path :
  55027. * ```javascript
  55028. * var scaleFunction = function(i, distance) {
  55029. * // do things
  55030. * return scaleValue;}
  55031. * ```
  55032. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55033. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55034. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55035. * 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
  55036. * 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
  55037. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55038. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55039. * 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).
  55040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55041. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55043. */
  55044. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55045. var path = options.path;
  55046. var shape = options.shape;
  55047. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55048. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55049. var ribbonCloseArray = options.ribbonCloseArray || false;
  55050. var ribbonClosePath = options.ribbonClosePath || false;
  55051. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55052. var updatable = options.updatable;
  55053. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55054. var instance = options.instance;
  55055. var invertUV = options.invertUV || false;
  55056. 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);
  55057. };
  55058. /**
  55059. * Creates lathe mesh.
  55060. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55061. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55062. *
  55063. * 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
  55064. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55065. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55066. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55067. * 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.
  55068. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55069. * 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
  55070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55071. * 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).
  55072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55073. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55075. */
  55076. MeshBuilder.CreateLathe = function (name, options, scene) {
  55077. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55078. var closed = (options.closed === undefined) ? true : options.closed;
  55079. var shape = options.shape;
  55080. var radius = options.radius || 1;
  55081. var tessellation = options.tessellation || 64;
  55082. var updatable = options.updatable;
  55083. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55084. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55085. var pi2 = Math.PI * 2;
  55086. var paths = new Array();
  55087. var invertUV = options.invertUV || false;
  55088. var i = 0;
  55089. var p = 0;
  55090. var step = pi2 / tessellation * arc;
  55091. var rotated;
  55092. var path = new Array();
  55093. ;
  55094. for (i = 0; i <= tessellation; i++) {
  55095. var path = [];
  55096. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55097. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55098. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55099. }
  55100. for (p = 0; p < shape.length; p++) {
  55101. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55102. path.push(rotated);
  55103. }
  55104. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55105. 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));
  55106. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55107. }
  55108. paths.push(path);
  55109. }
  55110. // lathe ribbon
  55111. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55112. return lathe;
  55113. };
  55114. /**
  55115. * Creates a plane mesh.
  55116. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55117. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55118. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55119. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55121. * 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).
  55122. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55123. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55124. */
  55125. MeshBuilder.CreatePlane = function (name, options, scene) {
  55126. var plane = new BABYLON.Mesh(name, scene);
  55127. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55128. plane._originalBuilderSideOrientation = options.sideOrientation;
  55129. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55130. vertexData.applyToMesh(plane, options.updatable);
  55131. if (options.sourcePlane) {
  55132. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55133. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55134. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55135. plane.rotate(vectorProduct, product);
  55136. }
  55137. return plane;
  55138. };
  55139. /**
  55140. * Creates a ground mesh.
  55141. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55142. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55143. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55145. */
  55146. MeshBuilder.CreateGround = function (name, options, scene) {
  55147. var ground = new BABYLON.GroundMesh(name, scene);
  55148. ground._setReady(false);
  55149. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55150. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55151. ground._width = options.width || 1;
  55152. ground._height = options.height || 1;
  55153. ground._maxX = ground._width / 2;
  55154. ground._maxZ = ground._height / 2;
  55155. ground._minX = -ground._maxX;
  55156. ground._minZ = -ground._maxZ;
  55157. var vertexData = BABYLON.VertexData.CreateGround(options);
  55158. vertexData.applyToMesh(ground, options.updatable);
  55159. ground._setReady(true);
  55160. return ground;
  55161. };
  55162. /**
  55163. * Creates a tiled ground mesh.
  55164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55165. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55166. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55167. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55168. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55169. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55170. * numbers of subdivisions on the ground width and height of each tile.
  55171. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55172. */
  55173. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55174. var tiledGround = new BABYLON.Mesh(name, scene);
  55175. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55176. vertexData.applyToMesh(tiledGround, options.updatable);
  55177. return tiledGround;
  55178. };
  55179. /**
  55180. * Creates a ground mesh from a height map.
  55181. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55182. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55183. * The parameter `url` sets the URL of the height map image resource.
  55184. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55185. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55186. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55187. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55188. * 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.
  55189. * 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).
  55190. * This function is passed the newly built mesh :
  55191. * ```javascript
  55192. * function(mesh) { // do things
  55193. * return; }
  55194. * ```
  55195. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55196. */
  55197. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55198. var width = options.width || 10.0;
  55199. var height = options.height || 10.0;
  55200. var subdivisions = options.subdivisions || 1 | 0;
  55201. var minHeight = options.minHeight || 0.0;
  55202. var maxHeight = options.maxHeight || 1.0;
  55203. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55204. var updatable = options.updatable;
  55205. var onReady = options.onReady;
  55206. var ground = new BABYLON.GroundMesh(name, scene);
  55207. ground._subdivisionsX = subdivisions;
  55208. ground._subdivisionsY = subdivisions;
  55209. ground._width = width;
  55210. ground._height = height;
  55211. ground._maxX = ground._width / 2.0;
  55212. ground._maxZ = ground._height / 2.0;
  55213. ground._minX = -ground._maxX;
  55214. ground._minZ = -ground._maxZ;
  55215. ground._setReady(false);
  55216. var onload = function (img) {
  55217. // Getting height map data
  55218. var canvas = document.createElement("canvas");
  55219. var context = canvas.getContext("2d");
  55220. if (!context) {
  55221. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55222. }
  55223. if (scene.isDisposed) {
  55224. return;
  55225. }
  55226. var bufferWidth = img.width;
  55227. var bufferHeight = img.height;
  55228. canvas.width = bufferWidth;
  55229. canvas.height = bufferHeight;
  55230. context.drawImage(img, 0, 0);
  55231. // Create VertexData from map data
  55232. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55233. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55234. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55235. width: width, height: height,
  55236. subdivisions: subdivisions,
  55237. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55238. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55239. });
  55240. vertexData.applyToMesh(ground, updatable);
  55241. ground._setReady(true);
  55242. //execute ready callback, if set
  55243. if (onReady) {
  55244. onReady(ground);
  55245. }
  55246. };
  55247. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55248. return ground;
  55249. };
  55250. /**
  55251. * Creates a polygon mesh.
  55252. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55253. * 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.
  55254. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55256. * 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).
  55257. * Remember you can only change the shape positions, not their number when updating a polygon.
  55258. */
  55259. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55260. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55261. var shape = options.shape;
  55262. var holes = options.holes || [];
  55263. var depth = options.depth || 0;
  55264. var contours = [];
  55265. var hole = [];
  55266. for (var i = 0; i < shape.length; i++) {
  55267. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55268. }
  55269. var epsilon = 0.00000001;
  55270. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55271. contours.pop();
  55272. }
  55273. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55274. for (var hNb = 0; hNb < holes.length; hNb++) {
  55275. hole = [];
  55276. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55277. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55278. }
  55279. polygonTriangulation.addHole(hole);
  55280. }
  55281. var polygon = polygonTriangulation.build(options.updatable, depth);
  55282. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55283. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55284. vertexData.applyToMesh(polygon, options.updatable);
  55285. return polygon;
  55286. };
  55287. ;
  55288. /**
  55289. * Creates an extruded polygon mesh, with depth in the Y direction.
  55290. * 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).
  55291. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55292. */
  55293. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55294. return MeshBuilder.CreatePolygon(name, options, scene);
  55295. };
  55296. ;
  55297. /**
  55298. * Creates a tube mesh.
  55299. * 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.
  55300. *
  55301. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55302. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55303. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55304. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55305. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55306. * 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.
  55307. * It must return a radius value (positive float) :
  55308. * ```javascript
  55309. * var radiusFunction = function(i, distance) {
  55310. * // do things
  55311. * return radius; }
  55312. * ```
  55313. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55314. * 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
  55315. * 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
  55316. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55317. * 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).
  55318. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55319. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55321. */
  55322. MeshBuilder.CreateTube = function (name, options, scene) {
  55323. var path = options.path;
  55324. var instance = options.instance;
  55325. var radius = 1.0;
  55326. if (instance) {
  55327. radius = instance.radius;
  55328. }
  55329. if (options.radius !== undefined) {
  55330. radius = options.radius;
  55331. }
  55332. ;
  55333. var tessellation = options.tessellation || 64 | 0;
  55334. var radiusFunction = options.radiusFunction || null;
  55335. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55336. var invertUV = options.invertUV || false;
  55337. var updatable = options.updatable;
  55338. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55339. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55340. // tube geometry
  55341. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55342. var tangents = path3D.getTangents();
  55343. var normals = path3D.getNormals();
  55344. var distances = path3D.getDistances();
  55345. var pi2 = Math.PI * 2;
  55346. var step = pi2 / tessellation * arc;
  55347. var returnRadius = function () { return radius; };
  55348. var radiusFunctionFinal = radiusFunction || returnRadius;
  55349. var circlePath;
  55350. var rad;
  55351. var normal;
  55352. var rotated;
  55353. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55354. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55355. for (var i = 0; i < path.length; i++) {
  55356. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55357. circlePath = Array(); // current circle array
  55358. normal = normals[i]; // current normal
  55359. for (var t = 0; t < tessellation; t++) {
  55360. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55361. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55362. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55363. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55364. circlePath[t] = rotated;
  55365. }
  55366. circlePaths[index] = circlePath;
  55367. index++;
  55368. }
  55369. // cap
  55370. var capPath = function (nbPoints, pathIndex) {
  55371. var pointCap = Array();
  55372. for (var i = 0; i < nbPoints; i++) {
  55373. pointCap.push(path[pathIndex]);
  55374. }
  55375. return pointCap;
  55376. };
  55377. switch (cap) {
  55378. case BABYLON.Mesh.NO_CAP:
  55379. break;
  55380. case BABYLON.Mesh.CAP_START:
  55381. circlePaths[0] = capPath(tessellation, 0);
  55382. circlePaths[1] = circlePaths[2].slice(0);
  55383. break;
  55384. case BABYLON.Mesh.CAP_END:
  55385. circlePaths[index] = circlePaths[index - 1].slice(0);
  55386. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55387. break;
  55388. case BABYLON.Mesh.CAP_ALL:
  55389. circlePaths[0] = capPath(tessellation, 0);
  55390. circlePaths[1] = circlePaths[2].slice(0);
  55391. circlePaths[index] = circlePaths[index - 1].slice(0);
  55392. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55393. break;
  55394. default:
  55395. break;
  55396. }
  55397. return circlePaths;
  55398. };
  55399. var path3D;
  55400. var pathArray;
  55401. if (instance) {
  55402. var arc = options.arc || instance.arc;
  55403. path3D = (instance.path3D).update(path);
  55404. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55405. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55406. instance.path3D = path3D;
  55407. instance.pathArray = pathArray;
  55408. instance.arc = arc;
  55409. instance.radius = radius;
  55410. return instance;
  55411. }
  55412. // tube creation
  55413. path3D = new BABYLON.Path3D(path);
  55414. var newPathArray = new Array();
  55415. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55416. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55417. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55418. tube.pathArray = pathArray;
  55419. tube.path3D = path3D;
  55420. tube.tessellation = tessellation;
  55421. tube.cap = cap;
  55422. tube.arc = options.arc;
  55423. tube.radius = radius;
  55424. return tube;
  55425. };
  55426. /**
  55427. * Creates a polyhedron mesh.
  55428. *
  55429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55430. * 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
  55431. * to choose the wanted type.
  55432. * The parameter `size` (positive float, default 1) sets the polygon size.
  55433. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55434. * 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`.
  55435. * 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
  55436. * 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)`).
  55437. * 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
  55438. * 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.
  55439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55440. * 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).
  55441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55443. */
  55444. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55445. var polyhedron = new BABYLON.Mesh(name, scene);
  55446. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55447. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55448. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55449. vertexData.applyToMesh(polyhedron, options.updatable);
  55450. return polyhedron;
  55451. };
  55452. /**
  55453. * Creates a decal mesh.
  55454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55455. * 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.
  55456. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55457. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55458. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55459. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55460. */
  55461. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55462. var indices = sourceMesh.getIndices();
  55463. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55464. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55465. var position = options.position || BABYLON.Vector3.Zero();
  55466. var normal = options.normal || BABYLON.Vector3.Up();
  55467. var size = options.size || BABYLON.Vector3.One();
  55468. var angle = options.angle || 0;
  55469. // Getting correct rotation
  55470. if (!normal) {
  55471. var target = new BABYLON.Vector3(0, 0, 1);
  55472. var camera = sourceMesh.getScene().activeCamera;
  55473. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55474. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55475. }
  55476. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55477. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55478. var pitch = Math.atan2(normal.y, len);
  55479. // Matrix
  55480. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55481. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55482. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55483. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55484. var vertexData = new BABYLON.VertexData();
  55485. vertexData.indices = [];
  55486. vertexData.positions = [];
  55487. vertexData.normals = [];
  55488. vertexData.uvs = [];
  55489. var currentVertexDataIndex = 0;
  55490. var extractDecalVector3 = function (indexId) {
  55491. var result = new BABYLON.PositionNormalVertex();
  55492. if (!indices || !positions || !normals) {
  55493. return result;
  55494. }
  55495. var vertexId = indices[indexId];
  55496. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55497. // Send vector to decal local world
  55498. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55499. // Get normal
  55500. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55501. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55502. return result;
  55503. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55504. var clip = function (vertices, axis) {
  55505. if (vertices.length === 0) {
  55506. return vertices;
  55507. }
  55508. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55509. var clipVertices = function (v0, v1) {
  55510. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55511. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55512. };
  55513. var result = new Array();
  55514. for (var index = 0; index < vertices.length; index += 3) {
  55515. var v1Out;
  55516. var v2Out;
  55517. var v3Out;
  55518. var total = 0;
  55519. var nV1 = null;
  55520. var nV2 = null;
  55521. var nV3 = null;
  55522. var nV4 = null;
  55523. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55524. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55525. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55526. v1Out = d1 > 0;
  55527. v2Out = d2 > 0;
  55528. v3Out = d3 > 0;
  55529. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55530. switch (total) {
  55531. case 0:
  55532. result.push(vertices[index]);
  55533. result.push(vertices[index + 1]);
  55534. result.push(vertices[index + 2]);
  55535. break;
  55536. case 1:
  55537. if (v1Out) {
  55538. nV1 = vertices[index + 1];
  55539. nV2 = vertices[index + 2];
  55540. nV3 = clipVertices(vertices[index], nV1);
  55541. nV4 = clipVertices(vertices[index], nV2);
  55542. }
  55543. if (v2Out) {
  55544. nV1 = vertices[index];
  55545. nV2 = vertices[index + 2];
  55546. nV3 = clipVertices(vertices[index + 1], nV1);
  55547. nV4 = clipVertices(vertices[index + 1], nV2);
  55548. result.push(nV3);
  55549. result.push(nV2.clone());
  55550. result.push(nV1.clone());
  55551. result.push(nV2.clone());
  55552. result.push(nV3.clone());
  55553. result.push(nV4);
  55554. break;
  55555. }
  55556. if (v3Out) {
  55557. nV1 = vertices[index];
  55558. nV2 = vertices[index + 1];
  55559. nV3 = clipVertices(vertices[index + 2], nV1);
  55560. nV4 = clipVertices(vertices[index + 2], nV2);
  55561. }
  55562. if (nV1 && nV2 && nV3 && nV4) {
  55563. result.push(nV1.clone());
  55564. result.push(nV2.clone());
  55565. result.push(nV3);
  55566. result.push(nV4);
  55567. result.push(nV3.clone());
  55568. result.push(nV2.clone());
  55569. }
  55570. break;
  55571. case 2:
  55572. if (!v1Out) {
  55573. nV1 = vertices[index].clone();
  55574. nV2 = clipVertices(nV1, vertices[index + 1]);
  55575. nV3 = clipVertices(nV1, vertices[index + 2]);
  55576. result.push(nV1);
  55577. result.push(nV2);
  55578. result.push(nV3);
  55579. }
  55580. if (!v2Out) {
  55581. nV1 = vertices[index + 1].clone();
  55582. nV2 = clipVertices(nV1, vertices[index + 2]);
  55583. nV3 = clipVertices(nV1, vertices[index]);
  55584. result.push(nV1);
  55585. result.push(nV2);
  55586. result.push(nV3);
  55587. }
  55588. if (!v3Out) {
  55589. nV1 = vertices[index + 2].clone();
  55590. nV2 = clipVertices(nV1, vertices[index]);
  55591. nV3 = clipVertices(nV1, vertices[index + 1]);
  55592. result.push(nV1);
  55593. result.push(nV2);
  55594. result.push(nV3);
  55595. }
  55596. break;
  55597. case 3:
  55598. break;
  55599. }
  55600. }
  55601. return result;
  55602. };
  55603. for (var index = 0; index < indices.length; index += 3) {
  55604. var faceVertices = new Array();
  55605. faceVertices.push(extractDecalVector3(index));
  55606. faceVertices.push(extractDecalVector3(index + 1));
  55607. faceVertices.push(extractDecalVector3(index + 2));
  55608. // Clip
  55609. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55610. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55611. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55612. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55613. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55614. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55615. if (faceVertices.length === 0) {
  55616. continue;
  55617. }
  55618. // Add UVs and get back to world
  55619. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55620. var vertex = faceVertices[vIndex];
  55621. //TODO check for Int32Array | Uint32Array | Uint16Array
  55622. vertexData.indices.push(currentVertexDataIndex);
  55623. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55624. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55625. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55626. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55627. currentVertexDataIndex++;
  55628. }
  55629. }
  55630. // Return mesh
  55631. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55632. vertexData.applyToMesh(decal);
  55633. decal.position = position.clone();
  55634. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55635. return decal;
  55636. };
  55637. // Privates
  55638. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55639. // extrusion geometry
  55640. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55641. var tangents = path3D.getTangents();
  55642. var normals = path3D.getNormals();
  55643. var binormals = path3D.getBinormals();
  55644. var distances = path3D.getDistances();
  55645. var angle = 0;
  55646. var returnScale = function () { return scale !== null ? scale : 1; };
  55647. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55648. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55649. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55650. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55651. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55652. for (var i = 0; i < curve.length; i++) {
  55653. var shapePath = new Array();
  55654. var angleStep = rotate(i, distances[i]);
  55655. var scaleRatio = scl(i, distances[i]);
  55656. for (var p = 0; p < shape.length; p++) {
  55657. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55658. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55659. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55660. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55661. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55662. shapePath[p] = rotated;
  55663. }
  55664. shapePaths[index] = shapePath;
  55665. angle += angleStep;
  55666. index++;
  55667. }
  55668. // cap
  55669. var capPath = function (shapePath) {
  55670. var pointCap = Array();
  55671. var barycenter = BABYLON.Vector3.Zero();
  55672. var i;
  55673. for (i = 0; i < shapePath.length; i++) {
  55674. barycenter.addInPlace(shapePath[i]);
  55675. }
  55676. barycenter.scaleInPlace(1.0 / shapePath.length);
  55677. for (i = 0; i < shapePath.length; i++) {
  55678. pointCap.push(barycenter);
  55679. }
  55680. return pointCap;
  55681. };
  55682. switch (cap) {
  55683. case BABYLON.Mesh.NO_CAP:
  55684. break;
  55685. case BABYLON.Mesh.CAP_START:
  55686. shapePaths[0] = capPath(shapePaths[2]);
  55687. shapePaths[1] = shapePaths[2];
  55688. break;
  55689. case BABYLON.Mesh.CAP_END:
  55690. shapePaths[index] = shapePaths[index - 1];
  55691. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55692. break;
  55693. case BABYLON.Mesh.CAP_ALL:
  55694. shapePaths[0] = capPath(shapePaths[2]);
  55695. shapePaths[1] = shapePaths[2];
  55696. shapePaths[index] = shapePaths[index - 1];
  55697. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55698. break;
  55699. default:
  55700. break;
  55701. }
  55702. return shapePaths;
  55703. };
  55704. var path3D;
  55705. var pathArray;
  55706. if (instance) {
  55707. path3D = (instance.path3D).update(curve);
  55708. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55709. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55710. return instance;
  55711. }
  55712. // extruded shape creation
  55713. path3D = new BABYLON.Path3D(curve);
  55714. var newShapePaths = new Array();
  55715. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55716. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55717. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55718. extrudedGeneric.pathArray = pathArray;
  55719. extrudedGeneric.path3D = path3D;
  55720. extrudedGeneric.cap = cap;
  55721. return extrudedGeneric;
  55722. };
  55723. return MeshBuilder;
  55724. }());
  55725. BABYLON.MeshBuilder = MeshBuilder;
  55726. })(BABYLON || (BABYLON = {}));
  55727. //# sourceMappingURL=babylon.meshBuilder.js.map
  55728. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  55729. var BABYLON;
  55730. (function (BABYLON) {
  55731. /**
  55732. * Draco compression (https://google.github.io/draco/)
  55733. */
  55734. var DracoCompression = /** @class */ (function () {
  55735. /**
  55736. * Constructor
  55737. * @param numWorkers The number of workers for async operations
  55738. */
  55739. function DracoCompression(numWorkers) {
  55740. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  55741. var workers = new Array(numWorkers);
  55742. for (var i = 0; i < workers.length; i++) {
  55743. var worker = new Worker(DracoCompression._WorkerBlobUrl);
  55744. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  55745. workers[i] = worker;
  55746. }
  55747. this._workerPool = new BABYLON.WorkerPool(workers);
  55748. }
  55749. /**
  55750. * Stop all async operations and release resources.
  55751. */
  55752. DracoCompression.prototype.dispose = function () {
  55753. this._workerPool.dispose();
  55754. delete this._workerPool;
  55755. };
  55756. /**
  55757. * Decode Draco compressed mesh data to vertex data.
  55758. * @param data The array buffer view for the Draco compression data
  55759. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  55760. * @returns A promise that resolves with the decoded vertex data
  55761. */
  55762. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  55763. var _this = this;
  55764. return new Promise(function (resolve, reject) {
  55765. _this._workerPool.push(function (worker, onComplete) {
  55766. var vertexData = new BABYLON.VertexData();
  55767. var onError = function (error) {
  55768. worker.removeEventListener("error", onError);
  55769. worker.removeEventListener("message", onMessage);
  55770. reject(error);
  55771. onComplete();
  55772. };
  55773. var onMessage = function (message) {
  55774. if (message.data === "done") {
  55775. worker.removeEventListener("error", onError);
  55776. worker.removeEventListener("message", onMessage);
  55777. resolve(vertexData);
  55778. onComplete();
  55779. }
  55780. else if (message.data.id === "indices") {
  55781. vertexData.indices = message.data.value;
  55782. }
  55783. else {
  55784. vertexData.set(message.data.value, message.data.id);
  55785. }
  55786. };
  55787. worker.addEventListener("error", onError);
  55788. worker.addEventListener("message", onMessage);
  55789. var dataCopy = new Uint8Array(data.byteLength);
  55790. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  55791. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  55792. });
  55793. });
  55794. };
  55795. /**
  55796. * The worker function that gets converted to a blob url to pass into a worker.
  55797. */
  55798. DracoCompression._Worker = function () {
  55799. // self is actually a DedicatedWorkerGlobalScope
  55800. var _self = self;
  55801. var decodeMesh = function (data, attributes) {
  55802. var dracoModule = new DracoDecoderModule();
  55803. var buffer = new dracoModule.DecoderBuffer();
  55804. buffer.Init(data, data.byteLength);
  55805. var decoder = new dracoModule.Decoder();
  55806. var geometry;
  55807. var status;
  55808. try {
  55809. var type = decoder.GetEncodedGeometryType(buffer);
  55810. switch (type) {
  55811. case dracoModule.TRIANGULAR_MESH:
  55812. geometry = new dracoModule.Mesh();
  55813. status = decoder.DecodeBufferToMesh(buffer, geometry);
  55814. break;
  55815. case dracoModule.POINT_CLOUD:
  55816. geometry = new dracoModule.PointCloud();
  55817. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  55818. break;
  55819. default:
  55820. throw new Error("Invalid geometry type " + type);
  55821. }
  55822. if (!status.ok() || !geometry.ptr) {
  55823. throw new Error(status.error_msg());
  55824. }
  55825. var numPoints = geometry.num_points();
  55826. if (type === dracoModule.TRIANGULAR_MESH) {
  55827. var numFaces = geometry.num_faces();
  55828. var faceIndices = new dracoModule.DracoInt32Array();
  55829. try {
  55830. var indices = new Uint32Array(numFaces * 3);
  55831. for (var i = 0; i < numFaces; i++) {
  55832. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  55833. var offset = i * 3;
  55834. indices[offset + 0] = faceIndices.GetValue(0);
  55835. indices[offset + 1] = faceIndices.GetValue(1);
  55836. indices[offset + 2] = faceIndices.GetValue(2);
  55837. }
  55838. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  55839. }
  55840. finally {
  55841. dracoModule.destroy(faceIndices);
  55842. }
  55843. }
  55844. for (var kind in attributes) {
  55845. var uniqueId = attributes[kind];
  55846. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  55847. var dracoData = new dracoModule.DracoFloat32Array();
  55848. try {
  55849. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  55850. var babylonData = new Float32Array(numPoints * attribute.num_components());
  55851. for (var i = 0; i < babylonData.length; i++) {
  55852. babylonData[i] = dracoData.GetValue(i);
  55853. }
  55854. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  55855. }
  55856. finally {
  55857. dracoModule.destroy(dracoData);
  55858. }
  55859. }
  55860. }
  55861. finally {
  55862. if (geometry) {
  55863. dracoModule.destroy(geometry);
  55864. }
  55865. dracoModule.destroy(decoder);
  55866. dracoModule.destroy(buffer);
  55867. }
  55868. _self.postMessage("done");
  55869. };
  55870. _self.onmessage = function (event) {
  55871. switch (event.data.id) {
  55872. case "initDecoder": {
  55873. importScripts(event.data.url);
  55874. break;
  55875. }
  55876. case "decodeMesh": {
  55877. decodeMesh(event.data.data, event.data.attributes);
  55878. break;
  55879. }
  55880. }
  55881. };
  55882. };
  55883. DracoCompression._GetDefaultDecoderUrl = function () {
  55884. for (var i = 0; i < document.scripts.length; i++) {
  55885. if (document.scripts[i].type === "text/x-draco-decoder") {
  55886. return document.scripts[i].src;
  55887. }
  55888. }
  55889. return null;
  55890. };
  55891. /**
  55892. * Gets the url to the draco decoder if available.
  55893. */
  55894. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  55895. DracoCompression._WorkerBlobUrl = URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  55896. return DracoCompression;
  55897. }());
  55898. BABYLON.DracoCompression = DracoCompression;
  55899. })(BABYLON || (BABYLON = {}));
  55900. //# sourceMappingURL=babylon.dracoCompression.js.map
  55901. var BABYLON;
  55902. (function (BABYLON) {
  55903. var AudioEngine = /** @class */ (function () {
  55904. function AudioEngine() {
  55905. this._audioContext = null;
  55906. this._audioContextInitialized = false;
  55907. this.canUseWebAudio = false;
  55908. this.WarnedWebAudioUnsupported = false;
  55909. this.unlocked = false;
  55910. this.isMP3supported = false;
  55911. this.isOGGsupported = false;
  55912. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55913. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55914. this.canUseWebAudio = true;
  55915. }
  55916. var audioElem = document.createElement('audio');
  55917. try {
  55918. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55919. this.isMP3supported = true;
  55920. }
  55921. }
  55922. catch (e) {
  55923. // protect error during capability check.
  55924. }
  55925. try {
  55926. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55927. this.isOGGsupported = true;
  55928. }
  55929. }
  55930. catch (e) {
  55931. // protect error during capability check.
  55932. }
  55933. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55934. this._unlockiOSaudio();
  55935. }
  55936. else {
  55937. this.unlocked = true;
  55938. }
  55939. }
  55940. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55941. get: function () {
  55942. if (!this._audioContextInitialized) {
  55943. this._initializeAudioContext();
  55944. }
  55945. return this._audioContext;
  55946. },
  55947. enumerable: true,
  55948. configurable: true
  55949. });
  55950. AudioEngine.prototype._unlockiOSaudio = function () {
  55951. var _this = this;
  55952. var unlockaudio = function () {
  55953. if (!_this.audioContext) {
  55954. return;
  55955. }
  55956. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55957. var source = _this.audioContext.createBufferSource();
  55958. source.buffer = buffer;
  55959. source.connect(_this.audioContext.destination);
  55960. source.start(0);
  55961. setTimeout(function () {
  55962. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55963. _this.unlocked = true;
  55964. window.removeEventListener('touchend', unlockaudio, false);
  55965. if (_this.onAudioUnlocked) {
  55966. _this.onAudioUnlocked();
  55967. }
  55968. }
  55969. }, 0);
  55970. };
  55971. window.addEventListener('touchend', unlockaudio, false);
  55972. };
  55973. AudioEngine.prototype._initializeAudioContext = function () {
  55974. try {
  55975. if (this.canUseWebAudio) {
  55976. this._audioContext = new AudioContext();
  55977. // create a global volume gain node
  55978. this.masterGain = this._audioContext.createGain();
  55979. this.masterGain.gain.value = 1;
  55980. this.masterGain.connect(this._audioContext.destination);
  55981. this._audioContextInitialized = true;
  55982. }
  55983. }
  55984. catch (e) {
  55985. this.canUseWebAudio = false;
  55986. BABYLON.Tools.Error("Web Audio: " + e.message);
  55987. }
  55988. };
  55989. AudioEngine.prototype.dispose = function () {
  55990. if (this.canUseWebAudio && this._audioContextInitialized) {
  55991. if (this._connectedAnalyser && this._audioContext) {
  55992. this._connectedAnalyser.stopDebugCanvas();
  55993. this._connectedAnalyser.dispose();
  55994. this.masterGain.disconnect();
  55995. this.masterGain.connect(this._audioContext.destination);
  55996. this._connectedAnalyser = null;
  55997. }
  55998. this.masterGain.gain.value = 1;
  55999. }
  56000. this.WarnedWebAudioUnsupported = false;
  56001. };
  56002. AudioEngine.prototype.getGlobalVolume = function () {
  56003. if (this.canUseWebAudio && this._audioContextInitialized) {
  56004. return this.masterGain.gain.value;
  56005. }
  56006. else {
  56007. return -1;
  56008. }
  56009. };
  56010. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56011. if (this.canUseWebAudio && this._audioContextInitialized) {
  56012. this.masterGain.gain.value = newVolume;
  56013. }
  56014. };
  56015. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56016. if (this._connectedAnalyser) {
  56017. this._connectedAnalyser.stopDebugCanvas();
  56018. }
  56019. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56020. this._connectedAnalyser = analyser;
  56021. this.masterGain.disconnect();
  56022. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56023. }
  56024. };
  56025. return AudioEngine;
  56026. }());
  56027. BABYLON.AudioEngine = AudioEngine;
  56028. })(BABYLON || (BABYLON = {}));
  56029. //# sourceMappingURL=babylon.audioEngine.js.map
  56030. var BABYLON;
  56031. (function (BABYLON) {
  56032. var Sound = /** @class */ (function () {
  56033. /**
  56034. * Create a sound and attach it to a scene
  56035. * @param name Name of your sound
  56036. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56037. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56038. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56039. */
  56040. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56041. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56042. var _this = this;
  56043. this.autoplay = false;
  56044. this.loop = false;
  56045. this.useCustomAttenuation = false;
  56046. this.spatialSound = false;
  56047. this.refDistance = 1;
  56048. this.rolloffFactor = 1;
  56049. this.maxDistance = 100;
  56050. this.distanceModel = "linear";
  56051. this._panningModel = "equalpower";
  56052. this._playbackRate = 1;
  56053. this._streaming = false;
  56054. this._startTime = 0;
  56055. this._startOffset = 0;
  56056. this._position = BABYLON.Vector3.Zero();
  56057. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56058. this._volume = 1;
  56059. this._isReadyToPlay = false;
  56060. this.isPlaying = false;
  56061. this.isPaused = false;
  56062. this._isDirectional = false;
  56063. // Used if you'd like to create a directional sound.
  56064. // If not set, the sound will be omnidirectional
  56065. this._coneInnerAngle = 360;
  56066. this._coneOuterAngle = 360;
  56067. this._coneOuterGain = 0;
  56068. this._isOutputConnected = false;
  56069. this._urlType = "Unknown";
  56070. this.name = name;
  56071. this._scene = scene;
  56072. this._readyToPlayCallback = readyToPlayCallback;
  56073. // Default custom attenuation function is a linear attenuation
  56074. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56075. if (currentDistance < maxDistance) {
  56076. return currentVolume * (1 - currentDistance / maxDistance);
  56077. }
  56078. else {
  56079. return 0;
  56080. }
  56081. };
  56082. if (options) {
  56083. this.autoplay = options.autoplay || false;
  56084. this.loop = options.loop || false;
  56085. // if volume === 0, we need another way to check this option
  56086. if (options.volume !== undefined) {
  56087. this._volume = options.volume;
  56088. }
  56089. this.spatialSound = options.spatialSound || false;
  56090. this.maxDistance = options.maxDistance || 100;
  56091. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56092. this.rolloffFactor = options.rolloffFactor || 1;
  56093. this.refDistance = options.refDistance || 1;
  56094. this.distanceModel = options.distanceModel || "linear";
  56095. this._playbackRate = options.playbackRate || 1;
  56096. this._streaming = options.streaming || false;
  56097. }
  56098. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56099. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56100. this._soundGain.gain.value = this._volume;
  56101. this._inputAudioNode = this._soundGain;
  56102. this._ouputAudioNode = this._soundGain;
  56103. if (this.spatialSound) {
  56104. this._createSpatialParameters();
  56105. }
  56106. this._scene.mainSoundTrack.AddSound(this);
  56107. var validParameter = true;
  56108. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56109. if (urlOrArrayBuffer) {
  56110. if (typeof (urlOrArrayBuffer) === "string")
  56111. this._urlType = "String";
  56112. if (Array.isArray(urlOrArrayBuffer))
  56113. this._urlType = "Array";
  56114. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56115. this._urlType = "ArrayBuffer";
  56116. var urls = [];
  56117. var codecSupportedFound = false;
  56118. switch (this._urlType) {
  56119. case "ArrayBuffer":
  56120. if (urlOrArrayBuffer.byteLength > 0) {
  56121. codecSupportedFound = true;
  56122. this._soundLoaded(urlOrArrayBuffer);
  56123. }
  56124. break;
  56125. case "String":
  56126. urls.push(urlOrArrayBuffer);
  56127. case "Array":
  56128. if (urls.length === 0)
  56129. urls = urlOrArrayBuffer;
  56130. // If we found a supported format, we load it immediately and stop the loop
  56131. for (var i = 0; i < urls.length; i++) {
  56132. var url = urls[i];
  56133. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56134. codecSupportedFound = true;
  56135. }
  56136. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56137. codecSupportedFound = true;
  56138. }
  56139. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56140. codecSupportedFound = true;
  56141. }
  56142. if (url.indexOf("blob:") !== -1) {
  56143. codecSupportedFound = true;
  56144. }
  56145. if (codecSupportedFound) {
  56146. // Loading sound using XHR2
  56147. if (!this._streaming) {
  56148. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56149. }
  56150. else {
  56151. this._htmlAudioElement = new Audio(url);
  56152. this._htmlAudioElement.controls = false;
  56153. this._htmlAudioElement.loop = this.loop;
  56154. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56155. this._htmlAudioElement.preload = "auto";
  56156. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56157. _this._isReadyToPlay = true;
  56158. if (_this.autoplay) {
  56159. _this.play();
  56160. }
  56161. if (_this._readyToPlayCallback) {
  56162. _this._readyToPlayCallback();
  56163. }
  56164. });
  56165. document.body.appendChild(this._htmlAudioElement);
  56166. }
  56167. break;
  56168. }
  56169. }
  56170. break;
  56171. default:
  56172. validParameter = false;
  56173. break;
  56174. }
  56175. if (!validParameter) {
  56176. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56177. }
  56178. else {
  56179. if (!codecSupportedFound) {
  56180. this._isReadyToPlay = true;
  56181. // Simulating a ready to play event to avoid breaking code path
  56182. if (this._readyToPlayCallback) {
  56183. window.setTimeout(function () {
  56184. if (_this._readyToPlayCallback) {
  56185. _this._readyToPlayCallback();
  56186. }
  56187. }, 1000);
  56188. }
  56189. }
  56190. }
  56191. }
  56192. }
  56193. else {
  56194. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56195. this._scene.mainSoundTrack.AddSound(this);
  56196. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56197. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56198. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56199. }
  56200. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56201. if (this._readyToPlayCallback) {
  56202. window.setTimeout(function () {
  56203. if (_this._readyToPlayCallback) {
  56204. _this._readyToPlayCallback();
  56205. }
  56206. }, 1000);
  56207. }
  56208. }
  56209. }
  56210. Sound.prototype.dispose = function () {
  56211. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56212. if (this.isPlaying) {
  56213. this.stop();
  56214. }
  56215. this._isReadyToPlay = false;
  56216. if (this.soundTrackId === -1) {
  56217. this._scene.mainSoundTrack.RemoveSound(this);
  56218. }
  56219. else {
  56220. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56221. }
  56222. if (this._soundGain) {
  56223. this._soundGain.disconnect();
  56224. this._soundGain = null;
  56225. }
  56226. if (this._soundPanner) {
  56227. this._soundPanner.disconnect();
  56228. this._soundPanner = null;
  56229. }
  56230. if (this._soundSource) {
  56231. this._soundSource.disconnect();
  56232. this._soundSource = null;
  56233. }
  56234. this._audioBuffer = null;
  56235. if (this._htmlAudioElement) {
  56236. this._htmlAudioElement.pause();
  56237. this._htmlAudioElement.src = "";
  56238. document.body.removeChild(this._htmlAudioElement);
  56239. }
  56240. if (this._connectedMesh && this._registerFunc) {
  56241. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56242. this._connectedMesh = null;
  56243. }
  56244. }
  56245. };
  56246. Sound.prototype.isReady = function () {
  56247. return this._isReadyToPlay;
  56248. };
  56249. Sound.prototype._soundLoaded = function (audioData) {
  56250. var _this = this;
  56251. if (!BABYLON.Engine.audioEngine.audioContext) {
  56252. return;
  56253. }
  56254. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56255. _this._audioBuffer = buffer;
  56256. _this._isReadyToPlay = true;
  56257. if (_this.autoplay) {
  56258. _this.play();
  56259. }
  56260. if (_this._readyToPlayCallback) {
  56261. _this._readyToPlayCallback();
  56262. }
  56263. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56264. };
  56265. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56266. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56267. this._audioBuffer = audioBuffer;
  56268. this._isReadyToPlay = true;
  56269. }
  56270. };
  56271. Sound.prototype.updateOptions = function (options) {
  56272. if (options) {
  56273. this.loop = options.loop || this.loop;
  56274. this.maxDistance = options.maxDistance || this.maxDistance;
  56275. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56276. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56277. this.refDistance = options.refDistance || this.refDistance;
  56278. this.distanceModel = options.distanceModel || this.distanceModel;
  56279. this._playbackRate = options.playbackRate || this._playbackRate;
  56280. this._updateSpatialParameters();
  56281. if (this.isPlaying) {
  56282. if (this._streaming) {
  56283. this._htmlAudioElement.playbackRate = this._playbackRate;
  56284. }
  56285. else {
  56286. if (this._soundSource) {
  56287. this._soundSource.playbackRate.value = this._playbackRate;
  56288. }
  56289. }
  56290. }
  56291. }
  56292. };
  56293. Sound.prototype._createSpatialParameters = function () {
  56294. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56295. if (this._scene.headphone) {
  56296. this._panningModel = "HRTF";
  56297. }
  56298. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56299. this._updateSpatialParameters();
  56300. this._soundPanner.connect(this._ouputAudioNode);
  56301. this._inputAudioNode = this._soundPanner;
  56302. }
  56303. };
  56304. Sound.prototype._updateSpatialParameters = function () {
  56305. if (this.spatialSound && this._soundPanner) {
  56306. if (this.useCustomAttenuation) {
  56307. // Tricks to disable in a way embedded Web Audio attenuation
  56308. this._soundPanner.distanceModel = "linear";
  56309. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56310. this._soundPanner.refDistance = 1;
  56311. this._soundPanner.rolloffFactor = 1;
  56312. this._soundPanner.panningModel = this._panningModel;
  56313. }
  56314. else {
  56315. this._soundPanner.distanceModel = this.distanceModel;
  56316. this._soundPanner.maxDistance = this.maxDistance;
  56317. this._soundPanner.refDistance = this.refDistance;
  56318. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56319. this._soundPanner.panningModel = this._panningModel;
  56320. }
  56321. }
  56322. };
  56323. Sound.prototype.switchPanningModelToHRTF = function () {
  56324. this._panningModel = "HRTF";
  56325. this._switchPanningModel();
  56326. };
  56327. Sound.prototype.switchPanningModelToEqualPower = function () {
  56328. this._panningModel = "equalpower";
  56329. this._switchPanningModel();
  56330. };
  56331. Sound.prototype._switchPanningModel = function () {
  56332. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56333. this._soundPanner.panningModel = this._panningModel;
  56334. }
  56335. };
  56336. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56337. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56338. if (this._isOutputConnected) {
  56339. this._ouputAudioNode.disconnect();
  56340. }
  56341. this._ouputAudioNode.connect(soundTrackAudioNode);
  56342. this._isOutputConnected = true;
  56343. }
  56344. };
  56345. /**
  56346. * Transform this sound into a directional source
  56347. * @param coneInnerAngle Size of the inner cone in degree
  56348. * @param coneOuterAngle Size of the outer cone in degree
  56349. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56350. */
  56351. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56352. if (coneOuterAngle < coneInnerAngle) {
  56353. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56354. return;
  56355. }
  56356. this._coneInnerAngle = coneInnerAngle;
  56357. this._coneOuterAngle = coneOuterAngle;
  56358. this._coneOuterGain = coneOuterGain;
  56359. this._isDirectional = true;
  56360. if (this.isPlaying && this.loop) {
  56361. this.stop();
  56362. this.play();
  56363. }
  56364. };
  56365. Sound.prototype.setPosition = function (newPosition) {
  56366. this._position = newPosition;
  56367. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56368. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56369. }
  56370. };
  56371. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56372. this._localDirection = newLocalDirection;
  56373. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56374. this._updateDirection();
  56375. }
  56376. };
  56377. Sound.prototype._updateDirection = function () {
  56378. if (!this._connectedMesh || !this._soundPanner) {
  56379. return;
  56380. }
  56381. var mat = this._connectedMesh.getWorldMatrix();
  56382. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56383. direction.normalize();
  56384. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56385. };
  56386. Sound.prototype.updateDistanceFromListener = function () {
  56387. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56388. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56389. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56390. }
  56391. };
  56392. Sound.prototype.setAttenuationFunction = function (callback) {
  56393. this._customAttenuationFunction = callback;
  56394. };
  56395. /**
  56396. * Play the sound
  56397. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56398. * @param offset (optional) Start the sound setting it at a specific time
  56399. */
  56400. Sound.prototype.play = function (time, offset) {
  56401. var _this = this;
  56402. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56403. try {
  56404. if (this._startOffset < 0) {
  56405. time = -this._startOffset;
  56406. this._startOffset = 0;
  56407. }
  56408. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56409. if (!this._soundSource || !this._streamingSource) {
  56410. if (this.spatialSound && this._soundPanner) {
  56411. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56412. if (this._isDirectional) {
  56413. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56414. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56415. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56416. if (this._connectedMesh) {
  56417. this._updateDirection();
  56418. }
  56419. else {
  56420. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56421. }
  56422. }
  56423. }
  56424. }
  56425. if (this._streaming) {
  56426. if (!this._streamingSource) {
  56427. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56428. this._htmlAudioElement.onended = function () { _this._onended(); };
  56429. this._htmlAudioElement.playbackRate = this._playbackRate;
  56430. }
  56431. this._streamingSource.disconnect();
  56432. this._streamingSource.connect(this._inputAudioNode);
  56433. this._htmlAudioElement.play();
  56434. }
  56435. else {
  56436. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56437. this._soundSource.buffer = this._audioBuffer;
  56438. this._soundSource.connect(this._inputAudioNode);
  56439. this._soundSource.loop = this.loop;
  56440. this._soundSource.playbackRate.value = this._playbackRate;
  56441. this._soundSource.onended = function () { _this._onended(); };
  56442. if (this._soundSource.buffer) {
  56443. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56444. }
  56445. }
  56446. this._startTime = startTime;
  56447. this.isPlaying = true;
  56448. this.isPaused = false;
  56449. }
  56450. catch (ex) {
  56451. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56452. }
  56453. }
  56454. };
  56455. Sound.prototype._onended = function () {
  56456. this.isPlaying = false;
  56457. if (this.onended) {
  56458. this.onended();
  56459. }
  56460. };
  56461. /**
  56462. * Stop the sound
  56463. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56464. */
  56465. Sound.prototype.stop = function (time) {
  56466. if (this.isPlaying) {
  56467. if (this._streaming) {
  56468. this._htmlAudioElement.pause();
  56469. // Test needed for Firefox or it will generate an Invalid State Error
  56470. if (this._htmlAudioElement.currentTime > 0) {
  56471. this._htmlAudioElement.currentTime = 0;
  56472. }
  56473. }
  56474. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56475. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56476. this._soundSource.stop(stopTime);
  56477. this._soundSource.onended = function () { };
  56478. if (!this.isPaused) {
  56479. this._startOffset = 0;
  56480. }
  56481. }
  56482. this.isPlaying = false;
  56483. }
  56484. };
  56485. Sound.prototype.pause = function () {
  56486. if (this.isPlaying) {
  56487. this.isPaused = true;
  56488. if (this._streaming) {
  56489. this._htmlAudioElement.pause();
  56490. }
  56491. else if (BABYLON.Engine.audioEngine.audioContext) {
  56492. this.stop(0);
  56493. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56494. }
  56495. }
  56496. };
  56497. Sound.prototype.setVolume = function (newVolume, time) {
  56498. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56499. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56500. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56501. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56502. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56503. }
  56504. else {
  56505. this._soundGain.gain.value = newVolume;
  56506. }
  56507. }
  56508. this._volume = newVolume;
  56509. };
  56510. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56511. this._playbackRate = newPlaybackRate;
  56512. if (this.isPlaying) {
  56513. if (this._streaming) {
  56514. this._htmlAudioElement.playbackRate = this._playbackRate;
  56515. }
  56516. else if (this._soundSource) {
  56517. this._soundSource.playbackRate.value = this._playbackRate;
  56518. }
  56519. }
  56520. };
  56521. Sound.prototype.getVolume = function () {
  56522. return this._volume;
  56523. };
  56524. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56525. var _this = this;
  56526. if (this._connectedMesh && this._registerFunc) {
  56527. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56528. this._registerFunc = null;
  56529. }
  56530. this._connectedMesh = meshToConnectTo;
  56531. if (!this.spatialSound) {
  56532. this.spatialSound = true;
  56533. this._createSpatialParameters();
  56534. if (this.isPlaying && this.loop) {
  56535. this.stop();
  56536. this.play();
  56537. }
  56538. }
  56539. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56540. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56541. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56542. };
  56543. Sound.prototype.detachFromMesh = function () {
  56544. if (this._connectedMesh && this._registerFunc) {
  56545. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56546. this._registerFunc = null;
  56547. this._connectedMesh = null;
  56548. }
  56549. };
  56550. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56551. if (!node.getBoundingInfo) {
  56552. return;
  56553. }
  56554. var mesh = node;
  56555. var boundingInfo = mesh.getBoundingInfo();
  56556. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56557. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56558. this._updateDirection();
  56559. }
  56560. };
  56561. Sound.prototype.clone = function () {
  56562. var _this = this;
  56563. if (!this._streaming) {
  56564. var setBufferAndRun = function () {
  56565. if (_this._isReadyToPlay) {
  56566. clonedSound._audioBuffer = _this.getAudioBuffer();
  56567. clonedSound._isReadyToPlay = true;
  56568. if (clonedSound.autoplay) {
  56569. clonedSound.play();
  56570. }
  56571. }
  56572. else {
  56573. window.setTimeout(setBufferAndRun, 300);
  56574. }
  56575. };
  56576. var currentOptions = {
  56577. autoplay: this.autoplay, loop: this.loop,
  56578. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56579. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56580. refDistance: this.refDistance, distanceModel: this.distanceModel
  56581. };
  56582. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56583. if (this.useCustomAttenuation) {
  56584. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56585. }
  56586. clonedSound.setPosition(this._position);
  56587. clonedSound.setPlaybackRate(this._playbackRate);
  56588. setBufferAndRun();
  56589. return clonedSound;
  56590. }
  56591. else {
  56592. return null;
  56593. }
  56594. };
  56595. Sound.prototype.getAudioBuffer = function () {
  56596. return this._audioBuffer;
  56597. };
  56598. Sound.prototype.serialize = function () {
  56599. var serializationObject = {
  56600. name: this.name,
  56601. url: this.name,
  56602. autoplay: this.autoplay,
  56603. loop: this.loop,
  56604. volume: this._volume,
  56605. spatialSound: this.spatialSound,
  56606. maxDistance: this.maxDistance,
  56607. rolloffFactor: this.rolloffFactor,
  56608. refDistance: this.refDistance,
  56609. distanceModel: this.distanceModel,
  56610. playbackRate: this._playbackRate,
  56611. panningModel: this._panningModel,
  56612. soundTrackId: this.soundTrackId
  56613. };
  56614. if (this.spatialSound) {
  56615. if (this._connectedMesh)
  56616. serializationObject.connectedMeshId = this._connectedMesh.id;
  56617. serializationObject.position = this._position.asArray();
  56618. serializationObject.refDistance = this.refDistance;
  56619. serializationObject.distanceModel = this.distanceModel;
  56620. serializationObject.isDirectional = this._isDirectional;
  56621. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56622. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56623. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56624. serializationObject.coneOuterGain = this._coneOuterGain;
  56625. }
  56626. return serializationObject;
  56627. };
  56628. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56629. var soundName = parsedSound.name;
  56630. var soundUrl;
  56631. if (parsedSound.url) {
  56632. soundUrl = rootUrl + parsedSound.url;
  56633. }
  56634. else {
  56635. soundUrl = rootUrl + soundName;
  56636. }
  56637. var options = {
  56638. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56639. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56640. rolloffFactor: parsedSound.rolloffFactor,
  56641. refDistance: parsedSound.refDistance,
  56642. distanceModel: parsedSound.distanceModel,
  56643. playbackRate: parsedSound.playbackRate
  56644. };
  56645. var newSound;
  56646. if (!sourceSound) {
  56647. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56648. scene._addPendingData(newSound);
  56649. }
  56650. else {
  56651. var setBufferAndRun = function () {
  56652. if (sourceSound._isReadyToPlay) {
  56653. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56654. newSound._isReadyToPlay = true;
  56655. if (newSound.autoplay) {
  56656. newSound.play();
  56657. }
  56658. }
  56659. else {
  56660. window.setTimeout(setBufferAndRun, 300);
  56661. }
  56662. };
  56663. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56664. setBufferAndRun();
  56665. }
  56666. if (parsedSound.position) {
  56667. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56668. newSound.setPosition(soundPosition);
  56669. }
  56670. if (parsedSound.isDirectional) {
  56671. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56672. if (parsedSound.localDirectionToMesh) {
  56673. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56674. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56675. }
  56676. }
  56677. if (parsedSound.connectedMeshId) {
  56678. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56679. if (connectedMesh) {
  56680. newSound.attachToMesh(connectedMesh);
  56681. }
  56682. }
  56683. return newSound;
  56684. };
  56685. return Sound;
  56686. }());
  56687. BABYLON.Sound = Sound;
  56688. })(BABYLON || (BABYLON = {}));
  56689. //# sourceMappingURL=babylon.sound.js.map
  56690. var BABYLON;
  56691. (function (BABYLON) {
  56692. var SoundTrack = /** @class */ (function () {
  56693. function SoundTrack(scene, options) {
  56694. this.id = -1;
  56695. this._isMainTrack = false;
  56696. this._isInitialized = false;
  56697. this._scene = scene;
  56698. this.soundCollection = new Array();
  56699. this._options = options;
  56700. if (!this._isMainTrack) {
  56701. this._scene.soundTracks.push(this);
  56702. this.id = this._scene.soundTracks.length - 1;
  56703. }
  56704. }
  56705. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56706. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56707. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56708. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56709. if (this._options) {
  56710. if (this._options.volume) {
  56711. this._outputAudioNode.gain.value = this._options.volume;
  56712. }
  56713. if (this._options.mainTrack) {
  56714. this._isMainTrack = this._options.mainTrack;
  56715. }
  56716. }
  56717. this._isInitialized = true;
  56718. }
  56719. };
  56720. SoundTrack.prototype.dispose = function () {
  56721. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56722. if (this._connectedAnalyser) {
  56723. this._connectedAnalyser.stopDebugCanvas();
  56724. }
  56725. while (this.soundCollection.length) {
  56726. this.soundCollection[0].dispose();
  56727. }
  56728. if (this._outputAudioNode) {
  56729. this._outputAudioNode.disconnect();
  56730. }
  56731. this._outputAudioNode = null;
  56732. }
  56733. };
  56734. SoundTrack.prototype.AddSound = function (sound) {
  56735. if (!this._isInitialized) {
  56736. this._initializeSoundTrackAudioGraph();
  56737. }
  56738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56739. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56740. }
  56741. if (sound.soundTrackId) {
  56742. if (sound.soundTrackId === -1) {
  56743. this._scene.mainSoundTrack.RemoveSound(sound);
  56744. }
  56745. else {
  56746. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56747. }
  56748. }
  56749. this.soundCollection.push(sound);
  56750. sound.soundTrackId = this.id;
  56751. };
  56752. SoundTrack.prototype.RemoveSound = function (sound) {
  56753. var index = this.soundCollection.indexOf(sound);
  56754. if (index !== -1) {
  56755. this.soundCollection.splice(index, 1);
  56756. }
  56757. };
  56758. SoundTrack.prototype.setVolume = function (newVolume) {
  56759. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56760. this._outputAudioNode.gain.value = newVolume;
  56761. }
  56762. };
  56763. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56764. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56765. for (var i = 0; i < this.soundCollection.length; i++) {
  56766. this.soundCollection[i].switchPanningModelToHRTF();
  56767. }
  56768. }
  56769. };
  56770. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56771. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56772. for (var i = 0; i < this.soundCollection.length; i++) {
  56773. this.soundCollection[i].switchPanningModelToEqualPower();
  56774. }
  56775. }
  56776. };
  56777. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56778. if (this._connectedAnalyser) {
  56779. this._connectedAnalyser.stopDebugCanvas();
  56780. }
  56781. this._connectedAnalyser = analyser;
  56782. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56783. this._outputAudioNode.disconnect();
  56784. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56785. }
  56786. };
  56787. return SoundTrack;
  56788. }());
  56789. BABYLON.SoundTrack = SoundTrack;
  56790. })(BABYLON || (BABYLON = {}));
  56791. //# sourceMappingURL=babylon.soundtrack.js.map
  56792. var BABYLON;
  56793. (function (BABYLON) {
  56794. var Analyser = /** @class */ (function () {
  56795. function Analyser(scene) {
  56796. this.SMOOTHING = 0.75;
  56797. this.FFT_SIZE = 512;
  56798. this.BARGRAPHAMPLITUDE = 256;
  56799. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56800. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56801. this._scene = scene;
  56802. this._audioEngine = BABYLON.Engine.audioEngine;
  56803. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56804. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56805. this._webAudioAnalyser.minDecibels = -140;
  56806. this._webAudioAnalyser.maxDecibels = 0;
  56807. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56808. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56809. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56810. }
  56811. }
  56812. Analyser.prototype.getFrequencyBinCount = function () {
  56813. if (this._audioEngine.canUseWebAudio) {
  56814. return this._webAudioAnalyser.frequencyBinCount;
  56815. }
  56816. else {
  56817. return 0;
  56818. }
  56819. };
  56820. Analyser.prototype.getByteFrequencyData = function () {
  56821. if (this._audioEngine.canUseWebAudio) {
  56822. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56823. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56824. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56825. }
  56826. return this._byteFreqs;
  56827. };
  56828. Analyser.prototype.getByteTimeDomainData = function () {
  56829. if (this._audioEngine.canUseWebAudio) {
  56830. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56831. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56832. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56833. }
  56834. return this._byteTime;
  56835. };
  56836. Analyser.prototype.getFloatFrequencyData = function () {
  56837. if (this._audioEngine.canUseWebAudio) {
  56838. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56839. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56840. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56841. }
  56842. return this._floatFreqs;
  56843. };
  56844. Analyser.prototype.drawDebugCanvas = function () {
  56845. var _this = this;
  56846. if (this._audioEngine.canUseWebAudio) {
  56847. if (!this._debugCanvas) {
  56848. this._debugCanvas = document.createElement("canvas");
  56849. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56850. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56851. this._debugCanvas.style.position = "absolute";
  56852. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56853. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56854. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56855. document.body.appendChild(this._debugCanvas);
  56856. this._registerFunc = function () {
  56857. _this.drawDebugCanvas();
  56858. };
  56859. this._scene.registerBeforeRender(this._registerFunc);
  56860. }
  56861. if (this._registerFunc && this._debugCanvasContext) {
  56862. var workingArray = this.getByteFrequencyData();
  56863. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56864. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56865. // Draw the frequency domain chart.
  56866. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56867. var value = workingArray[i];
  56868. var percent = value / this.BARGRAPHAMPLITUDE;
  56869. var height = this.DEBUGCANVASSIZE.height * percent;
  56870. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56871. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56872. var hue = i / this.getFrequencyBinCount() * 360;
  56873. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56874. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56875. }
  56876. }
  56877. }
  56878. };
  56879. Analyser.prototype.stopDebugCanvas = function () {
  56880. if (this._debugCanvas) {
  56881. if (this._registerFunc) {
  56882. this._scene.unregisterBeforeRender(this._registerFunc);
  56883. this._registerFunc = null;
  56884. }
  56885. document.body.removeChild(this._debugCanvas);
  56886. this._debugCanvas = null;
  56887. this._debugCanvasContext = null;
  56888. }
  56889. };
  56890. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56891. if (this._audioEngine.canUseWebAudio) {
  56892. inputAudioNode.connect(this._webAudioAnalyser);
  56893. this._webAudioAnalyser.connect(outputAudioNode);
  56894. }
  56895. };
  56896. Analyser.prototype.dispose = function () {
  56897. if (this._audioEngine.canUseWebAudio) {
  56898. this._webAudioAnalyser.disconnect();
  56899. }
  56900. };
  56901. return Analyser;
  56902. }());
  56903. BABYLON.Analyser = Analyser;
  56904. })(BABYLON || (BABYLON = {}));
  56905. //# sourceMappingURL=babylon.analyser.js.map
  56906. var BABYLON;
  56907. (function (BABYLON) {
  56908. var CubeTexture = /** @class */ (function (_super) {
  56909. __extends(CubeTexture, _super);
  56910. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56911. if (extensions === void 0) { extensions = null; }
  56912. if (noMipmap === void 0) { noMipmap = false; }
  56913. if (files === void 0) { files = null; }
  56914. if (onLoad === void 0) { onLoad = null; }
  56915. if (onError === void 0) { onError = null; }
  56916. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56917. if (prefiltered === void 0) { prefiltered = false; }
  56918. if (forcedExtension === void 0) { forcedExtension = null; }
  56919. var _this = _super.call(this, scene) || this;
  56920. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56921. /**
  56922. * Gets or sets the center of the bounding box associated with the cube texture
  56923. * It must define where the camera used to render the texture was set
  56924. */
  56925. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56926. _this.name = rootUrl;
  56927. _this.url = rootUrl;
  56928. _this._noMipmap = noMipmap;
  56929. _this.hasAlpha = false;
  56930. _this._format = format;
  56931. _this._prefiltered = prefiltered;
  56932. _this.isCube = true;
  56933. _this._textureMatrix = BABYLON.Matrix.Identity();
  56934. if (prefiltered) {
  56935. _this.gammaSpace = false;
  56936. }
  56937. if (!rootUrl && !files) {
  56938. return _this;
  56939. }
  56940. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56941. var lastDot = rootUrl.lastIndexOf(".");
  56942. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56943. var isDDS = (extension === ".dds");
  56944. if (!files) {
  56945. if (!isDDS && !extensions) {
  56946. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56947. }
  56948. files = [];
  56949. if (extensions) {
  56950. for (var index = 0; index < extensions.length; index++) {
  56951. files.push(rootUrl + extensions[index]);
  56952. }
  56953. }
  56954. }
  56955. _this._files = files;
  56956. if (!_this._texture) {
  56957. if (!scene.useDelayedTextureLoading) {
  56958. if (prefiltered) {
  56959. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56960. }
  56961. else {
  56962. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56963. }
  56964. }
  56965. else {
  56966. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56967. }
  56968. }
  56969. else if (onLoad) {
  56970. if (_this._texture.isReady) {
  56971. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56972. }
  56973. else {
  56974. _this._texture.onLoadedObservable.add(onLoad);
  56975. }
  56976. }
  56977. return _this;
  56978. }
  56979. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56980. get: function () {
  56981. return this._boundingBoxSize;
  56982. },
  56983. /**
  56984. * Gets or sets the size of the bounding box associated with the cube texture
  56985. * When defined, the cubemap will switch to local mode
  56986. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56987. * @example https://www.babylonjs-playground.com/#RNASML
  56988. */
  56989. set: function (value) {
  56990. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56991. return;
  56992. }
  56993. this._boundingBoxSize = value;
  56994. var scene = this.getScene();
  56995. if (scene) {
  56996. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56997. }
  56998. },
  56999. enumerable: true,
  57000. configurable: true
  57001. });
  57002. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57003. var rootUrlKey = "";
  57004. files.forEach(function (url) { return rootUrlKey += url; });
  57005. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57006. };
  57007. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57008. if (forcedExtension === void 0) { forcedExtension = null; }
  57009. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57010. };
  57011. // Methods
  57012. CubeTexture.prototype.delayLoad = function () {
  57013. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57014. return;
  57015. }
  57016. var scene = this.getScene();
  57017. if (!scene) {
  57018. return;
  57019. }
  57020. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57021. this._texture = this._getFromCache(this.url, this._noMipmap);
  57022. if (!this._texture) {
  57023. if (this._prefiltered) {
  57024. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57025. }
  57026. else {
  57027. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57028. }
  57029. }
  57030. };
  57031. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57032. return this._textureMatrix;
  57033. };
  57034. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57035. this._textureMatrix = value;
  57036. };
  57037. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57038. var texture = BABYLON.SerializationHelper.Parse(function () {
  57039. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57040. }, parsedTexture, scene);
  57041. // Local Cubemaps
  57042. if (parsedTexture.boundingBoxPosition) {
  57043. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  57044. }
  57045. if (parsedTexture.boundingBoxSize) {
  57046. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  57047. }
  57048. // Animations
  57049. if (parsedTexture.animations) {
  57050. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57051. var parsedAnimation = parsedTexture.animations[animationIndex];
  57052. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57053. }
  57054. }
  57055. return texture;
  57056. };
  57057. CubeTexture.prototype.clone = function () {
  57058. var _this = this;
  57059. return BABYLON.SerializationHelper.Clone(function () {
  57060. var scene = _this.getScene();
  57061. if (!scene) {
  57062. return _this;
  57063. }
  57064. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57065. }, this);
  57066. };
  57067. return CubeTexture;
  57068. }(BABYLON.BaseTexture));
  57069. BABYLON.CubeTexture = CubeTexture;
  57070. })(BABYLON || (BABYLON = {}));
  57071. //# sourceMappingURL=babylon.cubeTexture.js.map
  57072. var BABYLON;
  57073. (function (BABYLON) {
  57074. var RenderTargetTexture = /** @class */ (function (_super) {
  57075. __extends(RenderTargetTexture, _super);
  57076. /**
  57077. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  57078. * or used a shadow, depth texture...
  57079. * @param name The friendly name of the texture
  57080. * @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)
  57081. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  57082. * @param generateMipMaps True if mip maps need to be generated after render.
  57083. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  57084. * @param type The type of the buffer in the RTT (int, half float, float...)
  57085. * @param isCube True if a cube texture needs to be created
  57086. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  57087. * @param generateDepthBuffer True to generate a depth buffer
  57088. * @param generateStencilBuffer True to generate a stencil buffer
  57089. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  57090. */
  57091. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57092. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57093. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57094. if (isCube === void 0) { isCube = false; }
  57095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57096. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57097. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57098. if (isMulti === void 0) { isMulti = false; }
  57099. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57100. _this.isCube = isCube;
  57101. /**
  57102. * Use this list to define the list of mesh you want to render.
  57103. */
  57104. _this.renderList = new Array();
  57105. _this.renderParticles = true;
  57106. _this.renderSprites = false;
  57107. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57108. _this.ignoreCameraViewport = false;
  57109. // Events
  57110. /**
  57111. * An event triggered when the texture is unbind.
  57112. * @type {BABYLON.Observable}
  57113. */
  57114. _this.onBeforeBindObservable = new BABYLON.Observable();
  57115. /**
  57116. * An event triggered when the texture is unbind.
  57117. * @type {BABYLON.Observable}
  57118. */
  57119. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57120. /**
  57121. * An event triggered before rendering the texture
  57122. * @type {BABYLON.Observable}
  57123. */
  57124. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57125. /**
  57126. * An event triggered after rendering the texture
  57127. * @type {BABYLON.Observable}
  57128. */
  57129. _this.onAfterRenderObservable = new BABYLON.Observable();
  57130. /**
  57131. * An event triggered after the texture clear
  57132. * @type {BABYLON.Observable}
  57133. */
  57134. _this.onClearObservable = new BABYLON.Observable();
  57135. _this._currentRefreshId = -1;
  57136. _this._refreshRate = 1;
  57137. _this._samples = 1;
  57138. /**
  57139. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57140. * It must define where the camera used to render the texture is set
  57141. */
  57142. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57143. scene = _this.getScene();
  57144. if (!scene) {
  57145. return _this;
  57146. }
  57147. _this._engine = scene.getEngine();
  57148. _this.name = name;
  57149. _this.isRenderTarget = true;
  57150. _this._initialSizeParameter = size;
  57151. _this._processSizeParameter(size);
  57152. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57153. });
  57154. _this._generateMipMaps = generateMipMaps ? true : false;
  57155. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57156. // Rendering groups
  57157. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57158. if (isMulti) {
  57159. return _this;
  57160. }
  57161. _this._renderTargetOptions = {
  57162. generateMipMaps: generateMipMaps,
  57163. type: type,
  57164. samplingMode: samplingMode,
  57165. generateDepthBuffer: generateDepthBuffer,
  57166. generateStencilBuffer: generateStencilBuffer
  57167. };
  57168. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57169. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57170. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57171. }
  57172. if (isCube) {
  57173. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57174. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57175. _this._textureMatrix = BABYLON.Matrix.Identity();
  57176. }
  57177. else {
  57178. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57179. }
  57180. return _this;
  57181. }
  57182. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57183. get: function () {
  57184. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57185. },
  57186. enumerable: true,
  57187. configurable: true
  57188. });
  57189. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57190. get: function () {
  57191. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57192. },
  57193. enumerable: true,
  57194. configurable: true
  57195. });
  57196. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57197. get: function () {
  57198. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57199. },
  57200. enumerable: true,
  57201. configurable: true
  57202. });
  57203. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57204. set: function (callback) {
  57205. if (this._onAfterUnbindObserver) {
  57206. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57207. }
  57208. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57209. },
  57210. enumerable: true,
  57211. configurable: true
  57212. });
  57213. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57214. set: function (callback) {
  57215. if (this._onBeforeRenderObserver) {
  57216. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57217. }
  57218. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57219. },
  57220. enumerable: true,
  57221. configurable: true
  57222. });
  57223. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57224. set: function (callback) {
  57225. if (this._onAfterRenderObserver) {
  57226. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57227. }
  57228. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57229. },
  57230. enumerable: true,
  57231. configurable: true
  57232. });
  57233. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57234. set: function (callback) {
  57235. if (this._onClearObserver) {
  57236. this.onClearObservable.remove(this._onClearObserver);
  57237. }
  57238. this._onClearObserver = this.onClearObservable.add(callback);
  57239. },
  57240. enumerable: true,
  57241. configurable: true
  57242. });
  57243. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57244. get: function () {
  57245. return this._renderTargetOptions;
  57246. },
  57247. enumerable: true,
  57248. configurable: true
  57249. });
  57250. RenderTargetTexture.prototype._onRatioRescale = function () {
  57251. if (this._sizeRatio) {
  57252. this.resize(this._initialSizeParameter);
  57253. }
  57254. };
  57255. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57256. get: function () {
  57257. return this._boundingBoxSize;
  57258. },
  57259. /**
  57260. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57261. * When defined, the cubemap will switch to local mode
  57262. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57263. * @example https://www.babylonjs-playground.com/#RNASML
  57264. */
  57265. set: function (value) {
  57266. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57267. return;
  57268. }
  57269. this._boundingBoxSize = value;
  57270. var scene = this.getScene();
  57271. if (scene) {
  57272. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57273. }
  57274. },
  57275. enumerable: true,
  57276. configurable: true
  57277. });
  57278. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57279. if (size.ratio) {
  57280. this._sizeRatio = size.ratio;
  57281. this._size = {
  57282. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57283. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57284. };
  57285. }
  57286. else {
  57287. this._size = size;
  57288. }
  57289. };
  57290. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57291. get: function () {
  57292. return this._samples;
  57293. },
  57294. set: function (value) {
  57295. if (this._samples === value) {
  57296. return;
  57297. }
  57298. var scene = this.getScene();
  57299. if (!scene) {
  57300. return;
  57301. }
  57302. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57303. },
  57304. enumerable: true,
  57305. configurable: true
  57306. });
  57307. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57308. this._currentRefreshId = -1;
  57309. };
  57310. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57311. get: function () {
  57312. return this._refreshRate;
  57313. },
  57314. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57315. set: function (value) {
  57316. this._refreshRate = value;
  57317. this.resetRefreshCounter();
  57318. },
  57319. enumerable: true,
  57320. configurable: true
  57321. });
  57322. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57323. if (!this._postProcessManager) {
  57324. var scene = this.getScene();
  57325. if (!scene) {
  57326. return;
  57327. }
  57328. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57329. this._postProcesses = new Array();
  57330. }
  57331. this._postProcesses.push(postProcess);
  57332. this._postProcesses[0].autoClear = false;
  57333. };
  57334. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57335. if (!this._postProcesses) {
  57336. return;
  57337. }
  57338. if (dispose) {
  57339. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57340. var postProcess = _a[_i];
  57341. postProcess.dispose();
  57342. }
  57343. }
  57344. this._postProcesses = [];
  57345. };
  57346. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57347. if (!this._postProcesses) {
  57348. return;
  57349. }
  57350. var index = this._postProcesses.indexOf(postProcess);
  57351. if (index === -1) {
  57352. return;
  57353. }
  57354. this._postProcesses.splice(index, 1);
  57355. if (this._postProcesses.length > 0) {
  57356. this._postProcesses[0].autoClear = false;
  57357. }
  57358. };
  57359. RenderTargetTexture.prototype._shouldRender = function () {
  57360. if (this._currentRefreshId === -1) {
  57361. this._currentRefreshId = 1;
  57362. return true;
  57363. }
  57364. if (this.refreshRate === this._currentRefreshId) {
  57365. this._currentRefreshId = 1;
  57366. return true;
  57367. }
  57368. this._currentRefreshId++;
  57369. return false;
  57370. };
  57371. RenderTargetTexture.prototype.getRenderSize = function () {
  57372. if (this._size.width) {
  57373. return this._size.width;
  57374. }
  57375. return this._size;
  57376. };
  57377. RenderTargetTexture.prototype.getRenderWidth = function () {
  57378. if (this._size.width) {
  57379. return this._size.width;
  57380. }
  57381. return this._size;
  57382. };
  57383. RenderTargetTexture.prototype.getRenderHeight = function () {
  57384. if (this._size.width) {
  57385. return this._size.height;
  57386. }
  57387. return this._size;
  57388. };
  57389. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57390. get: function () {
  57391. return true;
  57392. },
  57393. enumerable: true,
  57394. configurable: true
  57395. });
  57396. RenderTargetTexture.prototype.scale = function (ratio) {
  57397. var newSize = this.getRenderSize() * ratio;
  57398. this.resize(newSize);
  57399. };
  57400. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57401. if (this.isCube) {
  57402. return this._textureMatrix;
  57403. }
  57404. return _super.prototype.getReflectionTextureMatrix.call(this);
  57405. };
  57406. RenderTargetTexture.prototype.resize = function (size) {
  57407. this.releaseInternalTexture();
  57408. var scene = this.getScene();
  57409. if (!scene) {
  57410. return;
  57411. }
  57412. this._processSizeParameter(size);
  57413. if (this.isCube) {
  57414. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57415. }
  57416. else {
  57417. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57418. }
  57419. };
  57420. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57421. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57422. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57423. var scene = this.getScene();
  57424. if (!scene) {
  57425. return;
  57426. }
  57427. var engine = scene.getEngine();
  57428. if (this.useCameraPostProcesses !== undefined) {
  57429. useCameraPostProcess = this.useCameraPostProcesses;
  57430. }
  57431. if (this._waitingRenderList) {
  57432. this.renderList = [];
  57433. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57434. var id = this._waitingRenderList[index];
  57435. var mesh_1 = scene.getMeshByID(id);
  57436. if (mesh_1) {
  57437. this.renderList.push(mesh_1);
  57438. }
  57439. }
  57440. delete this._waitingRenderList;
  57441. }
  57442. // Is predicate defined?
  57443. if (this.renderListPredicate) {
  57444. if (this.renderList) {
  57445. this.renderList.splice(0); // Clear previous renderList
  57446. }
  57447. else {
  57448. this.renderList = [];
  57449. }
  57450. var scene = this.getScene();
  57451. if (!scene) {
  57452. return;
  57453. }
  57454. var sceneMeshes = scene.meshes;
  57455. for (var index = 0; index < sceneMeshes.length; index++) {
  57456. var mesh = sceneMeshes[index];
  57457. if (this.renderListPredicate(mesh)) {
  57458. this.renderList.push(mesh);
  57459. }
  57460. }
  57461. }
  57462. this.onBeforeBindObservable.notifyObservers(this);
  57463. // Set custom projection.
  57464. // Needs to be before binding to prevent changing the aspect ratio.
  57465. var camera;
  57466. if (this.activeCamera) {
  57467. camera = this.activeCamera;
  57468. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57469. if (this.activeCamera !== scene.activeCamera) {
  57470. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57471. }
  57472. }
  57473. else {
  57474. camera = scene.activeCamera;
  57475. if (camera) {
  57476. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57477. }
  57478. }
  57479. // Prepare renderingManager
  57480. this._renderingManager.reset();
  57481. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57482. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57483. var sceneRenderId = scene.getRenderId();
  57484. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57485. var mesh = currentRenderList[meshIndex];
  57486. if (mesh) {
  57487. if (!mesh.isReady()) {
  57488. // Reset _currentRefreshId
  57489. this.resetRefreshCounter();
  57490. continue;
  57491. }
  57492. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57493. var isMasked = void 0;
  57494. if (!this.renderList && camera) {
  57495. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57496. }
  57497. else {
  57498. isMasked = false;
  57499. }
  57500. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57501. mesh._activate(sceneRenderId);
  57502. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57503. var subMesh = mesh.subMeshes[subIndex];
  57504. scene._activeIndices.addCount(subMesh.indexCount, false);
  57505. this._renderingManager.dispatch(subMesh, mesh);
  57506. }
  57507. }
  57508. }
  57509. }
  57510. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57511. var particleSystem = scene.particleSystems[particleIndex];
  57512. var emitter = particleSystem.emitter;
  57513. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57514. continue;
  57515. }
  57516. if (currentRenderList.indexOf(emitter) >= 0) {
  57517. this._renderingManager.dispatchParticles(particleSystem);
  57518. }
  57519. }
  57520. if (this.isCube) {
  57521. for (var face = 0; face < 6; face++) {
  57522. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57523. scene.incrementRenderId();
  57524. scene.resetCachedMaterial();
  57525. }
  57526. }
  57527. else {
  57528. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57529. }
  57530. this.onAfterUnbindObservable.notifyObservers(this);
  57531. if (scene.activeCamera) {
  57532. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57533. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57534. }
  57535. engine.setViewport(scene.activeCamera.viewport);
  57536. }
  57537. scene.resetCachedMaterial();
  57538. };
  57539. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57540. var minimum = 128;
  57541. var x = renderDimension * scale;
  57542. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57543. // Ensure we don't exceed the render dimension (while staying POT)
  57544. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57545. };
  57546. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57547. var _this = this;
  57548. if (!this._texture) {
  57549. return;
  57550. }
  57551. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57552. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57553. });
  57554. };
  57555. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57556. var scene = this.getScene();
  57557. if (!scene) {
  57558. return;
  57559. }
  57560. var engine = scene.getEngine();
  57561. if (!this._texture) {
  57562. return;
  57563. }
  57564. // Bind
  57565. if (this._postProcessManager) {
  57566. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57567. }
  57568. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57569. if (this._texture) {
  57570. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  57571. }
  57572. }
  57573. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57574. // Clear
  57575. if (this.onClearObservable.hasObservers()) {
  57576. this.onClearObservable.notifyObservers(engine);
  57577. }
  57578. else {
  57579. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57580. }
  57581. if (!this._doNotChangeAspectRatio) {
  57582. scene.updateTransformMatrix(true);
  57583. }
  57584. // Render
  57585. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57586. if (this._postProcessManager) {
  57587. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57588. }
  57589. else if (useCameraPostProcess) {
  57590. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57591. }
  57592. if (!this._doNotChangeAspectRatio) {
  57593. scene.updateTransformMatrix(true);
  57594. }
  57595. // Dump ?
  57596. if (dumpForDebug) {
  57597. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57598. }
  57599. // Unbind
  57600. if (!this.isCube || faceIndex === 5) {
  57601. if (this.isCube) {
  57602. if (faceIndex === 5) {
  57603. engine.generateMipMapsForCubemap(this._texture);
  57604. }
  57605. }
  57606. this.unbindFrameBuffer(engine, faceIndex);
  57607. }
  57608. else {
  57609. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57610. }
  57611. };
  57612. /**
  57613. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57614. * This allowed control for front to back rendering or reversly depending of the special needs.
  57615. *
  57616. * @param renderingGroupId The rendering group id corresponding to its index
  57617. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57618. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57619. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57620. */
  57621. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57622. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57623. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57624. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57625. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57626. };
  57627. /**
  57628. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57629. *
  57630. * @param renderingGroupId The rendering group id corresponding to its index
  57631. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57632. */
  57633. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57634. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57635. };
  57636. RenderTargetTexture.prototype.clone = function () {
  57637. var textureSize = this.getSize();
  57638. 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);
  57639. // Base texture
  57640. newTexture.hasAlpha = this.hasAlpha;
  57641. newTexture.level = this.level;
  57642. // RenderTarget Texture
  57643. newTexture.coordinatesMode = this.coordinatesMode;
  57644. if (this.renderList) {
  57645. newTexture.renderList = this.renderList.slice(0);
  57646. }
  57647. return newTexture;
  57648. };
  57649. RenderTargetTexture.prototype.serialize = function () {
  57650. if (!this.name) {
  57651. return null;
  57652. }
  57653. var serializationObject = _super.prototype.serialize.call(this);
  57654. serializationObject.renderTargetSize = this.getRenderSize();
  57655. serializationObject.renderList = [];
  57656. if (this.renderList) {
  57657. for (var index = 0; index < this.renderList.length; index++) {
  57658. serializationObject.renderList.push(this.renderList[index].id);
  57659. }
  57660. }
  57661. return serializationObject;
  57662. };
  57663. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57664. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57665. var objBuffer = this.getInternalTexture();
  57666. var scene = this.getScene();
  57667. if (objBuffer && scene) {
  57668. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57669. }
  57670. };
  57671. RenderTargetTexture.prototype.dispose = function () {
  57672. if (this._postProcessManager) {
  57673. this._postProcessManager.dispose();
  57674. this._postProcessManager = null;
  57675. }
  57676. this.clearPostProcesses(true);
  57677. if (this._resizeObserver) {
  57678. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57679. this._resizeObserver = null;
  57680. }
  57681. this.renderList = null;
  57682. // Remove from custom render targets
  57683. var scene = this.getScene();
  57684. if (!scene) {
  57685. return;
  57686. }
  57687. var index = scene.customRenderTargets.indexOf(this);
  57688. if (index >= 0) {
  57689. scene.customRenderTargets.splice(index, 1);
  57690. }
  57691. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57692. var camera = _a[_i];
  57693. index = camera.customRenderTargets.indexOf(this);
  57694. if (index >= 0) {
  57695. camera.customRenderTargets.splice(index, 1);
  57696. }
  57697. }
  57698. _super.prototype.dispose.call(this);
  57699. };
  57700. RenderTargetTexture.prototype._rebuild = function () {
  57701. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57702. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57703. }
  57704. if (this._postProcessManager) {
  57705. this._postProcessManager._rebuild();
  57706. }
  57707. };
  57708. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57709. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57710. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57711. return RenderTargetTexture;
  57712. }(BABYLON.Texture));
  57713. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57714. })(BABYLON || (BABYLON = {}));
  57715. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57716. var BABYLON;
  57717. (function (BABYLON) {
  57718. ;
  57719. var MultiRenderTarget = /** @class */ (function (_super) {
  57720. __extends(MultiRenderTarget, _super);
  57721. function MultiRenderTarget(name, size, count, scene, options) {
  57722. var _this = this;
  57723. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57724. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57725. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57726. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57727. _this._engine = scene.getEngine();
  57728. if (!_this.isSupported) {
  57729. _this.dispose();
  57730. return;
  57731. }
  57732. var types = [];
  57733. var samplingModes = [];
  57734. for (var i = 0; i < count; i++) {
  57735. if (options && options.types && options.types[i] !== undefined) {
  57736. types.push(options.types[i]);
  57737. }
  57738. else {
  57739. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57740. }
  57741. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57742. samplingModes.push(options.samplingModes[i]);
  57743. }
  57744. else {
  57745. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57746. }
  57747. }
  57748. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57749. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57750. _this._size = size;
  57751. _this._multiRenderTargetOptions = {
  57752. samplingModes: samplingModes,
  57753. generateMipMaps: generateMipMaps,
  57754. generateDepthBuffer: generateDepthBuffer,
  57755. generateStencilBuffer: generateStencilBuffer,
  57756. generateDepthTexture: generateDepthTexture,
  57757. types: types,
  57758. textureCount: count
  57759. };
  57760. _this._createInternalTextures();
  57761. _this._createTextures();
  57762. return _this;
  57763. }
  57764. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57765. get: function () {
  57766. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57767. },
  57768. enumerable: true,
  57769. configurable: true
  57770. });
  57771. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57772. get: function () {
  57773. return this._textures;
  57774. },
  57775. enumerable: true,
  57776. configurable: true
  57777. });
  57778. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57779. get: function () {
  57780. return this._textures[this._textures.length - 1];
  57781. },
  57782. enumerable: true,
  57783. configurable: true
  57784. });
  57785. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57786. set: function (wrap) {
  57787. if (this._textures) {
  57788. for (var i = 0; i < this._textures.length; i++) {
  57789. this._textures[i].wrapU = wrap;
  57790. }
  57791. }
  57792. },
  57793. enumerable: true,
  57794. configurable: true
  57795. });
  57796. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57797. set: function (wrap) {
  57798. if (this._textures) {
  57799. for (var i = 0; i < this._textures.length; i++) {
  57800. this._textures[i].wrapV = wrap;
  57801. }
  57802. }
  57803. },
  57804. enumerable: true,
  57805. configurable: true
  57806. });
  57807. MultiRenderTarget.prototype._rebuild = function () {
  57808. this.releaseInternalTextures();
  57809. this._createInternalTextures();
  57810. for (var i = 0; i < this._internalTextures.length; i++) {
  57811. var texture = this._textures[i];
  57812. texture._texture = this._internalTextures[i];
  57813. }
  57814. // Keeps references to frame buffer and stencil/depth buffer
  57815. this._texture = this._internalTextures[0];
  57816. };
  57817. MultiRenderTarget.prototype._createInternalTextures = function () {
  57818. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57819. };
  57820. MultiRenderTarget.prototype._createTextures = function () {
  57821. this._textures = [];
  57822. for (var i = 0; i < this._internalTextures.length; i++) {
  57823. var texture = new BABYLON.Texture(null, this.getScene());
  57824. texture._texture = this._internalTextures[i];
  57825. this._textures.push(texture);
  57826. }
  57827. // Keeps references to frame buffer and stencil/depth buffer
  57828. this._texture = this._internalTextures[0];
  57829. };
  57830. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57831. get: function () {
  57832. return this._samples;
  57833. },
  57834. set: function (value) {
  57835. if (this._samples === value) {
  57836. return;
  57837. }
  57838. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57839. },
  57840. enumerable: true,
  57841. configurable: true
  57842. });
  57843. MultiRenderTarget.prototype.resize = function (size) {
  57844. this.releaseInternalTextures();
  57845. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57846. this._createInternalTextures();
  57847. };
  57848. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57849. var _this = this;
  57850. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57851. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57852. });
  57853. };
  57854. MultiRenderTarget.prototype.dispose = function () {
  57855. this.releaseInternalTextures();
  57856. _super.prototype.dispose.call(this);
  57857. };
  57858. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57859. if (!this._internalTextures) {
  57860. return;
  57861. }
  57862. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57863. if (this._internalTextures[i] !== undefined) {
  57864. this._internalTextures[i].dispose();
  57865. this._internalTextures.splice(i, 1);
  57866. }
  57867. }
  57868. };
  57869. return MultiRenderTarget;
  57870. }(BABYLON.RenderTargetTexture));
  57871. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57872. })(BABYLON || (BABYLON = {}));
  57873. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57874. var BABYLON;
  57875. (function (BABYLON) {
  57876. var MirrorTexture = /** @class */ (function (_super) {
  57877. __extends(MirrorTexture, _super);
  57878. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57879. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57881. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57882. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57883. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57884. _this._transformMatrix = BABYLON.Matrix.Zero();
  57885. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57886. _this._adaptiveBlurKernel = 0;
  57887. _this._blurKernelX = 0;
  57888. _this._blurKernelY = 0;
  57889. _this._blurRatio = 1.0;
  57890. _this.ignoreCameraViewport = true;
  57891. _this.onBeforeRenderObservable.add(function () {
  57892. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57893. _this._savedViewMatrix = scene.getViewMatrix();
  57894. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57895. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57896. scene.clipPlane = _this.mirrorPlane;
  57897. scene.getEngine().cullBackFaces = false;
  57898. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57899. });
  57900. _this.onAfterRenderObservable.add(function () {
  57901. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57902. scene.getEngine().cullBackFaces = true;
  57903. scene._mirroredCameraPosition = null;
  57904. delete scene.clipPlane;
  57905. });
  57906. return _this;
  57907. }
  57908. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57909. get: function () {
  57910. return this._blurRatio;
  57911. },
  57912. set: function (value) {
  57913. if (this._blurRatio === value) {
  57914. return;
  57915. }
  57916. this._blurRatio = value;
  57917. this._preparePostProcesses();
  57918. },
  57919. enumerable: true,
  57920. configurable: true
  57921. });
  57922. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57923. set: function (value) {
  57924. this._adaptiveBlurKernel = value;
  57925. this._autoComputeBlurKernel();
  57926. },
  57927. enumerable: true,
  57928. configurable: true
  57929. });
  57930. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57931. set: function (value) {
  57932. this.blurKernelX = value;
  57933. this.blurKernelY = value;
  57934. },
  57935. enumerable: true,
  57936. configurable: true
  57937. });
  57938. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57939. get: function () {
  57940. return this._blurKernelX;
  57941. },
  57942. set: function (value) {
  57943. if (this._blurKernelX === value) {
  57944. return;
  57945. }
  57946. this._blurKernelX = value;
  57947. this._preparePostProcesses();
  57948. },
  57949. enumerable: true,
  57950. configurable: true
  57951. });
  57952. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57953. get: function () {
  57954. return this._blurKernelY;
  57955. },
  57956. set: function (value) {
  57957. if (this._blurKernelY === value) {
  57958. return;
  57959. }
  57960. this._blurKernelY = value;
  57961. this._preparePostProcesses();
  57962. },
  57963. enumerable: true,
  57964. configurable: true
  57965. });
  57966. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57967. var engine = this.getScene().getEngine();
  57968. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57969. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57970. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57971. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57972. };
  57973. MirrorTexture.prototype._onRatioRescale = function () {
  57974. if (this._sizeRatio) {
  57975. this.resize(this._initialSizeParameter);
  57976. if (!this._adaptiveBlurKernel) {
  57977. this._preparePostProcesses();
  57978. }
  57979. }
  57980. if (this._adaptiveBlurKernel) {
  57981. this._autoComputeBlurKernel();
  57982. }
  57983. };
  57984. MirrorTexture.prototype._preparePostProcesses = function () {
  57985. this.clearPostProcesses(true);
  57986. if (this._blurKernelX && this._blurKernelY) {
  57987. var engine = this.getScene().getEngine();
  57988. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57989. 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);
  57990. this._blurX.autoClear = false;
  57991. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57992. this._blurX.inputTexture = this._texture;
  57993. }
  57994. else {
  57995. this._blurX.alwaysForcePOT = true;
  57996. }
  57997. 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);
  57998. this._blurY.autoClear = false;
  57999. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58000. this.addPostProcess(this._blurX);
  58001. this.addPostProcess(this._blurY);
  58002. }
  58003. else {
  58004. if (this._blurY) {
  58005. this.removePostProcess(this._blurY);
  58006. this._blurY.dispose();
  58007. this._blurY = null;
  58008. }
  58009. if (this._blurX) {
  58010. this.removePostProcess(this._blurX);
  58011. this._blurX.dispose();
  58012. this._blurX = null;
  58013. }
  58014. }
  58015. };
  58016. MirrorTexture.prototype.clone = function () {
  58017. var scene = this.getScene();
  58018. if (!scene) {
  58019. return this;
  58020. }
  58021. var textureSize = this.getSize();
  58022. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58023. // Base texture
  58024. newTexture.hasAlpha = this.hasAlpha;
  58025. newTexture.level = this.level;
  58026. // Mirror Texture
  58027. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58028. if (this.renderList) {
  58029. newTexture.renderList = this.renderList.slice(0);
  58030. }
  58031. return newTexture;
  58032. };
  58033. MirrorTexture.prototype.serialize = function () {
  58034. if (!this.name) {
  58035. return null;
  58036. }
  58037. var serializationObject = _super.prototype.serialize.call(this);
  58038. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58039. return serializationObject;
  58040. };
  58041. return MirrorTexture;
  58042. }(BABYLON.RenderTargetTexture));
  58043. BABYLON.MirrorTexture = MirrorTexture;
  58044. })(BABYLON || (BABYLON = {}));
  58045. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58046. var BABYLON;
  58047. (function (BABYLON) {
  58048. /**
  58049. * Creates a refraction texture used by refraction channel of the standard material.
  58050. * @param name the texture name
  58051. * @param size size of the underlying texture
  58052. * @param scene root scene
  58053. */
  58054. var RefractionTexture = /** @class */ (function (_super) {
  58055. __extends(RefractionTexture, _super);
  58056. function RefractionTexture(name, size, scene, generateMipMaps) {
  58057. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58058. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58059. _this.depth = 2.0;
  58060. _this.onBeforeRenderObservable.add(function () {
  58061. scene.clipPlane = _this.refractionPlane;
  58062. });
  58063. _this.onAfterRenderObservable.add(function () {
  58064. delete scene.clipPlane;
  58065. });
  58066. return _this;
  58067. }
  58068. RefractionTexture.prototype.clone = function () {
  58069. var scene = this.getScene();
  58070. if (!scene) {
  58071. return this;
  58072. }
  58073. var textureSize = this.getSize();
  58074. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58075. // Base texture
  58076. newTexture.hasAlpha = this.hasAlpha;
  58077. newTexture.level = this.level;
  58078. // Refraction Texture
  58079. newTexture.refractionPlane = this.refractionPlane.clone();
  58080. if (this.renderList) {
  58081. newTexture.renderList = this.renderList.slice(0);
  58082. }
  58083. newTexture.depth = this.depth;
  58084. return newTexture;
  58085. };
  58086. RefractionTexture.prototype.serialize = function () {
  58087. if (!this.name) {
  58088. return null;
  58089. }
  58090. var serializationObject = _super.prototype.serialize.call(this);
  58091. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58092. serializationObject.depth = this.depth;
  58093. return serializationObject;
  58094. };
  58095. return RefractionTexture;
  58096. }(BABYLON.RenderTargetTexture));
  58097. BABYLON.RefractionTexture = RefractionTexture;
  58098. })(BABYLON || (BABYLON = {}));
  58099. //# sourceMappingURL=babylon.refractionTexture.js.map
  58100. var BABYLON;
  58101. (function (BABYLON) {
  58102. var DynamicTexture = /** @class */ (function (_super) {
  58103. __extends(DynamicTexture, _super);
  58104. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58105. if (scene === void 0) { scene = null; }
  58106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58107. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58108. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58109. _this.name = name;
  58110. _this._engine = _this.getScene().getEngine();
  58111. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58112. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58113. _this._generateMipMaps = generateMipMaps;
  58114. if (options.getContext) {
  58115. _this._canvas = options;
  58116. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58117. }
  58118. else {
  58119. _this._canvas = document.createElement("canvas");
  58120. if (options.width) {
  58121. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58122. }
  58123. else {
  58124. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58125. }
  58126. }
  58127. var textureSize = _this.getSize();
  58128. _this._canvas.width = textureSize.width;
  58129. _this._canvas.height = textureSize.height;
  58130. _this._context = _this._canvas.getContext("2d");
  58131. return _this;
  58132. }
  58133. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58134. get: function () {
  58135. return true;
  58136. },
  58137. enumerable: true,
  58138. configurable: true
  58139. });
  58140. DynamicTexture.prototype._recreate = function (textureSize) {
  58141. this._canvas.width = textureSize.width;
  58142. this._canvas.height = textureSize.height;
  58143. this.releaseInternalTexture();
  58144. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58145. };
  58146. DynamicTexture.prototype.scale = function (ratio) {
  58147. var textureSize = this.getSize();
  58148. textureSize.width *= ratio;
  58149. textureSize.height *= ratio;
  58150. this._recreate(textureSize);
  58151. };
  58152. DynamicTexture.prototype.scaleTo = function (width, height) {
  58153. var textureSize = this.getSize();
  58154. textureSize.width = width;
  58155. textureSize.height = height;
  58156. this._recreate(textureSize);
  58157. };
  58158. DynamicTexture.prototype.getContext = function () {
  58159. return this._context;
  58160. };
  58161. DynamicTexture.prototype.clear = function () {
  58162. var size = this.getSize();
  58163. this._context.fillRect(0, 0, size.width, size.height);
  58164. };
  58165. DynamicTexture.prototype.update = function (invertY) {
  58166. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58167. };
  58168. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58169. if (update === void 0) { update = true; }
  58170. var size = this.getSize();
  58171. if (clearColor) {
  58172. this._context.fillStyle = clearColor;
  58173. this._context.fillRect(0, 0, size.width, size.height);
  58174. }
  58175. this._context.font = font;
  58176. if (x === null || x === undefined) {
  58177. var textSize = this._context.measureText(text);
  58178. x = (size.width - textSize.width) / 2;
  58179. }
  58180. if (y === null || y === undefined) {
  58181. var fontSize = parseInt((font.replace(/\D/g, '')));
  58182. ;
  58183. y = (size.height / 2) + (fontSize / 3.65);
  58184. }
  58185. this._context.fillStyle = color;
  58186. this._context.fillText(text, x, y);
  58187. if (update) {
  58188. this.update(invertY);
  58189. }
  58190. };
  58191. DynamicTexture.prototype.clone = function () {
  58192. var scene = this.getScene();
  58193. if (!scene) {
  58194. return this;
  58195. }
  58196. var textureSize = this.getSize();
  58197. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58198. // Base texture
  58199. newTexture.hasAlpha = this.hasAlpha;
  58200. newTexture.level = this.level;
  58201. // Dynamic Texture
  58202. newTexture.wrapU = this.wrapU;
  58203. newTexture.wrapV = this.wrapV;
  58204. return newTexture;
  58205. };
  58206. DynamicTexture.prototype._rebuild = function () {
  58207. this.update();
  58208. };
  58209. return DynamicTexture;
  58210. }(BABYLON.Texture));
  58211. BABYLON.DynamicTexture = DynamicTexture;
  58212. })(BABYLON || (BABYLON = {}));
  58213. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58214. var BABYLON;
  58215. (function (BABYLON) {
  58216. var VideoTexture = /** @class */ (function (_super) {
  58217. __extends(VideoTexture, _super);
  58218. /**
  58219. * Creates a video texture.
  58220. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58221. * @param {string | null} name optional name, will detect from video source, if not defined
  58222. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58223. * @param {BABYLON.Scene} scene is obviously the current scene.
  58224. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58225. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58226. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58227. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58228. */
  58229. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58230. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58231. if (invertY === void 0) { invertY = false; }
  58232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58233. if (settings === void 0) { settings = {
  58234. autoPlay: true,
  58235. loop: true,
  58236. autoUpdateTexture: true,
  58237. }; }
  58238. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58239. _this._createInternalTexture = function () {
  58240. if (_this._texture != null) {
  58241. return;
  58242. }
  58243. if (!_this._engine.needPOTTextures ||
  58244. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58245. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58246. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58247. }
  58248. else {
  58249. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58250. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58251. _this._generateMipMaps = false;
  58252. }
  58253. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58254. _this._texture.isReady = true;
  58255. _this._updateInternalTexture();
  58256. };
  58257. _this.reset = function () {
  58258. if (_this._texture == null) {
  58259. return;
  58260. }
  58261. _this._texture.dispose();
  58262. _this._texture = null;
  58263. };
  58264. _this._updateInternalTexture = function (e) {
  58265. if (_this._texture == null || !_this._texture.isReady) {
  58266. return;
  58267. }
  58268. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58269. return;
  58270. }
  58271. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58272. };
  58273. _this._engine = _this.getScene().getEngine();
  58274. _this._generateMipMaps = generateMipMaps;
  58275. _this._samplingMode = samplingMode;
  58276. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58277. _this.name = name || _this._getName(src);
  58278. _this.video = _this._getVideo(src);
  58279. if (settings.autoPlay !== undefined) {
  58280. _this.video.autoplay = settings.autoPlay;
  58281. }
  58282. if (settings.loop !== undefined) {
  58283. _this.video.loop = settings.loop;
  58284. }
  58285. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58286. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58287. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58288. _this.video.addEventListener("emptied", _this.reset);
  58289. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58290. _this._createInternalTexture();
  58291. }
  58292. return _this;
  58293. }
  58294. VideoTexture.prototype._getName = function (src) {
  58295. if (src instanceof HTMLVideoElement) {
  58296. return src.currentSrc;
  58297. }
  58298. if (typeof src === "object") {
  58299. return src.toString();
  58300. }
  58301. return src;
  58302. };
  58303. ;
  58304. VideoTexture.prototype._getVideo = function (src) {
  58305. if (src instanceof HTMLVideoElement) {
  58306. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58307. return src;
  58308. }
  58309. var video = document.createElement("video");
  58310. if (typeof src === "string") {
  58311. BABYLON.Tools.SetCorsBehavior(src, video);
  58312. video.src = src;
  58313. }
  58314. else {
  58315. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58316. src.forEach(function (url) {
  58317. var source = document.createElement("source");
  58318. source.src = url;
  58319. video.appendChild(source);
  58320. });
  58321. }
  58322. return video;
  58323. };
  58324. ;
  58325. /**
  58326. * Internal method to initiate `update`.
  58327. */
  58328. VideoTexture.prototype._rebuild = function () {
  58329. this.update();
  58330. };
  58331. /**
  58332. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58333. */
  58334. VideoTexture.prototype.update = function () {
  58335. if (!this.autoUpdateTexture) {
  58336. // Expecting user to call `updateTexture` manually
  58337. return;
  58338. }
  58339. this.updateTexture(true);
  58340. };
  58341. /**
  58342. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58343. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58344. */
  58345. VideoTexture.prototype.updateTexture = function (isVisible) {
  58346. if (!isVisible) {
  58347. return;
  58348. }
  58349. if (this.video.paused) {
  58350. return;
  58351. }
  58352. this._updateInternalTexture();
  58353. };
  58354. /**
  58355. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58356. * @param url New url.
  58357. */
  58358. VideoTexture.prototype.updateURL = function (url) {
  58359. this.video.src = url;
  58360. };
  58361. VideoTexture.prototype.dispose = function () {
  58362. _super.prototype.dispose.call(this);
  58363. this.video.removeEventListener("canplay", this._createInternalTexture);
  58364. this.video.removeEventListener("paused", this._updateInternalTexture);
  58365. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58366. this.video.removeEventListener("emptied", this.reset);
  58367. this.video.pause();
  58368. };
  58369. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58370. var video = document.createElement("video");
  58371. var constraintsDeviceId;
  58372. if (constraints && constraints.deviceId) {
  58373. constraintsDeviceId = {
  58374. exact: constraints.deviceId,
  58375. };
  58376. }
  58377. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58378. if (navigator.mediaDevices) {
  58379. navigator.mediaDevices.getUserMedia({ video: constraints })
  58380. .then(function (stream) {
  58381. if (video.mozSrcObject !== undefined) {
  58382. // hack for Firefox < 19
  58383. video.mozSrcObject = stream;
  58384. }
  58385. else {
  58386. video.srcObject = stream;
  58387. }
  58388. var onPlaying = function () {
  58389. if (onReady) {
  58390. onReady(new VideoTexture("video", video, scene, true, true));
  58391. }
  58392. video.removeEventListener("playing", onPlaying);
  58393. };
  58394. video.addEventListener("playing", onPlaying);
  58395. video.play();
  58396. })
  58397. .catch(function (err) {
  58398. BABYLON.Tools.Error(err.name);
  58399. });
  58400. }
  58401. else {
  58402. navigator.getUserMedia =
  58403. navigator.getUserMedia ||
  58404. navigator.webkitGetUserMedia ||
  58405. navigator.mozGetUserMedia ||
  58406. navigator.msGetUserMedia;
  58407. if (navigator.getUserMedia) {
  58408. navigator.getUserMedia({
  58409. video: {
  58410. deviceId: constraintsDeviceId,
  58411. width: {
  58412. min: (constraints && constraints.minWidth) || 256,
  58413. max: (constraints && constraints.maxWidth) || 640,
  58414. },
  58415. height: {
  58416. min: (constraints && constraints.minHeight) || 256,
  58417. max: (constraints && constraints.maxHeight) || 480,
  58418. },
  58419. },
  58420. }, function (stream) {
  58421. if (video.mozSrcObject !== undefined) {
  58422. // hack for Firefox < 19
  58423. video.mozSrcObject = stream;
  58424. }
  58425. else {
  58426. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58427. }
  58428. video.play();
  58429. if (onReady) {
  58430. onReady(new VideoTexture("video", video, scene, true, true));
  58431. }
  58432. }, function (e) {
  58433. BABYLON.Tools.Error(e.name);
  58434. });
  58435. }
  58436. }
  58437. };
  58438. return VideoTexture;
  58439. }(BABYLON.Texture));
  58440. BABYLON.VideoTexture = VideoTexture;
  58441. })(BABYLON || (BABYLON = {}));
  58442. //# sourceMappingURL=babylon.videoTexture.js.map
  58443. var BABYLON;
  58444. (function (BABYLON) {
  58445. var RawTexture = /** @class */ (function (_super) {
  58446. __extends(RawTexture, _super);
  58447. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58448. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58449. if (invertY === void 0) { invertY = false; }
  58450. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58451. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58452. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58453. _this.format = format;
  58454. _this._engine = scene.getEngine();
  58455. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58456. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58457. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58458. return _this;
  58459. }
  58460. RawTexture.prototype.update = function (data) {
  58461. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58462. };
  58463. // Statics
  58464. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58465. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58466. if (invertY === void 0) { invertY = false; }
  58467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58468. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58469. };
  58470. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58471. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58472. if (invertY === void 0) { invertY = false; }
  58473. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58474. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58475. };
  58476. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58478. if (invertY === void 0) { invertY = false; }
  58479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58480. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58481. };
  58482. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58483. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58484. if (invertY === void 0) { invertY = false; }
  58485. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58486. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58487. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58488. };
  58489. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58490. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58491. if (invertY === void 0) { invertY = false; }
  58492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58493. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58494. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58495. };
  58496. return RawTexture;
  58497. }(BABYLON.Texture));
  58498. BABYLON.RawTexture = RawTexture;
  58499. })(BABYLON || (BABYLON = {}));
  58500. //# sourceMappingURL=babylon.rawTexture.js.map
  58501. var BABYLON;
  58502. (function (BABYLON) {
  58503. /**
  58504. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58505. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58506. */
  58507. var PostProcess = /** @class */ (function () {
  58508. /**
  58509. * Creates a new instance of @see PostProcess
  58510. * @param name The name of the PostProcess.
  58511. * @param fragmentUrl The url of the fragment shader to be used.
  58512. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58513. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58514. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58515. * @param camera The camera to apply the render pass to.
  58516. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58517. * @param engine The engine which the post process will be applied. (default: current engine)
  58518. * @param reusable If the post process can be reused on the same frame. (default: false)
  58519. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58520. * @param textureType Type of textures used when performing the post process. (default: 0)
  58521. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58522. * @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
  58523. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58524. */
  58525. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58527. if (defines === void 0) { defines = null; }
  58528. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58529. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58530. if (blockCompilation === void 0) { blockCompilation = false; }
  58531. this.name = name;
  58532. /**
  58533. * Width of the texture to apply the post process on
  58534. */
  58535. this.width = -1;
  58536. /**
  58537. * Height of the texture to apply the post process on
  58538. */
  58539. this.height = -1;
  58540. /**
  58541. * If the buffer needs to be cleared before applying the post process. (default: true)
  58542. * Should be set to false if shader will overwrite all previous pixels.
  58543. */
  58544. this.autoClear = true;
  58545. /**
  58546. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58547. */
  58548. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58549. /**
  58550. * Animations to be used for the post processing
  58551. */
  58552. this.animations = new Array();
  58553. /**
  58554. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58555. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58556. */
  58557. this.enablePixelPerfectMode = false;
  58558. /**
  58559. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58560. */
  58561. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58562. /**
  58563. * Force textures to be a power of two (default: false)
  58564. */
  58565. this.alwaysForcePOT = false;
  58566. /**
  58567. * Number of sample textures (default: 1)
  58568. */
  58569. this.samples = 1;
  58570. /**
  58571. * Modify the scale of the post process to be the same as the viewport (default: false)
  58572. */
  58573. this.adaptScaleToCurrentViewport = false;
  58574. this._reusable = false;
  58575. /**
  58576. * Smart array of input and output textures for the post process.
  58577. */
  58578. this._textures = new BABYLON.SmartArray(2);
  58579. /**
  58580. * The index in _textures that corresponds to the output texture.
  58581. */
  58582. this._currentRenderTextureInd = 0;
  58583. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58584. this._texelSize = BABYLON.Vector2.Zero();
  58585. // Events
  58586. /**
  58587. * An event triggered when the postprocess is activated.
  58588. * @type {BABYLON.Observable}
  58589. */
  58590. this.onActivateObservable = new BABYLON.Observable();
  58591. /**
  58592. * An event triggered when the postprocess changes its size.
  58593. * @type {BABYLON.Observable}
  58594. */
  58595. this.onSizeChangedObservable = new BABYLON.Observable();
  58596. /**
  58597. * An event triggered when the postprocess applies its effect.
  58598. * @type {BABYLON.Observable}
  58599. */
  58600. this.onApplyObservable = new BABYLON.Observable();
  58601. /**
  58602. * An event triggered before rendering the postprocess
  58603. * @type {BABYLON.Observable}
  58604. */
  58605. this.onBeforeRenderObservable = new BABYLON.Observable();
  58606. /**
  58607. * An event triggered after rendering the postprocess
  58608. * @type {BABYLON.Observable}
  58609. */
  58610. this.onAfterRenderObservable = new BABYLON.Observable();
  58611. if (camera != null) {
  58612. this._camera = camera;
  58613. this._scene = camera.getScene();
  58614. camera.attachPostProcess(this);
  58615. this._engine = this._scene.getEngine();
  58616. this._scene.postProcesses.push(this);
  58617. }
  58618. else if (engine) {
  58619. this._engine = engine;
  58620. this._engine.postProcesses.push(this);
  58621. }
  58622. this._options = options;
  58623. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58624. this._reusable = reusable || false;
  58625. this._textureType = textureType;
  58626. this._samplers = samplers || [];
  58627. this._samplers.push("textureSampler");
  58628. this._fragmentUrl = fragmentUrl;
  58629. this._vertexUrl = vertexUrl;
  58630. this._parameters = parameters || [];
  58631. this._parameters.push("scale");
  58632. this._indexParameters = indexParameters;
  58633. if (!blockCompilation) {
  58634. this.updateEffect(defines);
  58635. }
  58636. }
  58637. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58638. /**
  58639. * A function that is added to the onActivateObservable
  58640. */
  58641. set: function (callback) {
  58642. if (this._onActivateObserver) {
  58643. this.onActivateObservable.remove(this._onActivateObserver);
  58644. }
  58645. if (callback) {
  58646. this._onActivateObserver = this.onActivateObservable.add(callback);
  58647. }
  58648. },
  58649. enumerable: true,
  58650. configurable: true
  58651. });
  58652. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58653. /**
  58654. * A function that is added to the onSizeChangedObservable
  58655. */
  58656. set: function (callback) {
  58657. if (this._onSizeChangedObserver) {
  58658. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58659. }
  58660. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58661. },
  58662. enumerable: true,
  58663. configurable: true
  58664. });
  58665. Object.defineProperty(PostProcess.prototype, "onApply", {
  58666. /**
  58667. * A function that is added to the onApplyObservable
  58668. */
  58669. set: function (callback) {
  58670. if (this._onApplyObserver) {
  58671. this.onApplyObservable.remove(this._onApplyObserver);
  58672. }
  58673. this._onApplyObserver = this.onApplyObservable.add(callback);
  58674. },
  58675. enumerable: true,
  58676. configurable: true
  58677. });
  58678. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58679. /**
  58680. * A function that is added to the onBeforeRenderObservable
  58681. */
  58682. set: function (callback) {
  58683. if (this._onBeforeRenderObserver) {
  58684. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58685. }
  58686. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58687. },
  58688. enumerable: true,
  58689. configurable: true
  58690. });
  58691. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58692. /**
  58693. * A function that is added to the onAfterRenderObservable
  58694. */
  58695. set: function (callback) {
  58696. if (this._onAfterRenderObserver) {
  58697. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58698. }
  58699. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58700. },
  58701. enumerable: true,
  58702. configurable: true
  58703. });
  58704. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58705. /**
  58706. * 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
  58707. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58708. */
  58709. get: function () {
  58710. return this._textures.data[this._currentRenderTextureInd];
  58711. },
  58712. set: function (value) {
  58713. this._forcedOutputTexture = value;
  58714. },
  58715. enumerable: true,
  58716. configurable: true
  58717. });
  58718. /**
  58719. * Gets the camera which post process is applied to.
  58720. * @returns The camera the post process is applied to.
  58721. */
  58722. PostProcess.prototype.getCamera = function () {
  58723. return this._camera;
  58724. };
  58725. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58726. /**
  58727. * Gets the texel size of the postprocess.
  58728. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58729. */
  58730. get: function () {
  58731. if (this._shareOutputWithPostProcess) {
  58732. return this._shareOutputWithPostProcess.texelSize;
  58733. }
  58734. if (this._forcedOutputTexture) {
  58735. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58736. }
  58737. return this._texelSize;
  58738. },
  58739. enumerable: true,
  58740. configurable: true
  58741. });
  58742. /**
  58743. * Gets the engine which this post process belongs to.
  58744. * @returns The engine the post process was enabled with.
  58745. */
  58746. PostProcess.prototype.getEngine = function () {
  58747. return this._engine;
  58748. };
  58749. /**
  58750. * The effect that is created when initializing the post process.
  58751. * @returns The created effect corrisponding the the postprocess.
  58752. */
  58753. PostProcess.prototype.getEffect = function () {
  58754. return this._effect;
  58755. };
  58756. /**
  58757. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58758. * @param postProcess The post process to share the output with.
  58759. * @returns This post process.
  58760. */
  58761. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58762. this._disposeTextures();
  58763. this._shareOutputWithPostProcess = postProcess;
  58764. return this;
  58765. };
  58766. /**
  58767. * Updates the effect with the current post process compile time values and recompiles the shader.
  58768. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58769. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58770. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58771. * @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
  58772. * @param onCompiled Called when the shader has been compiled.
  58773. * @param onError Called if there is an error when compiling a shader.
  58774. */
  58775. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58776. if (defines === void 0) { defines = null; }
  58777. if (uniforms === void 0) { uniforms = null; }
  58778. if (samplers === void 0) { samplers = null; }
  58779. 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);
  58780. };
  58781. /**
  58782. * The post process is reusable if it can be used multiple times within one frame.
  58783. * @returns If the post process is reusable
  58784. */
  58785. PostProcess.prototype.isReusable = function () {
  58786. return this._reusable;
  58787. };
  58788. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58789. PostProcess.prototype.markTextureDirty = function () {
  58790. this.width = -1;
  58791. };
  58792. /**
  58793. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58794. * 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.
  58795. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58796. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58797. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58798. */
  58799. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58800. var _this = this;
  58801. if (sourceTexture === void 0) { sourceTexture = null; }
  58802. camera = camera || this._camera;
  58803. var scene = camera.getScene();
  58804. var engine = scene.getEngine();
  58805. var maxSize = engine.getCaps().maxTextureSize;
  58806. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58807. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58808. // 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
  58809. var webVRCamera = camera.parent;
  58810. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  58811. requiredWidth /= 2;
  58812. }
  58813. var desiredWidth = (this._options.width || requiredWidth);
  58814. var desiredHeight = this._options.height || requiredHeight;
  58815. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58816. if (this.adaptScaleToCurrentViewport) {
  58817. var currentViewport = engine.currentViewport;
  58818. if (currentViewport) {
  58819. desiredWidth *= currentViewport.width;
  58820. desiredHeight *= currentViewport.height;
  58821. }
  58822. }
  58823. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58824. if (!this._options.width) {
  58825. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58826. }
  58827. if (!this._options.height) {
  58828. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58829. }
  58830. }
  58831. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58832. if (this._textures.length > 0) {
  58833. for (var i = 0; i < this._textures.length; i++) {
  58834. this._engine._releaseTexture(this._textures.data[i]);
  58835. }
  58836. this._textures.reset();
  58837. }
  58838. this.width = desiredWidth;
  58839. this.height = desiredHeight;
  58840. var textureSize = { width: this.width, height: this.height };
  58841. var textureOptions = {
  58842. generateMipMaps: false,
  58843. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58844. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58845. samplingMode: this.renderTargetSamplingMode,
  58846. type: this._textureType
  58847. };
  58848. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58849. if (this._reusable) {
  58850. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58851. }
  58852. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58853. this.onSizeChangedObservable.notifyObservers(this);
  58854. }
  58855. this._textures.forEach(function (texture) {
  58856. if (texture.samples !== _this.samples) {
  58857. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58858. }
  58859. });
  58860. }
  58861. var target;
  58862. if (this._shareOutputWithPostProcess) {
  58863. target = this._shareOutputWithPostProcess.inputTexture;
  58864. }
  58865. else if (this._forcedOutputTexture) {
  58866. target = this._forcedOutputTexture;
  58867. this.width = this._forcedOutputTexture.width;
  58868. this.height = this._forcedOutputTexture.height;
  58869. }
  58870. else {
  58871. target = this.inputTexture;
  58872. }
  58873. // Bind the input of this post process to be used as the output of the previous post process.
  58874. if (this.enablePixelPerfectMode) {
  58875. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58876. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58877. }
  58878. else {
  58879. this._scaleRatio.copyFromFloats(1, 1);
  58880. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58881. }
  58882. this.onActivateObservable.notifyObservers(camera);
  58883. // Clear
  58884. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58885. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58886. }
  58887. if (this._reusable) {
  58888. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58889. }
  58890. };
  58891. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58892. /**
  58893. * If the post process is supported.
  58894. */
  58895. get: function () {
  58896. return this._effect.isSupported;
  58897. },
  58898. enumerable: true,
  58899. configurable: true
  58900. });
  58901. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58902. /**
  58903. * The aspect ratio of the output texture.
  58904. */
  58905. get: function () {
  58906. if (this._shareOutputWithPostProcess) {
  58907. return this._shareOutputWithPostProcess.aspectRatio;
  58908. }
  58909. if (this._forcedOutputTexture) {
  58910. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58911. }
  58912. return this.width / this.height;
  58913. },
  58914. enumerable: true,
  58915. configurable: true
  58916. });
  58917. /**
  58918. * Get a value indicating if the post-process is ready to be used
  58919. * @returns true if the post-process is ready (shader is compiled)
  58920. */
  58921. PostProcess.prototype.isReady = function () {
  58922. return this._effect && this._effect.isReady();
  58923. };
  58924. /**
  58925. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58926. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58927. */
  58928. PostProcess.prototype.apply = function () {
  58929. // Check
  58930. if (!this._effect || !this._effect.isReady())
  58931. return null;
  58932. // States
  58933. this._engine.enableEffect(this._effect);
  58934. this._engine.setState(false);
  58935. this._engine.setDepthBuffer(false);
  58936. this._engine.setDepthWrite(false);
  58937. // Alpha
  58938. this._engine.setAlphaMode(this.alphaMode);
  58939. if (this.alphaConstants) {
  58940. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58941. }
  58942. // Bind the output texture of the preivous post process as the input to this post process.
  58943. var source;
  58944. if (this._shareOutputWithPostProcess) {
  58945. source = this._shareOutputWithPostProcess.inputTexture;
  58946. }
  58947. else if (this._forcedOutputTexture) {
  58948. source = this._forcedOutputTexture;
  58949. }
  58950. else {
  58951. source = this.inputTexture;
  58952. }
  58953. this._effect._bindTexture("textureSampler", source);
  58954. // Parameters
  58955. this._effect.setVector2("scale", this._scaleRatio);
  58956. this.onApplyObservable.notifyObservers(this._effect);
  58957. return this._effect;
  58958. };
  58959. PostProcess.prototype._disposeTextures = function () {
  58960. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58961. return;
  58962. }
  58963. if (this._textures.length > 0) {
  58964. for (var i = 0; i < this._textures.length; i++) {
  58965. this._engine._releaseTexture(this._textures.data[i]);
  58966. }
  58967. }
  58968. this._textures.dispose();
  58969. };
  58970. /**
  58971. * Disposes the post process.
  58972. * @param camera The camera to dispose the post process on.
  58973. */
  58974. PostProcess.prototype.dispose = function (camera) {
  58975. camera = camera || this._camera;
  58976. this._disposeTextures();
  58977. if (this._scene) {
  58978. var index_1 = this._scene.postProcesses.indexOf(this);
  58979. if (index_1 !== -1) {
  58980. this._scene.postProcesses.splice(index_1, 1);
  58981. }
  58982. }
  58983. else {
  58984. var index_2 = this._engine.postProcesses.indexOf(this);
  58985. if (index_2 !== -1) {
  58986. this._engine.postProcesses.splice(index_2, 1);
  58987. }
  58988. }
  58989. if (!camera) {
  58990. return;
  58991. }
  58992. camera.detachPostProcess(this);
  58993. var index = camera._postProcesses.indexOf(this);
  58994. if (index === 0 && camera._postProcesses.length > 0) {
  58995. this._camera._postProcesses[0].markTextureDirty();
  58996. }
  58997. this.onActivateObservable.clear();
  58998. this.onAfterRenderObservable.clear();
  58999. this.onApplyObservable.clear();
  59000. this.onBeforeRenderObservable.clear();
  59001. this.onSizeChangedObservable.clear();
  59002. };
  59003. return PostProcess;
  59004. }());
  59005. BABYLON.PostProcess = PostProcess;
  59006. })(BABYLON || (BABYLON = {}));
  59007. //# sourceMappingURL=babylon.postProcess.js.map
  59008. var BABYLON;
  59009. (function (BABYLON) {
  59010. var PassPostProcess = /** @class */ (function (_super) {
  59011. __extends(PassPostProcess, _super);
  59012. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59013. if (camera === void 0) { camera = null; }
  59014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59015. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59016. }
  59017. return PassPostProcess;
  59018. }(BABYLON.PostProcess));
  59019. BABYLON.PassPostProcess = PassPostProcess;
  59020. })(BABYLON || (BABYLON = {}));
  59021. //# sourceMappingURL=babylon.passPostProcess.js.map
  59022. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59023. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59024. s = arguments[i];
  59025. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59026. t[p] = s[p];
  59027. }
  59028. return t;
  59029. };
  59030. var BABYLON;
  59031. (function (BABYLON) {
  59032. /**
  59033. * Default implementation of @see IShadowGenerator.
  59034. * This is the main object responsible of generating shadows in the framework.
  59035. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59036. */
  59037. var ShadowGenerator = /** @class */ (function () {
  59038. /**
  59039. * Creates a ShadowGenerator object.
  59040. * A ShadowGenerator is the required tool to use the shadows.
  59041. * Each light casting shadows needs to use its own ShadowGenerator.
  59042. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59043. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59044. * @param light The light object generating the shadows.
  59045. * @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.
  59046. */
  59047. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59048. this._bias = 0.00005;
  59049. this._blurBoxOffset = 1;
  59050. this._blurScale = 2;
  59051. this._blurKernel = 1;
  59052. this._useKernelBlur = false;
  59053. this._filter = ShadowGenerator.FILTER_NONE;
  59054. this._darkness = 0;
  59055. this._transparencyShadow = false;
  59056. /**
  59057. * Controls the extent to which the shadows fade out at the edge of the frustum
  59058. * Used only by directionals and spots
  59059. */
  59060. this.frustumEdgeFalloff = 0;
  59061. /**
  59062. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59063. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59064. * It might on the other hand introduce peter panning.
  59065. */
  59066. this.forceBackFacesOnly = false;
  59067. this._lightDirection = BABYLON.Vector3.Zero();
  59068. this._viewMatrix = BABYLON.Matrix.Zero();
  59069. this._projectionMatrix = BABYLON.Matrix.Zero();
  59070. this._transformMatrix = BABYLON.Matrix.Zero();
  59071. this._currentFaceIndex = 0;
  59072. this._currentFaceIndexCache = 0;
  59073. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59074. this._mapSize = mapSize;
  59075. this._light = light;
  59076. this._scene = light.getScene();
  59077. light._shadowGenerator = this;
  59078. // Texture type fallback from float to int if not supported.
  59079. var caps = this._scene.getEngine().getCaps();
  59080. if (!useFullFloatFirst) {
  59081. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59082. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59083. }
  59084. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59085. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59086. }
  59087. else {
  59088. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59089. }
  59090. }
  59091. else {
  59092. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59093. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59094. }
  59095. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59096. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59097. }
  59098. else {
  59099. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59100. }
  59101. }
  59102. this._initializeGenerator();
  59103. }
  59104. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59105. /**
  59106. * Shadow generator mode None: no filtering applied.
  59107. */
  59108. get: function () {
  59109. return ShadowGenerator._FILTER_NONE;
  59110. },
  59111. enumerable: true,
  59112. configurable: true
  59113. });
  59114. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59115. /**
  59116. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59117. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59118. */
  59119. get: function () {
  59120. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59121. },
  59122. enumerable: true,
  59123. configurable: true
  59124. });
  59125. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59126. /**
  59127. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59128. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59129. */
  59130. get: function () {
  59131. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59132. },
  59133. enumerable: true,
  59134. configurable: true
  59135. });
  59136. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59137. /**
  59138. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59139. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59140. */
  59141. get: function () {
  59142. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59148. /**
  59149. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59150. * edge artifacts on steep falloff.
  59151. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59152. */
  59153. get: function () {
  59154. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59155. },
  59156. enumerable: true,
  59157. configurable: true
  59158. });
  59159. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59160. /**
  59161. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59162. * edge artifacts on steep falloff.
  59163. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59164. */
  59165. get: function () {
  59166. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59167. },
  59168. enumerable: true,
  59169. configurable: true
  59170. });
  59171. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59172. /**
  59173. * Gets the bias: offset applied on the depth preventing acnea.
  59174. */
  59175. get: function () {
  59176. return this._bias;
  59177. },
  59178. /**
  59179. * Sets the bias: offset applied on the depth preventing acnea.
  59180. */
  59181. set: function (bias) {
  59182. this._bias = bias;
  59183. },
  59184. enumerable: true,
  59185. configurable: true
  59186. });
  59187. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59188. /**
  59189. * Gets the blur box offset: offset applied during the blur pass.
  59190. * Only usefull if useKernelBlur = false
  59191. */
  59192. get: function () {
  59193. return this._blurBoxOffset;
  59194. },
  59195. /**
  59196. * Sets the blur box offset: offset applied during the blur pass.
  59197. * Only usefull if useKernelBlur = false
  59198. */
  59199. set: function (value) {
  59200. if (this._blurBoxOffset === value) {
  59201. return;
  59202. }
  59203. this._blurBoxOffset = value;
  59204. this._disposeBlurPostProcesses();
  59205. },
  59206. enumerable: true,
  59207. configurable: true
  59208. });
  59209. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59210. /**
  59211. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59212. * 2 means half of the size.
  59213. */
  59214. get: function () {
  59215. return this._blurScale;
  59216. },
  59217. /**
  59218. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59219. * 2 means half of the size.
  59220. */
  59221. set: function (value) {
  59222. if (this._blurScale === value) {
  59223. return;
  59224. }
  59225. this._blurScale = value;
  59226. this._disposeBlurPostProcesses();
  59227. },
  59228. enumerable: true,
  59229. configurable: true
  59230. });
  59231. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59232. /**
  59233. * Gets the blur kernel: kernel size of the blur pass.
  59234. * Only usefull if useKernelBlur = true
  59235. */
  59236. get: function () {
  59237. return this._blurKernel;
  59238. },
  59239. /**
  59240. * Sets the blur kernel: kernel size of the blur pass.
  59241. * Only usefull if useKernelBlur = true
  59242. */
  59243. set: function (value) {
  59244. if (this._blurKernel === value) {
  59245. return;
  59246. }
  59247. this._blurKernel = value;
  59248. this._disposeBlurPostProcesses();
  59249. },
  59250. enumerable: true,
  59251. configurable: true
  59252. });
  59253. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59254. /**
  59255. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59256. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59257. */
  59258. get: function () {
  59259. return this._useKernelBlur;
  59260. },
  59261. /**
  59262. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59263. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59264. */
  59265. set: function (value) {
  59266. if (this._useKernelBlur === value) {
  59267. return;
  59268. }
  59269. this._useKernelBlur = value;
  59270. this._disposeBlurPostProcesses();
  59271. },
  59272. enumerable: true,
  59273. configurable: true
  59274. });
  59275. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59276. /**
  59277. * Gets the depth scale used in ESM mode.
  59278. */
  59279. get: function () {
  59280. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59281. },
  59282. /**
  59283. * Sets the depth scale used in ESM mode.
  59284. * This can override the scale stored on the light.
  59285. */
  59286. set: function (value) {
  59287. this._depthScale = value;
  59288. },
  59289. enumerable: true,
  59290. configurable: true
  59291. });
  59292. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59293. /**
  59294. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59295. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59296. */
  59297. get: function () {
  59298. return this._filter;
  59299. },
  59300. /**
  59301. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59302. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59303. */
  59304. set: function (value) {
  59305. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59306. if (this._light.needCube()) {
  59307. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59308. this.useExponentialShadowMap = true;
  59309. return;
  59310. }
  59311. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59312. this.useCloseExponentialShadowMap = true;
  59313. return;
  59314. }
  59315. }
  59316. if (this._filter === value) {
  59317. return;
  59318. }
  59319. this._filter = value;
  59320. this._disposeBlurPostProcesses();
  59321. this._applyFilterValues();
  59322. this._light._markMeshesAsLightDirty();
  59323. },
  59324. enumerable: true,
  59325. configurable: true
  59326. });
  59327. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59328. /**
  59329. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59330. */
  59331. get: function () {
  59332. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59333. },
  59334. /**
  59335. * Sets the current filter to Poisson Sampling aka PCF.
  59336. */
  59337. set: function (value) {
  59338. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59339. return;
  59340. }
  59341. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59342. },
  59343. enumerable: true,
  59344. configurable: true
  59345. });
  59346. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59347. /**
  59348. * Gets if the current filter is set to VSM.
  59349. * DEPRECATED. Should use useExponentialShadowMap instead.
  59350. */
  59351. get: function () {
  59352. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59353. return this.useExponentialShadowMap;
  59354. },
  59355. /**
  59356. * Sets the current filter is to VSM.
  59357. * DEPRECATED. Should use useExponentialShadowMap instead.
  59358. */
  59359. set: function (value) {
  59360. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59361. this.useExponentialShadowMap = value;
  59362. },
  59363. enumerable: true,
  59364. configurable: true
  59365. });
  59366. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59367. /**
  59368. * Gets if the current filter is set to blurred VSM.
  59369. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59370. */
  59371. get: function () {
  59372. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59373. return this.useBlurExponentialShadowMap;
  59374. },
  59375. /**
  59376. * Sets the current filter is to blurred VSM.
  59377. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59378. */
  59379. set: function (value) {
  59380. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59381. this.useBlurExponentialShadowMap = value;
  59382. },
  59383. enumerable: true,
  59384. configurable: true
  59385. });
  59386. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59387. /**
  59388. * Gets if the current filter is set to ESM.
  59389. */
  59390. get: function () {
  59391. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59392. },
  59393. /**
  59394. * Sets the current filter is to ESM.
  59395. */
  59396. set: function (value) {
  59397. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59398. return;
  59399. }
  59400. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59401. },
  59402. enumerable: true,
  59403. configurable: true
  59404. });
  59405. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59406. /**
  59407. * Gets if the current filter is set to filtered ESM.
  59408. */
  59409. get: function () {
  59410. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59411. },
  59412. /**
  59413. * Gets if the current filter is set to filtered ESM.
  59414. */
  59415. set: function (value) {
  59416. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59417. return;
  59418. }
  59419. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59420. },
  59421. enumerable: true,
  59422. configurable: true
  59423. });
  59424. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59425. /**
  59426. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59427. * exponential to prevent steep falloff artifacts).
  59428. */
  59429. get: function () {
  59430. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59431. },
  59432. /**
  59433. * Sets the current filter to "close ESM" (using the inverse of the
  59434. * exponential to prevent steep falloff artifacts).
  59435. */
  59436. set: function (value) {
  59437. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59438. return;
  59439. }
  59440. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59441. },
  59442. enumerable: true,
  59443. configurable: true
  59444. });
  59445. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59446. /**
  59447. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59448. * exponential to prevent steep falloff artifacts).
  59449. */
  59450. get: function () {
  59451. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59452. },
  59453. /**
  59454. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59455. * exponential to prevent steep falloff artifacts).
  59456. */
  59457. set: function (value) {
  59458. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59459. return;
  59460. }
  59461. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59462. },
  59463. enumerable: true,
  59464. configurable: true
  59465. });
  59466. /**
  59467. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59468. * 0 means strongest and 1 would means no shadow.
  59469. * @returns the darkness.
  59470. */
  59471. ShadowGenerator.prototype.getDarkness = function () {
  59472. return this._darkness;
  59473. };
  59474. /**
  59475. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59476. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59477. * @returns the shadow generator allowing fluent coding.
  59478. */
  59479. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59480. if (darkness >= 1.0)
  59481. this._darkness = 1.0;
  59482. else if (darkness <= 0.0)
  59483. this._darkness = 0.0;
  59484. else
  59485. this._darkness = darkness;
  59486. return this;
  59487. };
  59488. /**
  59489. * Sets the ability to have transparent shadow (boolean).
  59490. * @param transparent True if transparent else False
  59491. * @returns the shadow generator allowing fluent coding
  59492. */
  59493. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59494. this._transparencyShadow = transparent;
  59495. return this;
  59496. };
  59497. /**
  59498. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59499. * @returns The render target texture if present otherwise, null
  59500. */
  59501. ShadowGenerator.prototype.getShadowMap = function () {
  59502. return this._shadowMap;
  59503. };
  59504. /**
  59505. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59506. * @returns The render target texture if the shadow map is present otherwise, null
  59507. */
  59508. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59509. if (this._shadowMap2) {
  59510. return this._shadowMap2;
  59511. }
  59512. return this._shadowMap;
  59513. };
  59514. /**
  59515. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59516. * @param mesh Mesh to add
  59517. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59518. * @returns the Shadow Generator itself
  59519. */
  59520. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59521. if (includeDescendants === void 0) { includeDescendants = true; }
  59522. if (!this._shadowMap) {
  59523. return this;
  59524. }
  59525. if (!this._shadowMap.renderList) {
  59526. this._shadowMap.renderList = [];
  59527. }
  59528. this._shadowMap.renderList.push(mesh);
  59529. if (includeDescendants) {
  59530. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59531. }
  59532. return this;
  59533. var _a;
  59534. };
  59535. /**
  59536. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59537. * @param mesh Mesh to remove
  59538. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59539. * @returns the Shadow Generator itself
  59540. */
  59541. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59542. if (includeDescendants === void 0) { includeDescendants = true; }
  59543. if (!this._shadowMap || !this._shadowMap.renderList) {
  59544. return this;
  59545. }
  59546. var index = this._shadowMap.renderList.indexOf(mesh);
  59547. if (index !== -1) {
  59548. this._shadowMap.renderList.splice(index, 1);
  59549. }
  59550. if (includeDescendants) {
  59551. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59552. var child = _a[_i];
  59553. this.removeShadowCaster(child);
  59554. }
  59555. }
  59556. return this;
  59557. };
  59558. /**
  59559. * Returns the associated light object.
  59560. * @returns the light generating the shadow
  59561. */
  59562. ShadowGenerator.prototype.getLight = function () {
  59563. return this._light;
  59564. };
  59565. ShadowGenerator.prototype._initializeGenerator = function () {
  59566. this._light._markMeshesAsLightDirty();
  59567. this._initializeShadowMap();
  59568. };
  59569. ShadowGenerator.prototype._initializeShadowMap = function () {
  59570. var _this = this;
  59571. // Render target
  59572. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59573. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59574. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59575. this._shadowMap.anisotropicFilteringLevel = 1;
  59576. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59577. this._shadowMap.renderParticles = false;
  59578. this._shadowMap.ignoreCameraViewport = true;
  59579. // Record Face Index before render.
  59580. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59581. _this._currentFaceIndex = faceIndex;
  59582. });
  59583. // Custom render function.
  59584. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59585. // Blur if required afer render.
  59586. this._shadowMap.onAfterUnbindObservable.add(function () {
  59587. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59588. return;
  59589. }
  59590. var shadowMap = _this.getShadowMapForRendering();
  59591. if (shadowMap) {
  59592. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59593. }
  59594. });
  59595. // Clear according to the chosen filter.
  59596. this._shadowMap.onClearObservable.add(function (engine) {
  59597. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59598. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59599. }
  59600. else {
  59601. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59602. }
  59603. });
  59604. };
  59605. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59606. var _this = this;
  59607. var engine = this._scene.getEngine();
  59608. var targetSize = this._mapSize / this.blurScale;
  59609. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59610. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59611. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59612. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59613. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59614. }
  59615. if (this.useKernelBlur) {
  59616. 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);
  59617. this._kernelBlurXPostprocess.width = targetSize;
  59618. this._kernelBlurXPostprocess.height = targetSize;
  59619. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59620. effect.setTexture("textureSampler", _this._shadowMap);
  59621. });
  59622. 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);
  59623. this._kernelBlurXPostprocess.autoClear = false;
  59624. this._kernelBlurYPostprocess.autoClear = false;
  59625. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59626. this._kernelBlurXPostprocess.packedFloat = true;
  59627. this._kernelBlurYPostprocess.packedFloat = true;
  59628. }
  59629. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59630. }
  59631. else {
  59632. 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);
  59633. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59634. effect.setFloat2("screenSize", targetSize, targetSize);
  59635. effect.setTexture("textureSampler", _this._shadowMap);
  59636. });
  59637. this._boxBlurPostprocess.autoClear = false;
  59638. this._blurPostProcesses = [this._boxBlurPostprocess];
  59639. }
  59640. };
  59641. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59642. var index;
  59643. var engine = this._scene.getEngine();
  59644. if (depthOnlySubMeshes.length) {
  59645. engine.setColorWrite(false);
  59646. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59647. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59648. }
  59649. engine.setColorWrite(true);
  59650. }
  59651. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59652. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59653. }
  59654. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59655. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59656. }
  59657. if (this._transparencyShadow) {
  59658. for (index = 0; index < transparentSubMeshes.length; index++) {
  59659. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59660. }
  59661. }
  59662. };
  59663. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59664. var _this = this;
  59665. var mesh = subMesh.getRenderingMesh();
  59666. var scene = this._scene;
  59667. var engine = scene.getEngine();
  59668. var material = subMesh.getMaterial();
  59669. if (!material) {
  59670. return;
  59671. }
  59672. // Culling
  59673. engine.setState(material.backFaceCulling);
  59674. // Managing instances
  59675. var batch = mesh._getInstancesRenderList(subMesh._id);
  59676. if (batch.mustReturn) {
  59677. return;
  59678. }
  59679. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59680. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59681. engine.enableEffect(this._effect);
  59682. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59683. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59684. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59685. this._effect.setVector3("lightPosition", this.getLight().position);
  59686. if (scene.activeCamera) {
  59687. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59688. }
  59689. // Alpha test
  59690. if (material && material.needAlphaTesting()) {
  59691. var alphaTexture = material.getAlphaTestTexture();
  59692. if (alphaTexture) {
  59693. this._effect.setTexture("diffuseSampler", alphaTexture);
  59694. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59695. }
  59696. }
  59697. // Bones
  59698. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59699. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59700. }
  59701. if (this.forceBackFacesOnly) {
  59702. engine.setState(true, 0, false, true);
  59703. }
  59704. // Draw
  59705. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59706. if (this.forceBackFacesOnly) {
  59707. engine.setState(true, 0, false, false);
  59708. }
  59709. }
  59710. else {
  59711. // Need to reset refresh rate of the shadowMap
  59712. if (this._shadowMap) {
  59713. this._shadowMap.resetRefreshCounter();
  59714. }
  59715. }
  59716. };
  59717. ShadowGenerator.prototype._applyFilterValues = function () {
  59718. if (!this._shadowMap) {
  59719. return;
  59720. }
  59721. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59722. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59723. }
  59724. else {
  59725. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59726. }
  59727. };
  59728. /**
  59729. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59730. * @param onCompiled Callback triggered at the and of the effects compilation
  59731. * @param options Sets of optional options forcing the compilation with different modes
  59732. */
  59733. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59734. var _this = this;
  59735. var localOptions = __assign({ useInstances: false }, options);
  59736. var shadowMap = this.getShadowMap();
  59737. if (!shadowMap) {
  59738. if (onCompiled) {
  59739. onCompiled(this);
  59740. }
  59741. return;
  59742. }
  59743. var renderList = shadowMap.renderList;
  59744. if (!renderList) {
  59745. if (onCompiled) {
  59746. onCompiled(this);
  59747. }
  59748. return;
  59749. }
  59750. var subMeshes = new Array();
  59751. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59752. var mesh = renderList_1[_i];
  59753. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59754. }
  59755. if (subMeshes.length === 0) {
  59756. if (onCompiled) {
  59757. onCompiled(this);
  59758. }
  59759. return;
  59760. }
  59761. var currentIndex = 0;
  59762. var checkReady = function () {
  59763. if (!_this._scene || !_this._scene.getEngine()) {
  59764. return;
  59765. }
  59766. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59767. currentIndex++;
  59768. if (currentIndex >= subMeshes.length) {
  59769. if (onCompiled) {
  59770. onCompiled(_this);
  59771. }
  59772. return;
  59773. }
  59774. }
  59775. setTimeout(checkReady, 16);
  59776. };
  59777. checkReady();
  59778. };
  59779. /**
  59780. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59781. * @param options Sets of optional options forcing the compilation with different modes
  59782. * @returns A promise that resolves when the compilation completes
  59783. */
  59784. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59785. var _this = this;
  59786. return new Promise(function (resolve) {
  59787. _this.forceCompilation(function () {
  59788. resolve();
  59789. }, options);
  59790. });
  59791. };
  59792. /**
  59793. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59794. * @param subMesh The submesh we want to render in the shadow map
  59795. * @param useInstances Defines wether will draw in the map using instances
  59796. * @returns true if ready otherwise, false
  59797. */
  59798. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59799. var defines = [];
  59800. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59801. defines.push("#define FLOAT");
  59802. }
  59803. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59804. defines.push("#define ESM");
  59805. }
  59806. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59807. var mesh = subMesh.getMesh();
  59808. var material = subMesh.getMaterial();
  59809. // Alpha test
  59810. if (material && material.needAlphaTesting()) {
  59811. var alphaTexture = material.getAlphaTestTexture();
  59812. if (alphaTexture) {
  59813. defines.push("#define ALPHATEST");
  59814. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59815. attribs.push(BABYLON.VertexBuffer.UVKind);
  59816. defines.push("#define UV1");
  59817. }
  59818. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59819. if (alphaTexture.coordinatesIndex === 1) {
  59820. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59821. defines.push("#define UV2");
  59822. }
  59823. }
  59824. }
  59825. }
  59826. // Bones
  59827. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59828. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59829. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59830. if (mesh.numBoneInfluencers > 4) {
  59831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59833. }
  59834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59835. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59836. }
  59837. else {
  59838. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59839. }
  59840. // Instances
  59841. if (useInstances) {
  59842. defines.push("#define INSTANCES");
  59843. attribs.push("world0");
  59844. attribs.push("world1");
  59845. attribs.push("world2");
  59846. attribs.push("world3");
  59847. }
  59848. // Get correct effect
  59849. var join = defines.join("\n");
  59850. if (this._cachedDefines !== join) {
  59851. this._cachedDefines = join;
  59852. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59853. }
  59854. if (!this._effect.isReady()) {
  59855. return false;
  59856. }
  59857. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59858. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59859. this._initializeBlurRTTAndPostProcesses();
  59860. }
  59861. }
  59862. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59863. return false;
  59864. }
  59865. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59866. return false;
  59867. }
  59868. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59869. return false;
  59870. }
  59871. return true;
  59872. };
  59873. /**
  59874. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59875. * @param defines Defines of the material we want to update
  59876. * @param lightIndex Index of the light in the enabled light list of the material
  59877. */
  59878. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59879. var scene = this._scene;
  59880. var light = this._light;
  59881. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59882. return;
  59883. }
  59884. defines["SHADOW" + lightIndex] = true;
  59885. if (this.usePoissonSampling) {
  59886. defines["SHADOWPCF" + lightIndex] = true;
  59887. }
  59888. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59889. defines["SHADOWESM" + lightIndex] = true;
  59890. }
  59891. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59892. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59893. }
  59894. if (light.needCube()) {
  59895. defines["SHADOWCUBE" + lightIndex] = true;
  59896. }
  59897. };
  59898. /**
  59899. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59900. * defined in the generator but impacting the effect).
  59901. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59902. * @param effect The effect we are binfing the information for
  59903. */
  59904. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59905. var light = this._light;
  59906. var scene = this._scene;
  59907. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59908. return;
  59909. }
  59910. var camera = scene.activeCamera;
  59911. if (!camera) {
  59912. return;
  59913. }
  59914. var shadowMap = this.getShadowMap();
  59915. if (!shadowMap) {
  59916. return;
  59917. }
  59918. if (!light.needCube()) {
  59919. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59920. }
  59921. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59922. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59923. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59924. };
  59925. /**
  59926. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59927. * (eq to shadow prjection matrix * light transform matrix)
  59928. * @returns The transform matrix used to create the shadow map
  59929. */
  59930. ShadowGenerator.prototype.getTransformMatrix = function () {
  59931. var scene = this._scene;
  59932. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59933. return this._transformMatrix;
  59934. }
  59935. this._currentRenderID = scene.getRenderId();
  59936. this._currentFaceIndexCache = this._currentFaceIndex;
  59937. var lightPosition = this._light.position;
  59938. if (this._light.computeTransformedInformation()) {
  59939. lightPosition = this._light.transformedPosition;
  59940. }
  59941. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59942. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59943. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59944. }
  59945. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59946. this._cachedPosition = lightPosition.clone();
  59947. this._cachedDirection = this._lightDirection.clone();
  59948. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59949. var shadowMap = this.getShadowMap();
  59950. if (shadowMap) {
  59951. var renderList = shadowMap.renderList;
  59952. if (renderList) {
  59953. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59954. }
  59955. }
  59956. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59957. }
  59958. return this._transformMatrix;
  59959. };
  59960. /**
  59961. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59962. * Cube and 2D textures for instance.
  59963. */
  59964. ShadowGenerator.prototype.recreateShadowMap = function () {
  59965. var shadowMap = this._shadowMap;
  59966. if (!shadowMap) {
  59967. return;
  59968. }
  59969. // Track render list.
  59970. var renderList = shadowMap.renderList;
  59971. // Clean up existing data.
  59972. this._disposeRTTandPostProcesses();
  59973. // Reinitializes.
  59974. this._initializeGenerator();
  59975. // Reaffect the filter to ensure a correct fallback if necessary.
  59976. this.filter = this.filter;
  59977. // Reaffect the filter.
  59978. this._applyFilterValues();
  59979. // Reaffect Render List.
  59980. this._shadowMap.renderList = renderList;
  59981. };
  59982. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59983. if (this._shadowMap2) {
  59984. this._shadowMap2.dispose();
  59985. this._shadowMap2 = null;
  59986. }
  59987. if (this._boxBlurPostprocess) {
  59988. this._boxBlurPostprocess.dispose();
  59989. this._boxBlurPostprocess = null;
  59990. }
  59991. if (this._kernelBlurXPostprocess) {
  59992. this._kernelBlurXPostprocess.dispose();
  59993. this._kernelBlurXPostprocess = null;
  59994. }
  59995. if (this._kernelBlurYPostprocess) {
  59996. this._kernelBlurYPostprocess.dispose();
  59997. this._kernelBlurYPostprocess = null;
  59998. }
  59999. this._blurPostProcesses = [];
  60000. };
  60001. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60002. if (this._shadowMap) {
  60003. this._shadowMap.dispose();
  60004. this._shadowMap = null;
  60005. }
  60006. this._disposeBlurPostProcesses();
  60007. };
  60008. /**
  60009. * Disposes the ShadowGenerator.
  60010. * Returns nothing.
  60011. */
  60012. ShadowGenerator.prototype.dispose = function () {
  60013. this._disposeRTTandPostProcesses();
  60014. if (this._light) {
  60015. this._light._shadowGenerator = null;
  60016. this._light._markMeshesAsLightDirty();
  60017. }
  60018. };
  60019. /**
  60020. * Serializes the shadow generator setup to a json object.
  60021. * @returns The serialized JSON object
  60022. */
  60023. ShadowGenerator.prototype.serialize = function () {
  60024. var serializationObject = {};
  60025. var shadowMap = this.getShadowMap();
  60026. if (!shadowMap) {
  60027. return serializationObject;
  60028. }
  60029. serializationObject.lightId = this._light.id;
  60030. serializationObject.mapSize = shadowMap.getRenderSize();
  60031. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60032. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60033. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60034. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60035. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60036. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60037. serializationObject.depthScale = this.depthScale;
  60038. serializationObject.darkness = this.getDarkness();
  60039. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60040. serializationObject.blurKernel = this.blurKernel;
  60041. serializationObject.blurScale = this.blurScale;
  60042. serializationObject.useKernelBlur = this.useKernelBlur;
  60043. serializationObject.transparencyShadow = this._transparencyShadow;
  60044. serializationObject.renderList = [];
  60045. if (shadowMap.renderList) {
  60046. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60047. var mesh = shadowMap.renderList[meshIndex];
  60048. serializationObject.renderList.push(mesh.id);
  60049. }
  60050. }
  60051. return serializationObject;
  60052. };
  60053. /**
  60054. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60055. * @param parsedShadowGenerator The JSON object to parse
  60056. * @param scene The scene to create the shadow map for
  60057. * @returns The parsed shadow generator
  60058. */
  60059. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60060. //casting to point light, as light is missing the position attr and typescript complains.
  60061. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60062. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60063. var shadowMap = shadowGenerator.getShadowMap();
  60064. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60065. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60066. meshes.forEach(function (mesh) {
  60067. if (!shadowMap) {
  60068. return;
  60069. }
  60070. if (!shadowMap.renderList) {
  60071. shadowMap.renderList = [];
  60072. }
  60073. shadowMap.renderList.push(mesh);
  60074. });
  60075. }
  60076. if (parsedShadowGenerator.usePoissonSampling) {
  60077. shadowGenerator.usePoissonSampling = true;
  60078. }
  60079. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60080. shadowGenerator.useExponentialShadowMap = true;
  60081. }
  60082. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60083. shadowGenerator.useBlurExponentialShadowMap = true;
  60084. }
  60085. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60086. shadowGenerator.useCloseExponentialShadowMap = true;
  60087. }
  60088. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60089. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60090. }
  60091. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60092. shadowGenerator.useExponentialShadowMap = true;
  60093. }
  60094. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60095. shadowGenerator.useBlurExponentialShadowMap = true;
  60096. }
  60097. if (parsedShadowGenerator.depthScale) {
  60098. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60099. }
  60100. if (parsedShadowGenerator.blurScale) {
  60101. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60102. }
  60103. if (parsedShadowGenerator.blurBoxOffset) {
  60104. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60105. }
  60106. if (parsedShadowGenerator.useKernelBlur) {
  60107. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60108. }
  60109. if (parsedShadowGenerator.blurKernel) {
  60110. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60111. }
  60112. if (parsedShadowGenerator.bias !== undefined) {
  60113. shadowGenerator.bias = parsedShadowGenerator.bias;
  60114. }
  60115. if (parsedShadowGenerator.darkness) {
  60116. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60117. }
  60118. if (parsedShadowGenerator.transparencyShadow) {
  60119. shadowGenerator.setTransparencyShadow(true);
  60120. }
  60121. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60122. return shadowGenerator;
  60123. };
  60124. ShadowGenerator._FILTER_NONE = 0;
  60125. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60126. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60127. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60128. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60129. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60130. return ShadowGenerator;
  60131. }());
  60132. BABYLON.ShadowGenerator = ShadowGenerator;
  60133. })(BABYLON || (BABYLON = {}));
  60134. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60135. var BABYLON;
  60136. (function (BABYLON) {
  60137. var DefaultLoadingScreen = /** @class */ (function () {
  60138. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60139. if (_loadingText === void 0) { _loadingText = ""; }
  60140. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60141. var _this = this;
  60142. this._renderingCanvas = _renderingCanvas;
  60143. this._loadingText = _loadingText;
  60144. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60145. // Resize
  60146. this._resizeLoadingUI = function () {
  60147. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60148. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60149. if (!_this._loadingDiv) {
  60150. return;
  60151. }
  60152. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60153. _this._loadingDiv.style.left = canvasRect.left + "px";
  60154. _this._loadingDiv.style.top = canvasRect.top + "px";
  60155. _this._loadingDiv.style.width = canvasRect.width + "px";
  60156. _this._loadingDiv.style.height = canvasRect.height + "px";
  60157. };
  60158. }
  60159. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60160. if (this._loadingDiv) {
  60161. // Do not add a loading screen if there is already one
  60162. return;
  60163. }
  60164. this._loadingDiv = document.createElement("div");
  60165. this._loadingDiv.id = "babylonjsLoadingDiv";
  60166. this._loadingDiv.style.opacity = "0";
  60167. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60168. this._loadingDiv.style.pointerEvents = "none";
  60169. // Loading text
  60170. this._loadingTextDiv = document.createElement("div");
  60171. this._loadingTextDiv.style.position = "absolute";
  60172. this._loadingTextDiv.style.left = "0";
  60173. this._loadingTextDiv.style.top = "50%";
  60174. this._loadingTextDiv.style.marginTop = "80px";
  60175. this._loadingTextDiv.style.width = "100%";
  60176. this._loadingTextDiv.style.height = "20px";
  60177. this._loadingTextDiv.style.fontFamily = "Arial";
  60178. this._loadingTextDiv.style.fontSize = "14px";
  60179. this._loadingTextDiv.style.color = "white";
  60180. this._loadingTextDiv.style.textAlign = "center";
  60181. this._loadingTextDiv.innerHTML = "Loading";
  60182. this._loadingDiv.appendChild(this._loadingTextDiv);
  60183. //set the predefined text
  60184. this._loadingTextDiv.innerHTML = this._loadingText;
  60185. // Generating keyframes
  60186. var style = document.createElement('style');
  60187. style.type = 'text/css';
  60188. 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 }";
  60189. style.innerHTML = keyFrames;
  60190. document.getElementsByTagName('head')[0].appendChild(style);
  60191. // Loading img
  60192. var imgBack = new Image();
  60193. 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";
  60194. imgBack.style.position = "absolute";
  60195. imgBack.style.left = "50%";
  60196. imgBack.style.top = "50%";
  60197. imgBack.style.marginLeft = "-60px";
  60198. imgBack.style.marginTop = "-60px";
  60199. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60200. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60201. imgBack.style.transformOrigin = "50% 50%";
  60202. imgBack.style.webkitTransformOrigin = "50% 50%";
  60203. this._loadingDiv.appendChild(imgBack);
  60204. this._resizeLoadingUI();
  60205. window.addEventListener("resize", this._resizeLoadingUI);
  60206. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60207. document.body.appendChild(this._loadingDiv);
  60208. this._loadingDiv.style.opacity = "1";
  60209. };
  60210. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60211. var _this = this;
  60212. if (!this._loadingDiv) {
  60213. return;
  60214. }
  60215. var onTransitionEnd = function () {
  60216. if (!_this._loadingDiv) {
  60217. return;
  60218. }
  60219. document.body.removeChild(_this._loadingDiv);
  60220. window.removeEventListener("resize", _this._resizeLoadingUI);
  60221. _this._loadingDiv = null;
  60222. };
  60223. this._loadingDiv.style.opacity = "0";
  60224. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60225. };
  60226. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60227. set: function (text) {
  60228. this._loadingText = text;
  60229. if (this._loadingTextDiv) {
  60230. this._loadingTextDiv.innerHTML = this._loadingText;
  60231. }
  60232. },
  60233. enumerable: true,
  60234. configurable: true
  60235. });
  60236. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60237. get: function () {
  60238. return this._loadingDivBackgroundColor;
  60239. },
  60240. set: function (color) {
  60241. this._loadingDivBackgroundColor = color;
  60242. if (!this._loadingDiv) {
  60243. return;
  60244. }
  60245. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60246. },
  60247. enumerable: true,
  60248. configurable: true
  60249. });
  60250. return DefaultLoadingScreen;
  60251. }());
  60252. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60253. })(BABYLON || (BABYLON = {}));
  60254. //# sourceMappingURL=babylon.loadingScreen.js.map
  60255. var BABYLON;
  60256. (function (BABYLON) {
  60257. var SceneLoaderProgressEvent = /** @class */ (function () {
  60258. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60259. this.lengthComputable = lengthComputable;
  60260. this.loaded = loaded;
  60261. this.total = total;
  60262. }
  60263. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60264. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60265. };
  60266. return SceneLoaderProgressEvent;
  60267. }());
  60268. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60269. var SceneLoader = /** @class */ (function () {
  60270. function SceneLoader() {
  60271. }
  60272. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60273. get: function () {
  60274. return 0;
  60275. },
  60276. enumerable: true,
  60277. configurable: true
  60278. });
  60279. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60280. get: function () {
  60281. return 1;
  60282. },
  60283. enumerable: true,
  60284. configurable: true
  60285. });
  60286. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60287. get: function () {
  60288. return 2;
  60289. },
  60290. enumerable: true,
  60291. configurable: true
  60292. });
  60293. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60294. get: function () {
  60295. return 3;
  60296. },
  60297. enumerable: true,
  60298. configurable: true
  60299. });
  60300. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60301. get: function () {
  60302. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60303. },
  60304. set: function (value) {
  60305. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60306. },
  60307. enumerable: true,
  60308. configurable: true
  60309. });
  60310. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60311. get: function () {
  60312. return SceneLoader._ShowLoadingScreen;
  60313. },
  60314. set: function (value) {
  60315. SceneLoader._ShowLoadingScreen = value;
  60316. },
  60317. enumerable: true,
  60318. configurable: true
  60319. });
  60320. Object.defineProperty(SceneLoader, "loggingLevel", {
  60321. get: function () {
  60322. return SceneLoader._loggingLevel;
  60323. },
  60324. set: function (value) {
  60325. SceneLoader._loggingLevel = value;
  60326. },
  60327. enumerable: true,
  60328. configurable: true
  60329. });
  60330. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60331. get: function () {
  60332. return SceneLoader._CleanBoneMatrixWeights;
  60333. },
  60334. set: function (value) {
  60335. SceneLoader._CleanBoneMatrixWeights = value;
  60336. },
  60337. enumerable: true,
  60338. configurable: true
  60339. });
  60340. SceneLoader._getDefaultPlugin = function () {
  60341. return SceneLoader._registeredPlugins[".babylon"];
  60342. };
  60343. SceneLoader._getPluginForExtension = function (extension) {
  60344. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60345. if (registeredPlugin) {
  60346. return registeredPlugin;
  60347. }
  60348. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60349. return SceneLoader._getDefaultPlugin();
  60350. };
  60351. SceneLoader._getPluginForDirectLoad = function (data) {
  60352. for (var extension in SceneLoader._registeredPlugins) {
  60353. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60354. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60355. return SceneLoader._registeredPlugins[extension];
  60356. }
  60357. }
  60358. return SceneLoader._getDefaultPlugin();
  60359. };
  60360. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60361. if (sceneFilename.name) {
  60362. sceneFilename = sceneFilename.name;
  60363. }
  60364. var queryStringPosition = sceneFilename.indexOf("?");
  60365. if (queryStringPosition !== -1) {
  60366. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60367. }
  60368. var dotPosition = sceneFilename.lastIndexOf(".");
  60369. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60370. return SceneLoader._getPluginForExtension(extension);
  60371. };
  60372. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60373. SceneLoader._getDirectLoad = function (sceneFilename) {
  60374. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60375. return sceneFilename.substr(5);
  60376. }
  60377. return null;
  60378. };
  60379. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60380. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60381. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60382. var plugin;
  60383. if (registeredPlugin.plugin.createPlugin) {
  60384. plugin = registeredPlugin.plugin.createPlugin();
  60385. }
  60386. else {
  60387. plugin = registeredPlugin.plugin;
  60388. }
  60389. var useArrayBuffer = registeredPlugin.isBinary;
  60390. var database;
  60391. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60392. var dataCallback = function (data, responseURL) {
  60393. if (scene.isDisposed) {
  60394. onError("Scene has been disposed");
  60395. return;
  60396. }
  60397. scene.database = database;
  60398. onSuccess(plugin, data, responseURL);
  60399. };
  60400. var request = null;
  60401. var pluginDisposed = false;
  60402. var onDisposeObservable = plugin.onDisposeObservable;
  60403. if (onDisposeObservable) {
  60404. onDisposeObservable.add(function () {
  60405. pluginDisposed = true;
  60406. if (request) {
  60407. request.abort();
  60408. request = null;
  60409. }
  60410. onDispose();
  60411. });
  60412. }
  60413. var manifestChecked = function () {
  60414. if (pluginDisposed) {
  60415. return;
  60416. }
  60417. var url = rootUrl + sceneFilename;
  60418. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60419. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60420. } : undefined, database, useArrayBuffer, function (request, exception) {
  60421. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60422. });
  60423. };
  60424. if (directLoad) {
  60425. dataCallback(directLoad);
  60426. return plugin;
  60427. }
  60428. if (rootUrl.indexOf("file:") === -1) {
  60429. if (scene.getEngine().enableOfflineSupport) {
  60430. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60431. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60432. }
  60433. else {
  60434. manifestChecked();
  60435. }
  60436. }
  60437. else {
  60438. var fileOrString = sceneFilename;
  60439. if (fileOrString.name) {
  60440. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60441. }
  60442. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60443. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60444. }
  60445. else {
  60446. onError("Unable to find file named " + sceneFilename);
  60447. }
  60448. }
  60449. return plugin;
  60450. };
  60451. // Public functions
  60452. SceneLoader.GetPluginForExtension = function (extension) {
  60453. return SceneLoader._getPluginForExtension(extension).plugin;
  60454. };
  60455. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60456. return !!SceneLoader._registeredPlugins[extension];
  60457. };
  60458. SceneLoader.RegisterPlugin = function (plugin) {
  60459. if (typeof plugin.extensions === "string") {
  60460. var extension = plugin.extensions;
  60461. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60462. plugin: plugin,
  60463. isBinary: false
  60464. };
  60465. }
  60466. else {
  60467. var extensions = plugin.extensions;
  60468. Object.keys(extensions).forEach(function (extension) {
  60469. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60470. plugin: plugin,
  60471. isBinary: extensions[extension].isBinary
  60472. };
  60473. });
  60474. }
  60475. };
  60476. /**
  60477. * Import meshes into a scene
  60478. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60479. * @param rootUrl a string that defines the root url for scene and resources
  60480. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60481. * @param scene the instance of BABYLON.Scene to append to
  60482. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60483. * @param onProgress a callback with a progress event for each file being loaded
  60484. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60485. * @param pluginExtension the extension used to determine the plugin
  60486. * @returns The loaded plugin
  60487. */
  60488. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60489. if (onSuccess === void 0) { onSuccess = null; }
  60490. if (onProgress === void 0) { onProgress = null; }
  60491. if (onError === void 0) { onError = null; }
  60492. if (pluginExtension === void 0) { pluginExtension = null; }
  60493. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60494. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60495. return null;
  60496. }
  60497. var loadingToken = {};
  60498. scene._addPendingData(loadingToken);
  60499. var disposeHandler = function () {
  60500. scene._removePendingData(loadingToken);
  60501. };
  60502. var errorHandler = function (message, exception) {
  60503. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60504. if (onError) {
  60505. onError(scene, errorMessage, exception);
  60506. }
  60507. else {
  60508. BABYLON.Tools.Error(errorMessage);
  60509. // should the exception be thrown?
  60510. }
  60511. disposeHandler();
  60512. };
  60513. var progressHandler = onProgress ? function (event) {
  60514. try {
  60515. onProgress(event);
  60516. }
  60517. catch (e) {
  60518. errorHandler("Error in onProgress callback", e);
  60519. }
  60520. } : undefined;
  60521. var successHandler = function (meshes, particleSystems, skeletons) {
  60522. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60523. if (onSuccess) {
  60524. try {
  60525. onSuccess(meshes, particleSystems, skeletons);
  60526. }
  60527. catch (e) {
  60528. errorHandler("Error in onSuccess callback", e);
  60529. }
  60530. }
  60531. scene._removePendingData(loadingToken);
  60532. };
  60533. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60534. if (plugin.rewriteRootURL) {
  60535. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60536. }
  60537. if (sceneFilename === "") {
  60538. if (sceneFilename === "") {
  60539. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60540. }
  60541. }
  60542. if (plugin.importMesh) {
  60543. var syncedPlugin = plugin;
  60544. var meshes = new Array();
  60545. var particleSystems = new Array();
  60546. var skeletons = new Array();
  60547. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60548. return;
  60549. }
  60550. scene.loadingPluginName = plugin.name;
  60551. successHandler(meshes, particleSystems, skeletons);
  60552. }
  60553. else {
  60554. var asyncedPlugin = plugin;
  60555. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60556. scene.loadingPluginName = plugin.name;
  60557. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60558. }).catch(function (error) {
  60559. errorHandler(error.message, error);
  60560. });
  60561. }
  60562. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60563. };
  60564. /**
  60565. * Import meshes into a scene
  60566. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60567. * @param rootUrl a string that defines the root url for scene and resources
  60568. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60569. * @param scene the instance of BABYLON.Scene to append to
  60570. * @param onProgress a callback with a progress event for each file being loaded
  60571. * @param pluginExtension the extension used to determine the plugin
  60572. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60573. */
  60574. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60575. if (onProgress === void 0) { onProgress = null; }
  60576. if (pluginExtension === void 0) { pluginExtension = null; }
  60577. return new Promise(function (resolve, reject) {
  60578. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60579. resolve({
  60580. meshes: meshes,
  60581. particleSystems: particleSystems,
  60582. skeletons: skeletons
  60583. });
  60584. }, onProgress, function (scene, message, exception) {
  60585. reject(exception || new Error(message));
  60586. });
  60587. });
  60588. };
  60589. /**
  60590. * Load a scene
  60591. * @param rootUrl a string that defines the root url for scene and resources
  60592. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60593. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60594. * @param onSuccess a callback with the scene when import succeeds
  60595. * @param onProgress a callback with a progress event for each file being loaded
  60596. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60597. * @param pluginExtension the extension used to determine the plugin
  60598. * @returns The loaded plugin
  60599. */
  60600. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60601. if (onSuccess === void 0) { onSuccess = null; }
  60602. if (onProgress === void 0) { onProgress = null; }
  60603. if (onError === void 0) { onError = null; }
  60604. if (pluginExtension === void 0) { pluginExtension = null; }
  60605. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60606. };
  60607. /**
  60608. * Load a scene
  60609. * @param rootUrl a string that defines the root url for scene and resources
  60610. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60611. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60612. * @param onProgress a callback with a progress event for each file being loaded
  60613. * @param pluginExtension the extension used to determine the plugin
  60614. * @returns The loaded scene
  60615. */
  60616. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60617. if (onProgress === void 0) { onProgress = null; }
  60618. if (pluginExtension === void 0) { pluginExtension = null; }
  60619. return new Promise(function (resolve, reject) {
  60620. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60621. resolve(scene);
  60622. }, onProgress, function (scene, message, exception) {
  60623. reject(exception || new Error(message));
  60624. }, pluginExtension);
  60625. });
  60626. };
  60627. /**
  60628. * Append a scene
  60629. * @param rootUrl a string that defines the root url for scene and resources
  60630. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60631. * @param scene is the instance of BABYLON.Scene to append to
  60632. * @param onSuccess a callback with the scene when import succeeds
  60633. * @param onProgress a callback with a progress event for each file being loaded
  60634. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60635. * @param pluginExtension the extension used to determine the plugin
  60636. * @returns The loaded plugin
  60637. */
  60638. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60639. if (onSuccess === void 0) { onSuccess = null; }
  60640. if (onProgress === void 0) { onProgress = null; }
  60641. if (onError === void 0) { onError = null; }
  60642. if (pluginExtension === void 0) { pluginExtension = null; }
  60643. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60644. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60645. return null;
  60646. }
  60647. if (SceneLoader.ShowLoadingScreen) {
  60648. scene.getEngine().displayLoadingUI();
  60649. }
  60650. var loadingToken = {};
  60651. scene._addPendingData(loadingToken);
  60652. var disposeHandler = function () {
  60653. scene._removePendingData(loadingToken);
  60654. scene.getEngine().hideLoadingUI();
  60655. };
  60656. var errorHandler = function (message, exception) {
  60657. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60658. if (onError) {
  60659. onError(scene, errorMessage, exception);
  60660. }
  60661. else {
  60662. BABYLON.Tools.Error(errorMessage);
  60663. // should the exception be thrown?
  60664. }
  60665. disposeHandler();
  60666. };
  60667. var progressHandler = onProgress ? function (event) {
  60668. try {
  60669. onProgress(event);
  60670. }
  60671. catch (e) {
  60672. errorHandler("Error in onProgress callback", e);
  60673. }
  60674. } : undefined;
  60675. var successHandler = function () {
  60676. if (onSuccess) {
  60677. try {
  60678. onSuccess(scene);
  60679. }
  60680. catch (e) {
  60681. errorHandler("Error in onSuccess callback", e);
  60682. }
  60683. }
  60684. scene._removePendingData(loadingToken);
  60685. };
  60686. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60687. if (sceneFilename === "") {
  60688. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60689. }
  60690. if (plugin.load) {
  60691. var syncedPlugin = plugin;
  60692. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60693. return;
  60694. }
  60695. scene.loadingPluginName = plugin.name;
  60696. successHandler();
  60697. }
  60698. else {
  60699. var asyncedPlugin = plugin;
  60700. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60701. scene.loadingPluginName = plugin.name;
  60702. successHandler();
  60703. }).catch(function (error) {
  60704. errorHandler(error.message, error);
  60705. });
  60706. }
  60707. if (SceneLoader.ShowLoadingScreen) {
  60708. scene.executeWhenReady(function () {
  60709. scene.getEngine().hideLoadingUI();
  60710. });
  60711. }
  60712. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60713. };
  60714. /**
  60715. * Append a scene
  60716. * @param rootUrl a string that defines the root url for scene and resources
  60717. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60718. * @param scene is the instance of BABYLON.Scene to append to
  60719. * @param onProgress a callback with a progress event for each file being loaded
  60720. * @param pluginExtension the extension used to determine the plugin
  60721. * @returns The given scene
  60722. */
  60723. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60724. if (onProgress === void 0) { onProgress = null; }
  60725. if (pluginExtension === void 0) { pluginExtension = null; }
  60726. return new Promise(function (resolve, reject) {
  60727. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60728. resolve(scene);
  60729. }, onProgress, function (scene, message, exception) {
  60730. reject(exception || new Error(message));
  60731. }, pluginExtension);
  60732. });
  60733. };
  60734. /**
  60735. * Load a scene into an asset container
  60736. * @param rootUrl a string that defines the root url for scene and resources
  60737. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60738. * @param scene is the instance of BABYLON.Scene to append to
  60739. * @param onSuccess a callback with the scene when import succeeds
  60740. * @param onProgress a callback with a progress event for each file being loaded
  60741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60742. * @param pluginExtension the extension used to determine the plugin
  60743. * @returns The loaded plugin
  60744. */
  60745. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60746. if (onSuccess === void 0) { onSuccess = null; }
  60747. if (onProgress === void 0) { onProgress = null; }
  60748. if (onError === void 0) { onError = null; }
  60749. if (pluginExtension === void 0) { pluginExtension = null; }
  60750. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60751. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60752. return null;
  60753. }
  60754. var loadingToken = {};
  60755. scene._addPendingData(loadingToken);
  60756. var disposeHandler = function () {
  60757. scene._removePendingData(loadingToken);
  60758. };
  60759. var errorHandler = function (message, exception) {
  60760. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60761. if (onError) {
  60762. onError(scene, errorMessage, exception);
  60763. }
  60764. else {
  60765. BABYLON.Tools.Error(errorMessage);
  60766. // should the exception be thrown?
  60767. }
  60768. disposeHandler();
  60769. };
  60770. var progressHandler = onProgress ? function (event) {
  60771. try {
  60772. onProgress(event);
  60773. }
  60774. catch (e) {
  60775. errorHandler("Error in onProgress callback", e);
  60776. }
  60777. } : undefined;
  60778. var successHandler = function (assets) {
  60779. if (onSuccess) {
  60780. try {
  60781. onSuccess(assets);
  60782. }
  60783. catch (e) {
  60784. errorHandler("Error in onSuccess callback", e);
  60785. }
  60786. }
  60787. scene._removePendingData(loadingToken);
  60788. };
  60789. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60790. if (plugin.loadAssetContainer) {
  60791. var syncedPlugin = plugin;
  60792. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60793. if (!assetContainer) {
  60794. return;
  60795. }
  60796. scene.loadingPluginName = plugin.name;
  60797. successHandler(assetContainer);
  60798. }
  60799. else if (plugin.loadAssetContainerAsync) {
  60800. var asyncedPlugin = plugin;
  60801. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60802. scene.loadingPluginName = plugin.name;
  60803. successHandler(assetContainer);
  60804. }).catch(function (error) {
  60805. errorHandler(error.message, error);
  60806. });
  60807. }
  60808. else {
  60809. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60810. }
  60811. if (SceneLoader.ShowLoadingScreen) {
  60812. scene.executeWhenReady(function () {
  60813. scene.getEngine().hideLoadingUI();
  60814. });
  60815. }
  60816. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60817. };
  60818. /**
  60819. * Load a scene into an asset container
  60820. * @param rootUrl a string that defines the root url for scene and resources
  60821. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60822. * @param scene is the instance of BABYLON.Scene to append to
  60823. * @param onProgress a callback with a progress event for each file being loaded
  60824. * @param pluginExtension the extension used to determine the plugin
  60825. * @returns The loaded asset container
  60826. */
  60827. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60828. if (onProgress === void 0) { onProgress = null; }
  60829. if (pluginExtension === void 0) { pluginExtension = null; }
  60830. return new Promise(function (resolve, reject) {
  60831. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60832. resolve(assetContainer);
  60833. }, onProgress, function (scene, message, exception) {
  60834. reject(exception || new Error(message));
  60835. }, pluginExtension);
  60836. });
  60837. };
  60838. // Flags
  60839. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60840. SceneLoader._ShowLoadingScreen = true;
  60841. SceneLoader._CleanBoneMatrixWeights = false;
  60842. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60843. // Members
  60844. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60845. SceneLoader._registeredPlugins = {};
  60846. return SceneLoader;
  60847. }());
  60848. BABYLON.SceneLoader = SceneLoader;
  60849. ;
  60850. })(BABYLON || (BABYLON = {}));
  60851. //# sourceMappingURL=babylon.sceneLoader.js.map
  60852. var BABYLON;
  60853. (function (BABYLON) {
  60854. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60855. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60856. var parsedMaterial = parsedData.materials[index];
  60857. if (parsedMaterial.id === id) {
  60858. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60859. }
  60860. }
  60861. return null;
  60862. };
  60863. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60864. for (var i in names) {
  60865. if (mesh.name === names[i]) {
  60866. hierarchyIds.push(mesh.id);
  60867. return true;
  60868. }
  60869. }
  60870. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60871. hierarchyIds.push(mesh.id);
  60872. return true;
  60873. }
  60874. return false;
  60875. };
  60876. var logOperation = function (operation, producer) {
  60877. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60878. };
  60879. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60880. if (addToScene === void 0) { addToScene = false; }
  60881. var container = new BABYLON.AssetContainer(scene);
  60882. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60883. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60884. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60885. // and avoid problems with multiple concurrent .babylon loads.
  60886. var log = "importScene has failed JSON parse";
  60887. try {
  60888. var parsedData = JSON.parse(data);
  60889. log = "";
  60890. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60891. var index;
  60892. var cache;
  60893. // Lights
  60894. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60895. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60896. var parsedLight = parsedData.lights[index];
  60897. var light = BABYLON.Light.Parse(parsedLight, scene);
  60898. if (light) {
  60899. container.lights.push(light);
  60900. log += (index === 0 ? "\n\tLights:" : "");
  60901. log += "\n\t\t" + light.toString(fullDetails);
  60902. }
  60903. }
  60904. }
  60905. // Animations
  60906. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60907. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60908. var parsedAnimation = parsedData.animations[index];
  60909. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60910. scene.animations.push(animation);
  60911. container.animations.push(animation);
  60912. log += (index === 0 ? "\n\tAnimations:" : "");
  60913. log += "\n\t\t" + animation.toString(fullDetails);
  60914. }
  60915. }
  60916. // Materials
  60917. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60918. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60919. var parsedMaterial = parsedData.materials[index];
  60920. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60921. container.materials.push(mat);
  60922. log += (index === 0 ? "\n\tMaterials:" : "");
  60923. log += "\n\t\t" + mat.toString(fullDetails);
  60924. }
  60925. }
  60926. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60927. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60928. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60929. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60930. container.multiMaterials.push(mmat);
  60931. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60932. log += "\n\t\t" + mmat.toString(fullDetails);
  60933. }
  60934. }
  60935. // Morph targets
  60936. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60937. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60938. var managerData = _a[_i];
  60939. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60940. }
  60941. }
  60942. // Skeletons
  60943. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60944. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60945. var parsedSkeleton = parsedData.skeletons[index];
  60946. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60947. container.skeletons.push(skeleton);
  60948. log += (index === 0 ? "\n\tSkeletons:" : "");
  60949. log += "\n\t\t" + skeleton.toString(fullDetails);
  60950. }
  60951. }
  60952. // Geometries
  60953. var geometries = parsedData.geometries;
  60954. if (geometries !== undefined && geometries !== null) {
  60955. var addedGeometry = new Array();
  60956. // Boxes
  60957. var boxes = geometries.boxes;
  60958. if (boxes !== undefined && boxes !== null) {
  60959. for (index = 0, cache = boxes.length; index < cache; index++) {
  60960. var parsedBox = boxes[index];
  60961. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60962. }
  60963. }
  60964. // Spheres
  60965. var spheres = geometries.spheres;
  60966. if (spheres !== undefined && spheres !== null) {
  60967. for (index = 0, cache = spheres.length; index < cache; index++) {
  60968. var parsedSphere = spheres[index];
  60969. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60970. }
  60971. }
  60972. // Cylinders
  60973. var cylinders = geometries.cylinders;
  60974. if (cylinders !== undefined && cylinders !== null) {
  60975. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60976. var parsedCylinder = cylinders[index];
  60977. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60978. }
  60979. }
  60980. // Toruses
  60981. var toruses = geometries.toruses;
  60982. if (toruses !== undefined && toruses !== null) {
  60983. for (index = 0, cache = toruses.length; index < cache; index++) {
  60984. var parsedTorus = toruses[index];
  60985. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60986. }
  60987. }
  60988. // Grounds
  60989. var grounds = geometries.grounds;
  60990. if (grounds !== undefined && grounds !== null) {
  60991. for (index = 0, cache = grounds.length; index < cache; index++) {
  60992. var parsedGround = grounds[index];
  60993. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60994. }
  60995. }
  60996. // Planes
  60997. var planes = geometries.planes;
  60998. if (planes !== undefined && planes !== null) {
  60999. for (index = 0, cache = planes.length; index < cache; index++) {
  61000. var parsedPlane = planes[index];
  61001. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61002. }
  61003. }
  61004. // TorusKnots
  61005. var torusKnots = geometries.torusKnots;
  61006. if (torusKnots !== undefined && torusKnots !== null) {
  61007. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61008. var parsedTorusKnot = torusKnots[index];
  61009. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61010. }
  61011. }
  61012. // VertexData
  61013. var vertexData = geometries.vertexData;
  61014. if (vertexData !== undefined && vertexData !== null) {
  61015. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61016. var parsedVertexData = vertexData[index];
  61017. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61018. }
  61019. }
  61020. addedGeometry.forEach(function (g) {
  61021. if (g) {
  61022. container.geometries.push(g);
  61023. }
  61024. });
  61025. }
  61026. // Transform nodes
  61027. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61028. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61029. var parsedTransformNode = parsedData.transformNodes[index];
  61030. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61031. container.transformNodes.push(node);
  61032. }
  61033. }
  61034. // Meshes
  61035. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61036. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61037. var parsedMesh = parsedData.meshes[index];
  61038. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61039. container.meshes.push(mesh);
  61040. log += (index === 0 ? "\n\tMeshes:" : "");
  61041. log += "\n\t\t" + mesh.toString(fullDetails);
  61042. }
  61043. }
  61044. // Cameras
  61045. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61046. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61047. var parsedCamera = parsedData.cameras[index];
  61048. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61049. container.cameras.push(camera);
  61050. log += (index === 0 ? "\n\tCameras:" : "");
  61051. log += "\n\t\t" + camera.toString(fullDetails);
  61052. }
  61053. }
  61054. // Browsing all the graph to connect the dots
  61055. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61056. var camera = scene.cameras[index];
  61057. if (camera._waitingParentId) {
  61058. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61059. camera._waitingParentId = null;
  61060. }
  61061. }
  61062. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61063. var light_1 = scene.lights[index];
  61064. if (light_1 && light_1._waitingParentId) {
  61065. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61066. light_1._waitingParentId = null;
  61067. }
  61068. }
  61069. // Sounds
  61070. // TODO: add sound
  61071. var loadedSounds = [];
  61072. var loadedSound;
  61073. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61074. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61075. var parsedSound = parsedData.sounds[index];
  61076. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61077. if (!parsedSound.url)
  61078. parsedSound.url = parsedSound.name;
  61079. if (!loadedSounds[parsedSound.url]) {
  61080. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61081. loadedSounds[parsedSound.url] = loadedSound;
  61082. container.sounds.push(loadedSound);
  61083. }
  61084. else {
  61085. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61086. }
  61087. }
  61088. else {
  61089. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61090. }
  61091. }
  61092. }
  61093. loadedSounds = [];
  61094. // Connect parents & children and parse actions
  61095. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61096. var transformNode = scene.transformNodes[index];
  61097. if (transformNode._waitingParentId) {
  61098. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61099. transformNode._waitingParentId = null;
  61100. }
  61101. }
  61102. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61103. var mesh = scene.meshes[index];
  61104. if (mesh._waitingParentId) {
  61105. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61106. mesh._waitingParentId = null;
  61107. }
  61108. if (mesh._waitingActions) {
  61109. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61110. mesh._waitingActions = null;
  61111. }
  61112. }
  61113. // freeze world matrix application
  61114. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61115. var currentMesh = scene.meshes[index];
  61116. if (currentMesh._waitingFreezeWorldMatrix) {
  61117. currentMesh.freezeWorldMatrix();
  61118. currentMesh._waitingFreezeWorldMatrix = null;
  61119. }
  61120. else {
  61121. currentMesh.computeWorldMatrix(true);
  61122. }
  61123. }
  61124. // Particles Systems
  61125. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61126. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61127. var parsedParticleSystem = parsedData.particleSystems[index];
  61128. if (parsedParticleSystem.activeParticleCount) {
  61129. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61130. container.particleSystems.push(ps);
  61131. }
  61132. else {
  61133. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61134. container.particleSystems.push(ps);
  61135. }
  61136. }
  61137. }
  61138. // Lens flares
  61139. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61140. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61141. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61142. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61143. container.lensFlareSystems.push(lf);
  61144. }
  61145. }
  61146. // Shadows
  61147. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61148. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61149. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61150. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61151. container.shadowGenerators.push(sg);
  61152. }
  61153. }
  61154. // Lights exclusions / inclusions
  61155. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61156. var light_2 = scene.lights[index];
  61157. // Excluded check
  61158. if (light_2._excludedMeshesIds.length > 0) {
  61159. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61160. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61161. if (excludedMesh) {
  61162. light_2.excludedMeshes.push(excludedMesh);
  61163. }
  61164. }
  61165. light_2._excludedMeshesIds = [];
  61166. }
  61167. // Included check
  61168. if (light_2._includedOnlyMeshesIds.length > 0) {
  61169. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61170. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61171. if (includedOnlyMesh) {
  61172. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61173. }
  61174. }
  61175. light_2._includedOnlyMeshesIds = [];
  61176. }
  61177. }
  61178. // Actions (scene)
  61179. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61180. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61181. }
  61182. if (!addToScene) {
  61183. container.removeAllFromScene();
  61184. }
  61185. }
  61186. catch (err) {
  61187. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61188. if (onError) {
  61189. onError(msg, err);
  61190. }
  61191. else {
  61192. BABYLON.Tools.Log(msg);
  61193. throw err;
  61194. }
  61195. }
  61196. finally {
  61197. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61198. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61199. }
  61200. }
  61201. return container;
  61202. };
  61203. BABYLON.SceneLoader.RegisterPlugin({
  61204. name: "babylon.js",
  61205. extensions: ".babylon",
  61206. canDirectLoad: function (data) {
  61207. if (data.indexOf("babylon") !== -1) {
  61208. return true;
  61209. }
  61210. return false;
  61211. },
  61212. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61213. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61214. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61215. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61216. // and avoid problems with multiple concurrent .babylon loads.
  61217. var log = "importMesh has failed JSON parse";
  61218. try {
  61219. var parsedData = JSON.parse(data);
  61220. log = "";
  61221. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61222. if (!meshesNames) {
  61223. meshesNames = null;
  61224. }
  61225. else if (!Array.isArray(meshesNames)) {
  61226. meshesNames = [meshesNames];
  61227. }
  61228. var hierarchyIds = new Array();
  61229. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61230. var loadedSkeletonsIds = [];
  61231. var loadedMaterialsIds = [];
  61232. var index;
  61233. var cache;
  61234. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61235. var parsedMesh = parsedData.meshes[index];
  61236. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61237. if (meshesNames !== null) {
  61238. // Remove found mesh name from list.
  61239. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61240. }
  61241. //Geometry?
  61242. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61243. //does the file contain geometries?
  61244. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61245. //find the correct geometry and add it to the scene
  61246. var found = false;
  61247. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61248. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61249. return;
  61250. }
  61251. else {
  61252. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61253. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61254. switch (geometryType) {
  61255. case "boxes":
  61256. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61257. break;
  61258. case "spheres":
  61259. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61260. break;
  61261. case "cylinders":
  61262. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61263. break;
  61264. case "toruses":
  61265. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61266. break;
  61267. case "grounds":
  61268. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61269. break;
  61270. case "planes":
  61271. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61272. break;
  61273. case "torusKnots":
  61274. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61275. break;
  61276. case "vertexData":
  61277. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61278. break;
  61279. }
  61280. found = true;
  61281. }
  61282. });
  61283. }
  61284. });
  61285. if (found === false) {
  61286. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61287. }
  61288. }
  61289. }
  61290. // Material ?
  61291. if (parsedMesh.materialId) {
  61292. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61293. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61294. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61295. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61296. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61297. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61298. var subMatId = parsedMultiMaterial.materials[matIndex];
  61299. loadedMaterialsIds.push(subMatId);
  61300. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61301. if (mat) {
  61302. log += "\n\tMaterial " + mat.toString(fullDetails);
  61303. }
  61304. }
  61305. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61306. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61307. if (mmat) {
  61308. materialFound = true;
  61309. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61310. }
  61311. break;
  61312. }
  61313. }
  61314. }
  61315. if (materialFound === false) {
  61316. loadedMaterialsIds.push(parsedMesh.materialId);
  61317. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61318. if (!mat) {
  61319. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61320. }
  61321. else {
  61322. log += "\n\tMaterial " + mat.toString(fullDetails);
  61323. }
  61324. }
  61325. }
  61326. // Skeleton ?
  61327. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61328. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61329. if (skeletonAlreadyLoaded === false) {
  61330. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61331. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61332. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61333. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61334. skeletons.push(skeleton);
  61335. loadedSkeletonsIds.push(parsedSkeleton.id);
  61336. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61337. }
  61338. }
  61339. }
  61340. }
  61341. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61342. meshes.push(mesh);
  61343. log += "\n\tMesh " + mesh.toString(fullDetails);
  61344. }
  61345. }
  61346. // Connecting parents
  61347. var currentMesh;
  61348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61349. currentMesh = scene.meshes[index];
  61350. if (currentMesh._waitingParentId) {
  61351. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61352. currentMesh._waitingParentId = null;
  61353. }
  61354. }
  61355. // freeze and compute world matrix application
  61356. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61357. currentMesh = scene.meshes[index];
  61358. if (currentMesh._waitingFreezeWorldMatrix) {
  61359. currentMesh.freezeWorldMatrix();
  61360. currentMesh._waitingFreezeWorldMatrix = null;
  61361. }
  61362. else {
  61363. currentMesh.computeWorldMatrix(true);
  61364. }
  61365. }
  61366. }
  61367. // Particles
  61368. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61369. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61370. var parsedParticleSystem = parsedData.particleSystems[index];
  61371. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61372. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61373. }
  61374. }
  61375. }
  61376. return true;
  61377. }
  61378. catch (err) {
  61379. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61380. if (onError) {
  61381. onError(msg, err);
  61382. }
  61383. else {
  61384. BABYLON.Tools.Log(msg);
  61385. throw err;
  61386. }
  61387. }
  61388. finally {
  61389. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61390. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61391. }
  61392. }
  61393. return false;
  61394. },
  61395. load: function (scene, data, rootUrl, onError) {
  61396. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61397. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61398. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61399. // and avoid problems with multiple concurrent .babylon loads.
  61400. var log = "importScene has failed JSON parse";
  61401. try {
  61402. var parsedData = JSON.parse(data);
  61403. log = "";
  61404. // Scene
  61405. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61406. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61407. }
  61408. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61409. scene.autoClear = parsedData.autoClear;
  61410. }
  61411. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61412. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61413. }
  61414. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61415. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61416. }
  61417. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61418. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61419. }
  61420. // Fog
  61421. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61422. scene.fogMode = parsedData.fogMode;
  61423. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61424. scene.fogStart = parsedData.fogStart;
  61425. scene.fogEnd = parsedData.fogEnd;
  61426. scene.fogDensity = parsedData.fogDensity;
  61427. log += "\tFog mode for scene: ";
  61428. switch (scene.fogMode) {
  61429. // getters not compiling, so using hardcoded
  61430. case 1:
  61431. log += "exp\n";
  61432. break;
  61433. case 2:
  61434. log += "exp2\n";
  61435. break;
  61436. case 3:
  61437. log += "linear\n";
  61438. break;
  61439. }
  61440. }
  61441. //Physics
  61442. if (parsedData.physicsEnabled) {
  61443. var physicsPlugin;
  61444. if (parsedData.physicsEngine === "cannon") {
  61445. physicsPlugin = new BABYLON.CannonJSPlugin();
  61446. }
  61447. else if (parsedData.physicsEngine === "oimo") {
  61448. physicsPlugin = new BABYLON.OimoJSPlugin();
  61449. }
  61450. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61451. //else - default engine, which is currently oimo
  61452. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61453. scene.enablePhysics(physicsGravity, physicsPlugin);
  61454. }
  61455. // Metadata
  61456. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61457. scene.metadata = parsedData.metadata;
  61458. }
  61459. //collisions, if defined. otherwise, default is true
  61460. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61461. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61462. }
  61463. scene.workerCollisions = !!parsedData.workerCollisions;
  61464. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61465. if (!container) {
  61466. return false;
  61467. }
  61468. if (parsedData.autoAnimate) {
  61469. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61470. }
  61471. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61472. scene.setActiveCameraByID(parsedData.activeCameraID);
  61473. }
  61474. // Environment texture
  61475. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61476. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61477. if (parsedData.createDefaultSkybox === true) {
  61478. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61479. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61480. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61481. }
  61482. }
  61483. // Finish
  61484. return true;
  61485. }
  61486. catch (err) {
  61487. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61488. if (onError) {
  61489. onError(msg, err);
  61490. }
  61491. else {
  61492. BABYLON.Tools.Log(msg);
  61493. throw err;
  61494. }
  61495. }
  61496. finally {
  61497. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61498. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61499. }
  61500. }
  61501. return false;
  61502. },
  61503. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61504. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61505. return container;
  61506. }
  61507. });
  61508. })(BABYLON || (BABYLON = {}));
  61509. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61510. var BABYLON;
  61511. (function (BABYLON) {
  61512. var FilesInput = /** @class */ (function () {
  61513. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61514. this.onProcessFileCallback = function () { return true; };
  61515. this._engine = engine;
  61516. this._currentScene = scene;
  61517. this._sceneLoadedCallback = sceneLoadedCallback;
  61518. this._progressCallback = progressCallback;
  61519. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61520. this._textureLoadingCallback = textureLoadingCallback;
  61521. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61522. this._onReloadCallback = onReloadCallback;
  61523. this._errorCallback = errorCallback;
  61524. }
  61525. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61526. var _this = this;
  61527. if (elementToMonitor) {
  61528. this._elementToMonitor = elementToMonitor;
  61529. this._dragEnterHandler = function (e) { _this.drag(e); };
  61530. this._dragOverHandler = function (e) { _this.drag(e); };
  61531. this._dropHandler = function (e) { _this.drop(e); };
  61532. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61533. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61534. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61535. }
  61536. };
  61537. FilesInput.prototype.dispose = function () {
  61538. if (!this._elementToMonitor) {
  61539. return;
  61540. }
  61541. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61542. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61543. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61544. };
  61545. FilesInput.prototype.renderFunction = function () {
  61546. if (this._additionalRenderLoopLogicCallback) {
  61547. this._additionalRenderLoopLogicCallback();
  61548. }
  61549. if (this._currentScene) {
  61550. if (this._textureLoadingCallback) {
  61551. var remaining = this._currentScene.getWaitingItemsCount();
  61552. if (remaining > 0) {
  61553. this._textureLoadingCallback(remaining);
  61554. }
  61555. }
  61556. this._currentScene.render();
  61557. }
  61558. };
  61559. FilesInput.prototype.drag = function (e) {
  61560. e.stopPropagation();
  61561. e.preventDefault();
  61562. };
  61563. FilesInput.prototype.drop = function (eventDrop) {
  61564. eventDrop.stopPropagation();
  61565. eventDrop.preventDefault();
  61566. this.loadFiles(eventDrop);
  61567. };
  61568. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61569. var _this = this;
  61570. var reader = folder.createReader();
  61571. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61572. reader.readEntries(function (entries) {
  61573. remaining.count += entries.length;
  61574. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61575. var entry = entries_1[_i];
  61576. if (entry.isFile) {
  61577. entry.file(function (file) {
  61578. file.correctName = relativePath + file.name;
  61579. files.push(file);
  61580. if (--remaining.count === 0) {
  61581. callback();
  61582. }
  61583. });
  61584. }
  61585. else if (entry.isDirectory) {
  61586. _this._traverseFolder(entry, files, remaining, callback);
  61587. }
  61588. }
  61589. if (--remaining.count) {
  61590. callback();
  61591. }
  61592. });
  61593. };
  61594. FilesInput.prototype._processFiles = function (files) {
  61595. for (var i = 0; i < files.length; i++) {
  61596. var name = files[i].correctName.toLowerCase();
  61597. var extension = name.split('.').pop();
  61598. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61599. continue;
  61600. }
  61601. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61602. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61603. this._sceneFileToLoad = files[i];
  61604. }
  61605. else {
  61606. FilesInput.FilesToLoad[name] = files[i];
  61607. }
  61608. }
  61609. };
  61610. FilesInput.prototype.loadFiles = function (event) {
  61611. var _this = this;
  61612. if (this._startingProcessingFilesCallback)
  61613. this._startingProcessingFilesCallback();
  61614. // Handling data transfer via drag'n'drop
  61615. if (event && event.dataTransfer && event.dataTransfer.files) {
  61616. this._filesToLoad = event.dataTransfer.files;
  61617. }
  61618. // Handling files from input files
  61619. if (event && event.target && event.target.files) {
  61620. this._filesToLoad = event.target.files;
  61621. }
  61622. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61623. var files_1 = new Array();
  61624. var folders = [];
  61625. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61626. for (var i = 0; i < this._filesToLoad.length; i++) {
  61627. var fileToLoad = this._filesToLoad[i];
  61628. var name_1 = fileToLoad.name.toLowerCase();
  61629. var entry = void 0;
  61630. fileToLoad.correctName = name_1;
  61631. if (items) {
  61632. var item = items[i];
  61633. if (item.getAsEntry) {
  61634. entry = item.getAsEntry();
  61635. }
  61636. else if (item.webkitGetAsEntry) {
  61637. entry = item.webkitGetAsEntry();
  61638. }
  61639. }
  61640. if (!entry) {
  61641. files_1.push(fileToLoad);
  61642. }
  61643. else {
  61644. if (entry.isDirectory) {
  61645. folders.push(entry);
  61646. }
  61647. else {
  61648. files_1.push(fileToLoad);
  61649. }
  61650. }
  61651. }
  61652. if (folders.length === 0) {
  61653. this._processFiles(files_1);
  61654. this._processReload();
  61655. }
  61656. else {
  61657. var remaining = { count: folders.length };
  61658. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61659. var folder = folders_1[_i];
  61660. this._traverseFolder(folder, files_1, remaining, function () {
  61661. _this._processFiles(files_1);
  61662. if (remaining.count === 0) {
  61663. _this._processReload();
  61664. }
  61665. });
  61666. }
  61667. }
  61668. }
  61669. };
  61670. FilesInput.prototype._processReload = function () {
  61671. if (this._onReloadCallback) {
  61672. this._onReloadCallback(this._sceneFileToLoad);
  61673. }
  61674. else {
  61675. this.reload();
  61676. }
  61677. };
  61678. FilesInput.prototype.reload = function () {
  61679. var _this = this;
  61680. // If a scene file has been provided
  61681. if (this._sceneFileToLoad) {
  61682. if (this._currentScene) {
  61683. if (BABYLON.Tools.errorsCount > 0) {
  61684. BABYLON.Tools.ClearLogCache();
  61685. }
  61686. this._engine.stopRenderLoop();
  61687. this._currentScene.dispose();
  61688. }
  61689. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61690. if (_this._progressCallback) {
  61691. _this._progressCallback(progress);
  61692. }
  61693. }).then(function (scene) {
  61694. _this._currentScene = scene;
  61695. if (_this._sceneLoadedCallback) {
  61696. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61697. }
  61698. // Wait for textures and shaders to be ready
  61699. _this._currentScene.executeWhenReady(function () {
  61700. _this._engine.runRenderLoop(function () {
  61701. _this.renderFunction();
  61702. });
  61703. });
  61704. }).catch(function (error) {
  61705. if (_this._errorCallback) {
  61706. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61707. }
  61708. });
  61709. }
  61710. else {
  61711. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61712. }
  61713. };
  61714. FilesInput.FilesToLoad = {};
  61715. return FilesInput;
  61716. }());
  61717. BABYLON.FilesInput = FilesInput;
  61718. })(BABYLON || (BABYLON = {}));
  61719. //# sourceMappingURL=babylon.filesInput.js.map
  61720. var BABYLON;
  61721. (function (BABYLON) {
  61722. /**
  61723. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61724. * The underlying implementation relies on an associative array to ensure the best performances.
  61725. * The value can be anything including 'null' but except 'undefined'
  61726. */
  61727. var StringDictionary = /** @class */ (function () {
  61728. function StringDictionary() {
  61729. this._count = 0;
  61730. this._data = {};
  61731. }
  61732. /**
  61733. * This will clear this dictionary and copy the content from the 'source' one.
  61734. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61735. * @param source the dictionary to take the content from and copy to this dictionary
  61736. */
  61737. StringDictionary.prototype.copyFrom = function (source) {
  61738. var _this = this;
  61739. this.clear();
  61740. source.forEach(function (t, v) { return _this.add(t, v); });
  61741. };
  61742. /**
  61743. * Get a value based from its key
  61744. * @param key the given key to get the matching value from
  61745. * @return the value if found, otherwise undefined is returned
  61746. */
  61747. StringDictionary.prototype.get = function (key) {
  61748. var val = this._data[key];
  61749. if (val !== undefined) {
  61750. return val;
  61751. }
  61752. return undefined;
  61753. };
  61754. /**
  61755. * Get a value from its key or add it if it doesn't exist.
  61756. * This method will ensure you that a given key/data will be present in the dictionary.
  61757. * @param key the given key to get the matching value from
  61758. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61759. * The factory will only be invoked if there's no data for the given key.
  61760. * @return the value corresponding to the key.
  61761. */
  61762. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61763. var val = this.get(key);
  61764. if (val !== undefined) {
  61765. return val;
  61766. }
  61767. val = factory(key);
  61768. if (val) {
  61769. this.add(key, val);
  61770. }
  61771. return val;
  61772. };
  61773. /**
  61774. * Get a value from its key if present in the dictionary otherwise add it
  61775. * @param key the key to get the value from
  61776. * @param val if there's no such key/value pair in the dictionary add it with this value
  61777. * @return the value corresponding to the key
  61778. */
  61779. StringDictionary.prototype.getOrAdd = function (key, val) {
  61780. var curVal = this.get(key);
  61781. if (curVal !== undefined) {
  61782. return curVal;
  61783. }
  61784. this.add(key, val);
  61785. return val;
  61786. };
  61787. /**
  61788. * Check if there's a given key in the dictionary
  61789. * @param key the key to check for
  61790. * @return true if the key is present, false otherwise
  61791. */
  61792. StringDictionary.prototype.contains = function (key) {
  61793. return this._data[key] !== undefined;
  61794. };
  61795. /**
  61796. * Add a new key and its corresponding value
  61797. * @param key the key to add
  61798. * @param value the value corresponding to the key
  61799. * @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
  61800. */
  61801. StringDictionary.prototype.add = function (key, value) {
  61802. if (this._data[key] !== undefined) {
  61803. return false;
  61804. }
  61805. this._data[key] = value;
  61806. ++this._count;
  61807. return true;
  61808. };
  61809. StringDictionary.prototype.set = function (key, value) {
  61810. if (this._data[key] === undefined) {
  61811. return false;
  61812. }
  61813. this._data[key] = value;
  61814. return true;
  61815. };
  61816. /**
  61817. * Get the element of the given key and remove it from the dictionary
  61818. * @param key
  61819. */
  61820. StringDictionary.prototype.getAndRemove = function (key) {
  61821. var val = this.get(key);
  61822. if (val !== undefined) {
  61823. delete this._data[key];
  61824. --this._count;
  61825. return val;
  61826. }
  61827. return null;
  61828. };
  61829. /**
  61830. * Remove a key/value from the dictionary.
  61831. * @param key the key to remove
  61832. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61833. */
  61834. StringDictionary.prototype.remove = function (key) {
  61835. if (this.contains(key)) {
  61836. delete this._data[key];
  61837. --this._count;
  61838. return true;
  61839. }
  61840. return false;
  61841. };
  61842. /**
  61843. * Clear the whole content of the dictionary
  61844. */
  61845. StringDictionary.prototype.clear = function () {
  61846. this._data = {};
  61847. this._count = 0;
  61848. };
  61849. Object.defineProperty(StringDictionary.prototype, "count", {
  61850. get: function () {
  61851. return this._count;
  61852. },
  61853. enumerable: true,
  61854. configurable: true
  61855. });
  61856. /**
  61857. * Execute a callback on each key/val of the dictionary.
  61858. * Note that you can remove any element in this dictionary in the callback implementation
  61859. * @param callback the callback to execute on a given key/value pair
  61860. */
  61861. StringDictionary.prototype.forEach = function (callback) {
  61862. for (var cur in this._data) {
  61863. var val = this._data[cur];
  61864. callback(cur, val);
  61865. }
  61866. };
  61867. /**
  61868. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61869. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61870. * Note that you can remove any element in this dictionary in the callback implementation
  61871. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61872. */
  61873. StringDictionary.prototype.first = function (callback) {
  61874. for (var cur in this._data) {
  61875. var val = this._data[cur];
  61876. var res = callback(cur, val);
  61877. if (res) {
  61878. return res;
  61879. }
  61880. }
  61881. return null;
  61882. };
  61883. return StringDictionary;
  61884. }());
  61885. BABYLON.StringDictionary = StringDictionary;
  61886. })(BABYLON || (BABYLON = {}));
  61887. //# sourceMappingURL=babylon.stringDictionary.js.map
  61888. var BABYLON;
  61889. (function (BABYLON) {
  61890. var Tags = /** @class */ (function () {
  61891. function Tags() {
  61892. }
  61893. Tags.EnableFor = function (obj) {
  61894. obj._tags = obj._tags || {};
  61895. obj.hasTags = function () {
  61896. return Tags.HasTags(obj);
  61897. };
  61898. obj.addTags = function (tagsString) {
  61899. return Tags.AddTagsTo(obj, tagsString);
  61900. };
  61901. obj.removeTags = function (tagsString) {
  61902. return Tags.RemoveTagsFrom(obj, tagsString);
  61903. };
  61904. obj.matchesTagsQuery = function (tagsQuery) {
  61905. return Tags.MatchesQuery(obj, tagsQuery);
  61906. };
  61907. };
  61908. Tags.DisableFor = function (obj) {
  61909. delete obj._tags;
  61910. delete obj.hasTags;
  61911. delete obj.addTags;
  61912. delete obj.removeTags;
  61913. delete obj.matchesTagsQuery;
  61914. };
  61915. Tags.HasTags = function (obj) {
  61916. if (!obj._tags) {
  61917. return false;
  61918. }
  61919. return !BABYLON.Tools.IsEmpty(obj._tags);
  61920. };
  61921. Tags.GetTags = function (obj, asString) {
  61922. if (asString === void 0) { asString = true; }
  61923. if (!obj._tags) {
  61924. return null;
  61925. }
  61926. if (asString) {
  61927. var tagsArray = [];
  61928. for (var tag in obj._tags) {
  61929. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61930. tagsArray.push(tag);
  61931. }
  61932. }
  61933. return tagsArray.join(" ");
  61934. }
  61935. else {
  61936. return obj._tags;
  61937. }
  61938. };
  61939. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61940. // a tag cannot start with '||', '&&', and '!'
  61941. // it cannot contain whitespaces
  61942. Tags.AddTagsTo = function (obj, tagsString) {
  61943. if (!tagsString) {
  61944. return;
  61945. }
  61946. if (typeof tagsString !== "string") {
  61947. return;
  61948. }
  61949. var tags = tagsString.split(" ");
  61950. tags.forEach(function (tag, index, array) {
  61951. Tags._AddTagTo(obj, tag);
  61952. });
  61953. };
  61954. Tags._AddTagTo = function (obj, tag) {
  61955. tag = tag.trim();
  61956. if (tag === "" || tag === "true" || tag === "false") {
  61957. return;
  61958. }
  61959. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61960. return;
  61961. }
  61962. Tags.EnableFor(obj);
  61963. obj._tags[tag] = true;
  61964. };
  61965. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61966. if (!Tags.HasTags(obj)) {
  61967. return;
  61968. }
  61969. var tags = tagsString.split(" ");
  61970. for (var t in tags) {
  61971. Tags._RemoveTagFrom(obj, tags[t]);
  61972. }
  61973. };
  61974. Tags._RemoveTagFrom = function (obj, tag) {
  61975. delete obj._tags[tag];
  61976. };
  61977. Tags.MatchesQuery = function (obj, tagsQuery) {
  61978. if (tagsQuery === undefined) {
  61979. return true;
  61980. }
  61981. if (tagsQuery === "") {
  61982. return Tags.HasTags(obj);
  61983. }
  61984. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61985. };
  61986. return Tags;
  61987. }());
  61988. BABYLON.Tags = Tags;
  61989. })(BABYLON || (BABYLON = {}));
  61990. //# sourceMappingURL=babylon.tags.js.map
  61991. var BABYLON;
  61992. (function (BABYLON) {
  61993. var AndOrNotEvaluator = /** @class */ (function () {
  61994. function AndOrNotEvaluator() {
  61995. }
  61996. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61997. if (!query.match(/\([^\(\)]*\)/g)) {
  61998. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61999. }
  62000. else {
  62001. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62002. // remove parenthesis
  62003. r = r.slice(1, r.length - 1);
  62004. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62005. });
  62006. }
  62007. if (query === "true") {
  62008. return true;
  62009. }
  62010. if (query === "false") {
  62011. return false;
  62012. }
  62013. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62014. };
  62015. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62016. evaluateCallback = evaluateCallback || (function (r) {
  62017. return r === "true" ? true : false;
  62018. });
  62019. var result;
  62020. var or = parenthesisContent.split("||");
  62021. for (var i in or) {
  62022. if (or.hasOwnProperty(i)) {
  62023. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62024. var and = ori.split("&&");
  62025. if (and.length > 1) {
  62026. for (var j = 0; j < and.length; ++j) {
  62027. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62028. if (andj !== "true" && andj !== "false") {
  62029. if (andj[0] === "!") {
  62030. result = !evaluateCallback(andj.substring(1));
  62031. }
  62032. else {
  62033. result = evaluateCallback(andj);
  62034. }
  62035. }
  62036. else {
  62037. result = andj === "true" ? true : false;
  62038. }
  62039. if (!result) {
  62040. ori = "false";
  62041. break;
  62042. }
  62043. }
  62044. }
  62045. if (result || ori === "true") {
  62046. result = true;
  62047. break;
  62048. }
  62049. // result equals false (or undefined)
  62050. if (ori !== "true" && ori !== "false") {
  62051. if (ori[0] === "!") {
  62052. result = !evaluateCallback(ori.substring(1));
  62053. }
  62054. else {
  62055. result = evaluateCallback(ori);
  62056. }
  62057. }
  62058. else {
  62059. result = ori === "true" ? true : false;
  62060. }
  62061. }
  62062. }
  62063. // the whole parenthesis scope is replaced by 'true' or 'false'
  62064. return result ? "true" : "false";
  62065. };
  62066. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62067. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62068. // remove whitespaces
  62069. r = r.replace(/[\s]/g, function () { return ""; });
  62070. return r.length % 2 ? "!" : "";
  62071. });
  62072. booleanString = booleanString.trim();
  62073. if (booleanString === "!true") {
  62074. booleanString = "false";
  62075. }
  62076. else if (booleanString === "!false") {
  62077. booleanString = "true";
  62078. }
  62079. return booleanString;
  62080. };
  62081. return AndOrNotEvaluator;
  62082. }());
  62083. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62084. })(BABYLON || (BABYLON = {}));
  62085. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62086. var BABYLON;
  62087. (function (BABYLON) {
  62088. var Database = /** @class */ (function () {
  62089. function Database(urlToScene, callbackManifestChecked) {
  62090. // Handling various flavors of prefixed version of IndexedDB
  62091. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62092. this.callbackManifestChecked = callbackManifestChecked;
  62093. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62094. this.db = null;
  62095. this._enableSceneOffline = false;
  62096. this._enableTexturesOffline = false;
  62097. this.manifestVersionFound = 0;
  62098. this.mustUpdateRessources = false;
  62099. this.hasReachedQuota = false;
  62100. if (!Database.IDBStorageEnabled) {
  62101. this.callbackManifestChecked(true);
  62102. }
  62103. else {
  62104. this.checkManifestFile();
  62105. }
  62106. }
  62107. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62108. get: function () {
  62109. return this._enableSceneOffline;
  62110. },
  62111. enumerable: true,
  62112. configurable: true
  62113. });
  62114. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62115. get: function () {
  62116. return this._enableTexturesOffline;
  62117. },
  62118. enumerable: true,
  62119. configurable: true
  62120. });
  62121. Database.prototype.checkManifestFile = function () {
  62122. var _this = this;
  62123. var noManifestFile = function () {
  62124. _this._enableSceneOffline = false;
  62125. _this._enableTexturesOffline = false;
  62126. _this.callbackManifestChecked(false);
  62127. };
  62128. var timeStampUsed = false;
  62129. var manifestURL = this.currentSceneUrl + ".manifest";
  62130. var xhr = new XMLHttpRequest();
  62131. if (navigator.onLine) {
  62132. // Adding a timestamp to by-pass browsers' cache
  62133. timeStampUsed = true;
  62134. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62135. }
  62136. xhr.open("GET", manifestURL, true);
  62137. xhr.addEventListener("load", function () {
  62138. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62139. try {
  62140. var manifestFile = JSON.parse(xhr.response);
  62141. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62142. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62143. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62144. _this.manifestVersionFound = manifestFile.version;
  62145. }
  62146. if (_this.callbackManifestChecked) {
  62147. _this.callbackManifestChecked(true);
  62148. }
  62149. }
  62150. catch (ex) {
  62151. noManifestFile();
  62152. }
  62153. }
  62154. else {
  62155. noManifestFile();
  62156. }
  62157. }, false);
  62158. xhr.addEventListener("error", function (event) {
  62159. if (timeStampUsed) {
  62160. timeStampUsed = false;
  62161. // Let's retry without the timeStamp
  62162. // It could fail when coupled with HTML5 Offline API
  62163. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62164. xhr.open("GET", retryManifestURL, true);
  62165. xhr.send();
  62166. }
  62167. else {
  62168. noManifestFile();
  62169. }
  62170. }, false);
  62171. try {
  62172. xhr.send();
  62173. }
  62174. catch (ex) {
  62175. BABYLON.Tools.Error("Error on XHR send request.");
  62176. this.callbackManifestChecked(false);
  62177. }
  62178. };
  62179. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62180. var _this = this;
  62181. var handleError = function () {
  62182. _this.isSupported = false;
  62183. if (errorCallback)
  62184. errorCallback();
  62185. };
  62186. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62187. // Your browser doesn't support IndexedDB
  62188. this.isSupported = false;
  62189. if (errorCallback)
  62190. errorCallback();
  62191. }
  62192. else {
  62193. // If the DB hasn't been opened or created yet
  62194. if (!this.db) {
  62195. this.hasReachedQuota = false;
  62196. this.isSupported = true;
  62197. var request = this.idbFactory.open("babylonjs", 1);
  62198. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62199. request.onerror = function (event) {
  62200. handleError();
  62201. };
  62202. // executes when a version change transaction cannot complete due to other active transactions
  62203. request.onblocked = function (event) {
  62204. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62205. handleError();
  62206. };
  62207. // DB has been opened successfully
  62208. request.onsuccess = function (event) {
  62209. _this.db = request.result;
  62210. successCallback();
  62211. };
  62212. // Initialization of the DB. Creating Scenes & Textures stores
  62213. request.onupgradeneeded = function (event) {
  62214. _this.db = (event.target).result;
  62215. if (_this.db) {
  62216. try {
  62217. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62218. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62219. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62220. }
  62221. catch (ex) {
  62222. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62223. handleError();
  62224. }
  62225. }
  62226. };
  62227. }
  62228. else {
  62229. if (successCallback)
  62230. successCallback();
  62231. }
  62232. }
  62233. };
  62234. Database.prototype.loadImageFromDB = function (url, image) {
  62235. var _this = this;
  62236. var completeURL = Database.ReturnFullUrlLocation(url);
  62237. var saveAndLoadImage = function () {
  62238. if (!_this.hasReachedQuota && _this.db !== null) {
  62239. // the texture is not yet in the DB, let's try to save it
  62240. _this._saveImageIntoDBAsync(completeURL, image);
  62241. }
  62242. else {
  62243. image.src = url;
  62244. }
  62245. };
  62246. if (!this.mustUpdateRessources) {
  62247. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62248. }
  62249. else {
  62250. saveAndLoadImage();
  62251. }
  62252. };
  62253. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62254. if (this.isSupported && this.db !== null) {
  62255. var texture;
  62256. var transaction = this.db.transaction(["textures"]);
  62257. transaction.onabort = function (event) {
  62258. image.src = url;
  62259. };
  62260. transaction.oncomplete = function (event) {
  62261. var blobTextureURL;
  62262. if (texture) {
  62263. var URL = window.URL || window.webkitURL;
  62264. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62265. image.onerror = function () {
  62266. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62267. image.src = url;
  62268. };
  62269. image.src = blobTextureURL;
  62270. }
  62271. else {
  62272. notInDBCallback();
  62273. }
  62274. };
  62275. var getRequest = transaction.objectStore("textures").get(url);
  62276. getRequest.onsuccess = function (event) {
  62277. texture = (event.target).result;
  62278. };
  62279. getRequest.onerror = function (event) {
  62280. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62281. image.src = url;
  62282. };
  62283. }
  62284. else {
  62285. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62286. image.src = url;
  62287. }
  62288. };
  62289. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62290. var _this = this;
  62291. if (this.isSupported) {
  62292. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62293. var generateBlobUrl = function () {
  62294. var blobTextureURL;
  62295. if (blob) {
  62296. var URL = window.URL || window.webkitURL;
  62297. try {
  62298. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62299. }
  62300. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62301. catch (ex) {
  62302. blobTextureURL = URL.createObjectURL(blob);
  62303. }
  62304. }
  62305. if (blobTextureURL) {
  62306. image.src = blobTextureURL;
  62307. }
  62308. };
  62309. if (Database.IsUASupportingBlobStorage) {
  62310. var xhr = new XMLHttpRequest(), blob;
  62311. xhr.open("GET", url, true);
  62312. xhr.responseType = "blob";
  62313. xhr.addEventListener("load", function () {
  62314. if (xhr.status === 200 && _this.db) {
  62315. // Blob as response (XHR2)
  62316. blob = xhr.response;
  62317. var transaction = _this.db.transaction(["textures"], "readwrite");
  62318. // the transaction could abort because of a QuotaExceededError error
  62319. transaction.onabort = function (event) {
  62320. try {
  62321. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62322. var srcElement = (event.srcElement || event.target);
  62323. var error = srcElement.error;
  62324. if (error && error.name === "QuotaExceededError") {
  62325. _this.hasReachedQuota = true;
  62326. }
  62327. }
  62328. catch (ex) { }
  62329. generateBlobUrl();
  62330. };
  62331. transaction.oncomplete = function (event) {
  62332. generateBlobUrl();
  62333. };
  62334. var newTexture = { textureUrl: url, data: blob };
  62335. try {
  62336. // Put the blob into the dabase
  62337. var addRequest = transaction.objectStore("textures").put(newTexture);
  62338. addRequest.onsuccess = function (event) {
  62339. };
  62340. addRequest.onerror = function (event) {
  62341. generateBlobUrl();
  62342. };
  62343. }
  62344. catch (ex) {
  62345. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62346. if (ex.code === 25) {
  62347. Database.IsUASupportingBlobStorage = false;
  62348. }
  62349. image.src = url;
  62350. }
  62351. }
  62352. else {
  62353. image.src = url;
  62354. }
  62355. }, false);
  62356. xhr.addEventListener("error", function (event) {
  62357. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62358. image.src = url;
  62359. }, false);
  62360. xhr.send();
  62361. }
  62362. else {
  62363. image.src = url;
  62364. }
  62365. }
  62366. else {
  62367. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62368. image.src = url;
  62369. }
  62370. };
  62371. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62372. var _this = this;
  62373. var updateVersion = function () {
  62374. // the version is not yet in the DB or we need to update it
  62375. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62376. };
  62377. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62378. };
  62379. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62380. var _this = this;
  62381. if (this.isSupported && this.db) {
  62382. var version;
  62383. try {
  62384. var transaction = this.db.transaction(["versions"]);
  62385. transaction.oncomplete = function (event) {
  62386. if (version) {
  62387. // If the version in the JSON file is > than the version in DB
  62388. if (_this.manifestVersionFound > version.data) {
  62389. _this.mustUpdateRessources = true;
  62390. updateInDBCallback();
  62391. }
  62392. else {
  62393. callback(version.data);
  62394. }
  62395. }
  62396. else {
  62397. _this.mustUpdateRessources = true;
  62398. updateInDBCallback();
  62399. }
  62400. };
  62401. transaction.onabort = function (event) {
  62402. callback(-1);
  62403. };
  62404. var getRequest = transaction.objectStore("versions").get(url);
  62405. getRequest.onsuccess = function (event) {
  62406. version = (event.target).result;
  62407. };
  62408. getRequest.onerror = function (event) {
  62409. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62410. callback(-1);
  62411. };
  62412. }
  62413. catch (ex) {
  62414. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62415. callback(-1);
  62416. }
  62417. }
  62418. else {
  62419. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62420. callback(-1);
  62421. }
  62422. };
  62423. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62424. var _this = this;
  62425. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62426. try {
  62427. // Open a transaction to the database
  62428. var transaction = this.db.transaction(["versions"], "readwrite");
  62429. // the transaction could abort because of a QuotaExceededError error
  62430. transaction.onabort = function (event) {
  62431. try {
  62432. var error = event.srcElement['error'];
  62433. if (error && error.name === "QuotaExceededError") {
  62434. _this.hasReachedQuota = true;
  62435. }
  62436. }
  62437. catch (ex) { }
  62438. callback(-1);
  62439. };
  62440. transaction.oncomplete = function (event) {
  62441. callback(_this.manifestVersionFound);
  62442. };
  62443. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62444. // Put the scene into the database
  62445. var addRequest = transaction.objectStore("versions").put(newVersion);
  62446. addRequest.onsuccess = function (event) {
  62447. };
  62448. addRequest.onerror = function (event) {
  62449. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62450. };
  62451. }
  62452. catch (ex) {
  62453. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62454. callback(-1);
  62455. }
  62456. }
  62457. else {
  62458. callback(-1);
  62459. }
  62460. };
  62461. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62462. var _this = this;
  62463. var completeUrl = Database.ReturnFullUrlLocation(url);
  62464. var saveAndLoadFile = function () {
  62465. // the scene is not yet in the DB, let's try to save it
  62466. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62467. };
  62468. this._checkVersionFromDB(completeUrl, function (version) {
  62469. if (version !== -1) {
  62470. if (!_this.mustUpdateRessources) {
  62471. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62472. }
  62473. else {
  62474. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62475. }
  62476. }
  62477. else {
  62478. if (errorCallback) {
  62479. errorCallback();
  62480. }
  62481. }
  62482. });
  62483. };
  62484. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62485. if (this.isSupported && this.db) {
  62486. var targetStore;
  62487. if (url.indexOf(".babylon") !== -1) {
  62488. targetStore = "scenes";
  62489. }
  62490. else {
  62491. targetStore = "textures";
  62492. }
  62493. var file;
  62494. var transaction = this.db.transaction([targetStore]);
  62495. transaction.oncomplete = function (event) {
  62496. if (file) {
  62497. callback(file.data);
  62498. }
  62499. else {
  62500. notInDBCallback();
  62501. }
  62502. };
  62503. transaction.onabort = function (event) {
  62504. notInDBCallback();
  62505. };
  62506. var getRequest = transaction.objectStore(targetStore).get(url);
  62507. getRequest.onsuccess = function (event) {
  62508. file = (event.target).result;
  62509. };
  62510. getRequest.onerror = function (event) {
  62511. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62512. notInDBCallback();
  62513. };
  62514. }
  62515. else {
  62516. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62517. callback();
  62518. }
  62519. };
  62520. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62521. var _this = this;
  62522. if (this.isSupported) {
  62523. var targetStore;
  62524. if (url.indexOf(".babylon") !== -1) {
  62525. targetStore = "scenes";
  62526. }
  62527. else {
  62528. targetStore = "textures";
  62529. }
  62530. // Create XHR
  62531. var xhr = new XMLHttpRequest();
  62532. var fileData;
  62533. xhr.open("GET", url, true);
  62534. if (useArrayBuffer) {
  62535. xhr.responseType = "arraybuffer";
  62536. }
  62537. if (progressCallback) {
  62538. xhr.onprogress = progressCallback;
  62539. }
  62540. xhr.addEventListener("load", function () {
  62541. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62542. // Blob as response (XHR2)
  62543. //fileData = xhr.responseText;
  62544. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62545. if (!_this.hasReachedQuota && _this.db) {
  62546. // Open a transaction to the database
  62547. var transaction = _this.db.transaction([targetStore], "readwrite");
  62548. // the transaction could abort because of a QuotaExceededError error
  62549. transaction.onabort = function (event) {
  62550. try {
  62551. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62552. var error = event.srcElement['error'];
  62553. if (error && error.name === "QuotaExceededError") {
  62554. _this.hasReachedQuota = true;
  62555. }
  62556. }
  62557. catch (ex) { }
  62558. callback(fileData);
  62559. };
  62560. transaction.oncomplete = function (event) {
  62561. callback(fileData);
  62562. };
  62563. var newFile;
  62564. if (targetStore === "scenes") {
  62565. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62566. }
  62567. else {
  62568. newFile = { textureUrl: url, data: fileData };
  62569. }
  62570. try {
  62571. // Put the scene into the database
  62572. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62573. addRequest.onsuccess = function (event) {
  62574. };
  62575. addRequest.onerror = function (event) {
  62576. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62577. };
  62578. }
  62579. catch (ex) {
  62580. callback(fileData);
  62581. }
  62582. }
  62583. else {
  62584. callback(fileData);
  62585. }
  62586. }
  62587. else {
  62588. callback();
  62589. }
  62590. }, false);
  62591. xhr.addEventListener("error", function (event) {
  62592. BABYLON.Tools.Error("error on XHR request.");
  62593. callback();
  62594. }, false);
  62595. xhr.send();
  62596. }
  62597. else {
  62598. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62599. callback();
  62600. }
  62601. };
  62602. Database.IsUASupportingBlobStorage = true;
  62603. Database.IDBStorageEnabled = true;
  62604. Database.parseURL = function (url) {
  62605. var a = document.createElement('a');
  62606. a.href = url;
  62607. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62608. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62609. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62610. return absLocation;
  62611. };
  62612. Database.ReturnFullUrlLocation = function (url) {
  62613. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62614. return (Database.parseURL(window.location.href) + url);
  62615. }
  62616. else {
  62617. return url;
  62618. }
  62619. };
  62620. return Database;
  62621. }());
  62622. BABYLON.Database = Database;
  62623. })(BABYLON || (BABYLON = {}));
  62624. //# sourceMappingURL=babylon.database.js.map
  62625. var BABYLON;
  62626. (function (BABYLON) {
  62627. var FresnelParameters = /** @class */ (function () {
  62628. function FresnelParameters() {
  62629. this._isEnabled = true;
  62630. this.leftColor = BABYLON.Color3.White();
  62631. this.rightColor = BABYLON.Color3.Black();
  62632. this.bias = 0;
  62633. this.power = 1;
  62634. }
  62635. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62636. get: function () {
  62637. return this._isEnabled;
  62638. },
  62639. set: function (value) {
  62640. if (this._isEnabled === value) {
  62641. return;
  62642. }
  62643. this._isEnabled = value;
  62644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62645. },
  62646. enumerable: true,
  62647. configurable: true
  62648. });
  62649. FresnelParameters.prototype.clone = function () {
  62650. var newFresnelParameters = new FresnelParameters();
  62651. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62652. return newFresnelParameters;
  62653. };
  62654. FresnelParameters.prototype.serialize = function () {
  62655. var serializationObject = {};
  62656. serializationObject.isEnabled = this.isEnabled;
  62657. serializationObject.leftColor = this.leftColor;
  62658. serializationObject.rightColor = this.rightColor;
  62659. serializationObject.bias = this.bias;
  62660. serializationObject.power = this.power;
  62661. return serializationObject;
  62662. };
  62663. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62664. var fresnelParameters = new FresnelParameters();
  62665. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62666. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62667. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62668. fresnelParameters.bias = parsedFresnelParameters.bias;
  62669. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62670. return fresnelParameters;
  62671. };
  62672. return FresnelParameters;
  62673. }());
  62674. BABYLON.FresnelParameters = FresnelParameters;
  62675. })(BABYLON || (BABYLON = {}));
  62676. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62677. var BABYLON;
  62678. (function (BABYLON) {
  62679. var MultiMaterial = /** @class */ (function (_super) {
  62680. __extends(MultiMaterial, _super);
  62681. function MultiMaterial(name, scene) {
  62682. var _this = _super.call(this, name, scene, true) || this;
  62683. scene.multiMaterials.push(_this);
  62684. _this.subMaterials = new Array();
  62685. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62686. return _this;
  62687. }
  62688. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62689. get: function () {
  62690. return this._subMaterials;
  62691. },
  62692. set: function (value) {
  62693. this._subMaterials = value;
  62694. this._hookArray(value);
  62695. },
  62696. enumerable: true,
  62697. configurable: true
  62698. });
  62699. MultiMaterial.prototype._hookArray = function (array) {
  62700. var _this = this;
  62701. var oldPush = array.push;
  62702. array.push = function () {
  62703. var items = [];
  62704. for (var _i = 0; _i < arguments.length; _i++) {
  62705. items[_i] = arguments[_i];
  62706. }
  62707. var result = oldPush.apply(array, items);
  62708. _this._markAllSubMeshesAsTexturesDirty();
  62709. return result;
  62710. };
  62711. var oldSplice = array.splice;
  62712. array.splice = function (index, deleteCount) {
  62713. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62714. _this._markAllSubMeshesAsTexturesDirty();
  62715. return deleted;
  62716. };
  62717. };
  62718. // Properties
  62719. MultiMaterial.prototype.getSubMaterial = function (index) {
  62720. if (index < 0 || index >= this.subMaterials.length) {
  62721. return this.getScene().defaultMaterial;
  62722. }
  62723. return this.subMaterials[index];
  62724. };
  62725. MultiMaterial.prototype.getActiveTextures = function () {
  62726. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62727. if (subMaterial) {
  62728. return subMaterial.getActiveTextures();
  62729. }
  62730. else {
  62731. return [];
  62732. }
  62733. }));
  62734. var _a;
  62735. };
  62736. // Methods
  62737. MultiMaterial.prototype.getClassName = function () {
  62738. return "MultiMaterial";
  62739. };
  62740. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62741. for (var index = 0; index < this.subMaterials.length; index++) {
  62742. var subMaterial = this.subMaterials[index];
  62743. if (subMaterial) {
  62744. if (subMaterial.storeEffectOnSubMeshes) {
  62745. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62746. return false;
  62747. }
  62748. continue;
  62749. }
  62750. if (!subMaterial.isReady(mesh)) {
  62751. return false;
  62752. }
  62753. }
  62754. }
  62755. return true;
  62756. };
  62757. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62758. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62759. for (var index = 0; index < this.subMaterials.length; index++) {
  62760. var subMaterial = null;
  62761. var current = this.subMaterials[index];
  62762. if (cloneChildren && current) {
  62763. subMaterial = current.clone(name + "-" + current.name);
  62764. }
  62765. else {
  62766. subMaterial = this.subMaterials[index];
  62767. }
  62768. newMultiMaterial.subMaterials.push(subMaterial);
  62769. }
  62770. return newMultiMaterial;
  62771. };
  62772. MultiMaterial.prototype.serialize = function () {
  62773. var serializationObject = {};
  62774. serializationObject.name = this.name;
  62775. serializationObject.id = this.id;
  62776. if (BABYLON.Tags) {
  62777. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62778. }
  62779. serializationObject.materials = [];
  62780. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62781. var subMat = this.subMaterials[matIndex];
  62782. if (subMat) {
  62783. serializationObject.materials.push(subMat.id);
  62784. }
  62785. else {
  62786. serializationObject.materials.push(null);
  62787. }
  62788. }
  62789. return serializationObject;
  62790. };
  62791. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62792. var scene = this.getScene();
  62793. if (!scene) {
  62794. return;
  62795. }
  62796. var index = scene.multiMaterials.indexOf(this);
  62797. if (index >= 0) {
  62798. scene.multiMaterials.splice(index, 1);
  62799. }
  62800. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62801. };
  62802. return MultiMaterial;
  62803. }(BABYLON.Material));
  62804. BABYLON.MultiMaterial = MultiMaterial;
  62805. })(BABYLON || (BABYLON = {}));
  62806. //# sourceMappingURL=babylon.multiMaterial.js.map
  62807. var BABYLON;
  62808. (function (BABYLON) {
  62809. var FreeCameraTouchInput = /** @class */ (function () {
  62810. function FreeCameraTouchInput() {
  62811. this._offsetX = null;
  62812. this._offsetY = null;
  62813. this._pointerPressed = new Array();
  62814. this.touchAngularSensibility = 200000.0;
  62815. this.touchMoveSensibility = 250.0;
  62816. }
  62817. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62818. var _this = this;
  62819. var previousPosition = null;
  62820. if (this._pointerInput === undefined) {
  62821. this._onLostFocus = function (evt) {
  62822. _this._offsetX = null;
  62823. _this._offsetY = null;
  62824. };
  62825. this._pointerInput = function (p, s) {
  62826. var evt = p.event;
  62827. if (evt.pointerType === "mouse") {
  62828. return;
  62829. }
  62830. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62831. if (!noPreventDefault) {
  62832. evt.preventDefault();
  62833. }
  62834. _this._pointerPressed.push(evt.pointerId);
  62835. if (_this._pointerPressed.length !== 1) {
  62836. return;
  62837. }
  62838. previousPosition = {
  62839. x: evt.clientX,
  62840. y: evt.clientY
  62841. };
  62842. }
  62843. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62844. if (!noPreventDefault) {
  62845. evt.preventDefault();
  62846. }
  62847. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62848. if (index === -1) {
  62849. return;
  62850. }
  62851. _this._pointerPressed.splice(index, 1);
  62852. if (index != 0) {
  62853. return;
  62854. }
  62855. previousPosition = null;
  62856. _this._offsetX = null;
  62857. _this._offsetY = null;
  62858. }
  62859. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62860. if (!noPreventDefault) {
  62861. evt.preventDefault();
  62862. }
  62863. if (!previousPosition) {
  62864. return;
  62865. }
  62866. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62867. if (index != 0) {
  62868. return;
  62869. }
  62870. _this._offsetX = evt.clientX - previousPosition.x;
  62871. _this._offsetY = -(evt.clientY - previousPosition.y);
  62872. }
  62873. };
  62874. }
  62875. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62876. if (this._onLostFocus) {
  62877. element.addEventListener("blur", this._onLostFocus);
  62878. }
  62879. };
  62880. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62881. if (this._pointerInput && element) {
  62882. if (this._observer) {
  62883. this.camera.getScene().onPointerObservable.remove(this._observer);
  62884. this._observer = null;
  62885. }
  62886. if (this._onLostFocus) {
  62887. element.removeEventListener("blur", this._onLostFocus);
  62888. this._onLostFocus = null;
  62889. }
  62890. this._pointerPressed = [];
  62891. this._offsetX = null;
  62892. this._offsetY = null;
  62893. }
  62894. };
  62895. FreeCameraTouchInput.prototype.checkInputs = function () {
  62896. if (this._offsetX && this._offsetY) {
  62897. var camera = this.camera;
  62898. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62899. if (this._pointerPressed.length > 1) {
  62900. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62901. }
  62902. else {
  62903. var speed = camera._computeLocalCameraSpeed();
  62904. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62905. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62906. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62907. }
  62908. }
  62909. };
  62910. FreeCameraTouchInput.prototype.getClassName = function () {
  62911. return "FreeCameraTouchInput";
  62912. };
  62913. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62914. return "touch";
  62915. };
  62916. __decorate([
  62917. BABYLON.serialize()
  62918. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62919. __decorate([
  62920. BABYLON.serialize()
  62921. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62922. return FreeCameraTouchInput;
  62923. }());
  62924. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62925. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62926. })(BABYLON || (BABYLON = {}));
  62927. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62928. var BABYLON;
  62929. (function (BABYLON) {
  62930. // We're mainly based on the logic defined into the FreeCamera code
  62931. var TouchCamera = /** @class */ (function (_super) {
  62932. __extends(TouchCamera, _super);
  62933. //-- end properties for backward compatibility for inputs
  62934. function TouchCamera(name, position, scene) {
  62935. var _this = _super.call(this, name, position, scene) || this;
  62936. _this.inputs.addTouch();
  62937. _this._setupInputs();
  62938. return _this;
  62939. }
  62940. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62941. //-- Begin properties for backward compatibility for inputs
  62942. get: function () {
  62943. var touch = this.inputs.attached["touch"];
  62944. if (touch)
  62945. return touch.touchAngularSensibility;
  62946. return 0;
  62947. },
  62948. set: function (value) {
  62949. var touch = this.inputs.attached["touch"];
  62950. if (touch)
  62951. touch.touchAngularSensibility = value;
  62952. },
  62953. enumerable: true,
  62954. configurable: true
  62955. });
  62956. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62957. get: function () {
  62958. var touch = this.inputs.attached["touch"];
  62959. if (touch)
  62960. return touch.touchMoveSensibility;
  62961. return 0;
  62962. },
  62963. set: function (value) {
  62964. var touch = this.inputs.attached["touch"];
  62965. if (touch)
  62966. touch.touchMoveSensibility = value;
  62967. },
  62968. enumerable: true,
  62969. configurable: true
  62970. });
  62971. TouchCamera.prototype.getClassName = function () {
  62972. return "TouchCamera";
  62973. };
  62974. TouchCamera.prototype._setupInputs = function () {
  62975. var mouse = this.inputs.attached["mouse"];
  62976. if (mouse) {
  62977. mouse.touchEnabled = false;
  62978. }
  62979. };
  62980. return TouchCamera;
  62981. }(BABYLON.FreeCamera));
  62982. BABYLON.TouchCamera = TouchCamera;
  62983. })(BABYLON || (BABYLON = {}));
  62984. //# sourceMappingURL=babylon.touchCamera.js.map
  62985. var BABYLON;
  62986. (function (BABYLON) {
  62987. var ProceduralTexture = /** @class */ (function (_super) {
  62988. __extends(ProceduralTexture, _super);
  62989. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62990. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62991. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62992. if (isCube === void 0) { isCube = false; }
  62993. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62994. _this.isCube = isCube;
  62995. _this.isEnabled = true;
  62996. _this._currentRefreshId = -1;
  62997. _this._refreshRate = 1;
  62998. _this._vertexBuffers = {};
  62999. _this._uniforms = new Array();
  63000. _this._samplers = new Array();
  63001. _this._textures = {};
  63002. _this._floats = {};
  63003. _this._floatsArrays = {};
  63004. _this._colors3 = {};
  63005. _this._colors4 = {};
  63006. _this._vectors2 = {};
  63007. _this._vectors3 = {};
  63008. _this._matrices = {};
  63009. _this._fallbackTextureUsed = false;
  63010. scene._proceduralTextures.push(_this);
  63011. _this._engine = scene.getEngine();
  63012. _this.name = name;
  63013. _this.isRenderTarget = true;
  63014. _this._size = size;
  63015. _this._generateMipMaps = generateMipMaps;
  63016. _this.setFragment(fragment);
  63017. _this._fallbackTexture = fallbackTexture;
  63018. if (isCube) {
  63019. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63020. _this.setFloat("face", 0);
  63021. }
  63022. else {
  63023. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63024. }
  63025. // VBO
  63026. var vertices = [];
  63027. vertices.push(1, 1);
  63028. vertices.push(-1, 1);
  63029. vertices.push(-1, -1);
  63030. vertices.push(1, -1);
  63031. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63032. _this._createIndexBuffer();
  63033. return _this;
  63034. }
  63035. ProceduralTexture.prototype._createIndexBuffer = function () {
  63036. var engine = this._engine;
  63037. // Indices
  63038. var indices = [];
  63039. indices.push(0);
  63040. indices.push(1);
  63041. indices.push(2);
  63042. indices.push(0);
  63043. indices.push(2);
  63044. indices.push(3);
  63045. this._indexBuffer = engine.createIndexBuffer(indices);
  63046. };
  63047. ProceduralTexture.prototype._rebuild = function () {
  63048. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63049. if (vb) {
  63050. vb._rebuild();
  63051. }
  63052. this._createIndexBuffer();
  63053. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63054. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63055. }
  63056. };
  63057. ProceduralTexture.prototype.reset = function () {
  63058. if (this._effect === undefined) {
  63059. return;
  63060. }
  63061. var engine = this._engine;
  63062. engine._releaseEffect(this._effect);
  63063. };
  63064. ProceduralTexture.prototype.isReady = function () {
  63065. var _this = this;
  63066. var engine = this._engine;
  63067. var shaders;
  63068. if (!this._fragment) {
  63069. return false;
  63070. }
  63071. if (this._fallbackTextureUsed) {
  63072. return true;
  63073. }
  63074. if (this._fragment.fragmentElement !== undefined) {
  63075. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63076. }
  63077. else {
  63078. shaders = { vertex: "procedural", fragment: this._fragment };
  63079. }
  63080. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63081. _this.releaseInternalTexture();
  63082. if (_this._fallbackTexture) {
  63083. _this._texture = _this._fallbackTexture._texture;
  63084. if (_this._texture) {
  63085. _this._texture.incrementReferences();
  63086. }
  63087. }
  63088. _this._fallbackTextureUsed = true;
  63089. });
  63090. return this._effect.isReady();
  63091. };
  63092. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63093. this._currentRefreshId = -1;
  63094. };
  63095. ProceduralTexture.prototype.setFragment = function (fragment) {
  63096. this._fragment = fragment;
  63097. };
  63098. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63099. get: function () {
  63100. return this._refreshRate;
  63101. },
  63102. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63103. set: function (value) {
  63104. this._refreshRate = value;
  63105. this.resetRefreshCounter();
  63106. },
  63107. enumerable: true,
  63108. configurable: true
  63109. });
  63110. ProceduralTexture.prototype._shouldRender = function () {
  63111. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63112. return false;
  63113. }
  63114. if (this._fallbackTextureUsed) {
  63115. return false;
  63116. }
  63117. if (this._currentRefreshId === -1) {
  63118. this._currentRefreshId = 1;
  63119. return true;
  63120. }
  63121. if (this.refreshRate === this._currentRefreshId) {
  63122. this._currentRefreshId = 1;
  63123. return true;
  63124. }
  63125. this._currentRefreshId++;
  63126. return false;
  63127. };
  63128. ProceduralTexture.prototype.getRenderSize = function () {
  63129. return this._size;
  63130. };
  63131. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63132. if (this._fallbackTextureUsed) {
  63133. return;
  63134. }
  63135. this.releaseInternalTexture();
  63136. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63137. };
  63138. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63139. if (this._uniforms.indexOf(uniformName) === -1) {
  63140. this._uniforms.push(uniformName);
  63141. }
  63142. };
  63143. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63144. if (this._samplers.indexOf(name) === -1) {
  63145. this._samplers.push(name);
  63146. }
  63147. this._textures[name] = texture;
  63148. return this;
  63149. };
  63150. ProceduralTexture.prototype.setFloat = function (name, value) {
  63151. this._checkUniform(name);
  63152. this._floats[name] = value;
  63153. return this;
  63154. };
  63155. ProceduralTexture.prototype.setFloats = function (name, value) {
  63156. this._checkUniform(name);
  63157. this._floatsArrays[name] = value;
  63158. return this;
  63159. };
  63160. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63161. this._checkUniform(name);
  63162. this._colors3[name] = value;
  63163. return this;
  63164. };
  63165. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63166. this._checkUniform(name);
  63167. this._colors4[name] = value;
  63168. return this;
  63169. };
  63170. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63171. this._checkUniform(name);
  63172. this._vectors2[name] = value;
  63173. return this;
  63174. };
  63175. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63176. this._checkUniform(name);
  63177. this._vectors3[name] = value;
  63178. return this;
  63179. };
  63180. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63181. this._checkUniform(name);
  63182. this._matrices[name] = value;
  63183. return this;
  63184. };
  63185. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63186. var scene = this.getScene();
  63187. if (!scene) {
  63188. return;
  63189. }
  63190. var engine = this._engine;
  63191. // Render
  63192. engine.enableEffect(this._effect);
  63193. engine.setState(false);
  63194. // Texture
  63195. for (var name in this._textures) {
  63196. this._effect.setTexture(name, this._textures[name]);
  63197. }
  63198. // Float
  63199. for (name in this._floats) {
  63200. this._effect.setFloat(name, this._floats[name]);
  63201. }
  63202. // Floats
  63203. for (name in this._floatsArrays) {
  63204. this._effect.setArray(name, this._floatsArrays[name]);
  63205. }
  63206. // Color3
  63207. for (name in this._colors3) {
  63208. this._effect.setColor3(name, this._colors3[name]);
  63209. }
  63210. // Color4
  63211. for (name in this._colors4) {
  63212. var color = this._colors4[name];
  63213. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63214. }
  63215. // Vector2
  63216. for (name in this._vectors2) {
  63217. this._effect.setVector2(name, this._vectors2[name]);
  63218. }
  63219. // Vector3
  63220. for (name in this._vectors3) {
  63221. this._effect.setVector3(name, this._vectors3[name]);
  63222. }
  63223. // Matrix
  63224. for (name in this._matrices) {
  63225. this._effect.setMatrix(name, this._matrices[name]);
  63226. }
  63227. if (!this._texture) {
  63228. return;
  63229. }
  63230. if (this.isCube) {
  63231. for (var face = 0; face < 6; face++) {
  63232. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63233. // VBOs
  63234. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63235. this._effect.setFloat("face", face);
  63236. // Clear
  63237. engine.clear(scene.clearColor, true, true, true);
  63238. // Draw order
  63239. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63240. // Mipmaps
  63241. if (face === 5) {
  63242. engine.generateMipMapsForCubemap(this._texture);
  63243. }
  63244. }
  63245. }
  63246. else {
  63247. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63248. // VBOs
  63249. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63250. // Clear
  63251. engine.clear(scene.clearColor, true, true, true);
  63252. // Draw order
  63253. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63254. }
  63255. // Unbind
  63256. engine.unBindFramebuffer(this._texture, this.isCube);
  63257. if (this.onGenerated) {
  63258. this.onGenerated();
  63259. }
  63260. };
  63261. ProceduralTexture.prototype.clone = function () {
  63262. var textureSize = this.getSize();
  63263. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63264. // Base texture
  63265. newTexture.hasAlpha = this.hasAlpha;
  63266. newTexture.level = this.level;
  63267. // RenderTarget Texture
  63268. newTexture.coordinatesMode = this.coordinatesMode;
  63269. return newTexture;
  63270. };
  63271. ProceduralTexture.prototype.dispose = function () {
  63272. var scene = this.getScene();
  63273. if (!scene) {
  63274. return;
  63275. }
  63276. var index = scene._proceduralTextures.indexOf(this);
  63277. if (index >= 0) {
  63278. scene._proceduralTextures.splice(index, 1);
  63279. }
  63280. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63281. if (vertexBuffer) {
  63282. vertexBuffer.dispose();
  63283. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63284. }
  63285. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63286. this._indexBuffer = null;
  63287. }
  63288. _super.prototype.dispose.call(this);
  63289. };
  63290. return ProceduralTexture;
  63291. }(BABYLON.Texture));
  63292. BABYLON.ProceduralTexture = ProceduralTexture;
  63293. })(BABYLON || (BABYLON = {}));
  63294. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63295. var BABYLON;
  63296. (function (BABYLON) {
  63297. var CustomProceduralTexture = /** @class */ (function (_super) {
  63298. __extends(CustomProceduralTexture, _super);
  63299. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63300. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63301. _this._animate = true;
  63302. _this._time = 0;
  63303. _this._texturePath = texturePath;
  63304. //Try to load json
  63305. _this.loadJson(texturePath);
  63306. _this.refreshRate = 1;
  63307. return _this;
  63308. }
  63309. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63310. var _this = this;
  63311. var noConfigFile = function () {
  63312. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63313. try {
  63314. _this.setFragment(_this._texturePath);
  63315. }
  63316. catch (ex) {
  63317. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63318. }
  63319. };
  63320. var configFileUrl = jsonUrl + "/config.json";
  63321. var xhr = new XMLHttpRequest();
  63322. xhr.open("GET", configFileUrl, true);
  63323. xhr.addEventListener("load", function () {
  63324. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63325. try {
  63326. _this._config = JSON.parse(xhr.response);
  63327. _this.updateShaderUniforms();
  63328. _this.updateTextures();
  63329. _this.setFragment(_this._texturePath + "/custom");
  63330. _this._animate = _this._config.animate;
  63331. _this.refreshRate = _this._config.refreshrate;
  63332. }
  63333. catch (ex) {
  63334. noConfigFile();
  63335. }
  63336. }
  63337. else {
  63338. noConfigFile();
  63339. }
  63340. }, false);
  63341. xhr.addEventListener("error", function () {
  63342. noConfigFile();
  63343. }, false);
  63344. try {
  63345. xhr.send();
  63346. }
  63347. catch (ex) {
  63348. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63349. }
  63350. };
  63351. CustomProceduralTexture.prototype.isReady = function () {
  63352. if (!_super.prototype.isReady.call(this)) {
  63353. return false;
  63354. }
  63355. for (var name in this._textures) {
  63356. var texture = this._textures[name];
  63357. if (!texture.isReady()) {
  63358. return false;
  63359. }
  63360. }
  63361. return true;
  63362. };
  63363. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63364. var scene = this.getScene();
  63365. if (this._animate && scene) {
  63366. this._time += scene.getAnimationRatio() * 0.03;
  63367. this.updateShaderUniforms();
  63368. }
  63369. _super.prototype.render.call(this, useCameraPostProcess);
  63370. };
  63371. CustomProceduralTexture.prototype.updateTextures = function () {
  63372. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63373. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63374. }
  63375. };
  63376. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63377. if (this._config) {
  63378. for (var j = 0; j < this._config.uniforms.length; j++) {
  63379. var uniform = this._config.uniforms[j];
  63380. switch (uniform.type) {
  63381. case "float":
  63382. this.setFloat(uniform.name, uniform.value);
  63383. break;
  63384. case "color3":
  63385. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63386. break;
  63387. case "color4":
  63388. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63389. break;
  63390. case "vector2":
  63391. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63392. break;
  63393. case "vector3":
  63394. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63395. break;
  63396. }
  63397. }
  63398. }
  63399. this.setFloat("time", this._time);
  63400. };
  63401. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63402. get: function () {
  63403. return this._animate;
  63404. },
  63405. set: function (value) {
  63406. this._animate = value;
  63407. },
  63408. enumerable: true,
  63409. configurable: true
  63410. });
  63411. return CustomProceduralTexture;
  63412. }(BABYLON.ProceduralTexture));
  63413. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63414. })(BABYLON || (BABYLON = {}));
  63415. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63416. var BABYLON;
  63417. (function (BABYLON) {
  63418. var FreeCameraGamepadInput = /** @class */ (function () {
  63419. function FreeCameraGamepadInput() {
  63420. this.gamepadAngularSensibility = 200;
  63421. this.gamepadMoveSensibility = 40;
  63422. // private members
  63423. this._cameraTransform = BABYLON.Matrix.Identity();
  63424. this._deltaTransform = BABYLON.Vector3.Zero();
  63425. this._vector3 = BABYLON.Vector3.Zero();
  63426. this._vector2 = BABYLON.Vector2.Zero();
  63427. }
  63428. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63429. var _this = this;
  63430. var manager = this.camera.getScene().gamepadManager;
  63431. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63432. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63433. // prioritize XBOX gamepads.
  63434. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63435. _this.gamepad = gamepad;
  63436. }
  63437. }
  63438. });
  63439. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63440. if (_this.gamepad === gamepad) {
  63441. _this.gamepad = null;
  63442. }
  63443. });
  63444. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63445. };
  63446. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63447. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63448. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63449. this.gamepad = null;
  63450. };
  63451. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63452. if (this.gamepad && this.gamepad.leftStick) {
  63453. var camera = this.camera;
  63454. var LSValues = this.gamepad.leftStick;
  63455. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63456. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63457. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63458. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63459. var RSValues = this.gamepad.rightStick;
  63460. if (RSValues) {
  63461. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63462. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63463. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63464. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63465. }
  63466. else {
  63467. RSValues = { x: 0, y: 0 };
  63468. }
  63469. if (!camera.rotationQuaternion) {
  63470. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63471. }
  63472. else {
  63473. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63474. }
  63475. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63476. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63477. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63478. camera.cameraDirection.addInPlace(this._deltaTransform);
  63479. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63480. camera.cameraRotation.addInPlace(this._vector2);
  63481. }
  63482. };
  63483. FreeCameraGamepadInput.prototype.getClassName = function () {
  63484. return "FreeCameraGamepadInput";
  63485. };
  63486. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63487. return "gamepad";
  63488. };
  63489. __decorate([
  63490. BABYLON.serialize()
  63491. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63492. __decorate([
  63493. BABYLON.serialize()
  63494. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63495. return FreeCameraGamepadInput;
  63496. }());
  63497. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63498. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63499. })(BABYLON || (BABYLON = {}));
  63500. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63501. var BABYLON;
  63502. (function (BABYLON) {
  63503. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63504. function ArcRotateCameraGamepadInput() {
  63505. this.gamepadRotationSensibility = 80;
  63506. this.gamepadMoveSensibility = 40;
  63507. }
  63508. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63509. var _this = this;
  63510. var manager = this.camera.getScene().gamepadManager;
  63511. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63512. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63513. // prioritize XBOX gamepads.
  63514. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63515. _this.gamepad = gamepad;
  63516. }
  63517. }
  63518. });
  63519. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63520. if (_this.gamepad === gamepad) {
  63521. _this.gamepad = null;
  63522. }
  63523. });
  63524. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63525. };
  63526. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63527. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63528. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63529. this.gamepad = null;
  63530. };
  63531. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63532. if (this.gamepad) {
  63533. var camera = this.camera;
  63534. var RSValues = this.gamepad.rightStick;
  63535. if (RSValues) {
  63536. if (RSValues.x != 0) {
  63537. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63538. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63539. camera.inertialAlphaOffset += normalizedRX;
  63540. }
  63541. }
  63542. if (RSValues.y != 0) {
  63543. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63544. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63545. camera.inertialBetaOffset += normalizedRY;
  63546. }
  63547. }
  63548. }
  63549. var LSValues = this.gamepad.leftStick;
  63550. if (LSValues && LSValues.y != 0) {
  63551. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63552. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63553. this.camera.inertialRadiusOffset -= normalizedLY;
  63554. }
  63555. }
  63556. }
  63557. };
  63558. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63559. return "ArcRotateCameraGamepadInput";
  63560. };
  63561. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63562. return "gamepad";
  63563. };
  63564. __decorate([
  63565. BABYLON.serialize()
  63566. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63567. __decorate([
  63568. BABYLON.serialize()
  63569. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63570. return ArcRotateCameraGamepadInput;
  63571. }());
  63572. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63573. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63574. })(BABYLON || (BABYLON = {}));
  63575. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63576. var BABYLON;
  63577. (function (BABYLON) {
  63578. var GamepadManager = /** @class */ (function () {
  63579. function GamepadManager(_scene) {
  63580. var _this = this;
  63581. this._scene = _scene;
  63582. this._babylonGamepads = [];
  63583. this._oneGamepadConnected = false;
  63584. this._isMonitoring = false;
  63585. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63586. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63587. this._gamepadEventSupported = false;
  63588. }
  63589. else {
  63590. this._gamepadEventSupported = 'GamepadEvent' in window;
  63591. this._gamepadSupport = (navigator.getGamepads ||
  63592. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63593. }
  63594. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63595. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63596. for (var i in _this._babylonGamepads) {
  63597. var gamepad = _this._babylonGamepads[i];
  63598. if (gamepad && gamepad._isConnected) {
  63599. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63600. }
  63601. }
  63602. });
  63603. this._onGamepadConnectedEvent = function (evt) {
  63604. var gamepad = evt.gamepad;
  63605. if (gamepad.index in _this._babylonGamepads) {
  63606. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63607. return;
  63608. }
  63609. }
  63610. var newGamepad;
  63611. if (_this._babylonGamepads[gamepad.index]) {
  63612. newGamepad = _this._babylonGamepads[gamepad.index];
  63613. newGamepad.browserGamepad = gamepad;
  63614. newGamepad._isConnected = true;
  63615. }
  63616. else {
  63617. newGamepad = _this._addNewGamepad(gamepad);
  63618. }
  63619. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63620. _this._startMonitoringGamepads();
  63621. };
  63622. this._onGamepadDisconnectedEvent = function (evt) {
  63623. var gamepad = evt.gamepad;
  63624. // Remove the gamepad from the list of gamepads to monitor.
  63625. for (var i in _this._babylonGamepads) {
  63626. if (_this._babylonGamepads[i].index === gamepad.index) {
  63627. var disconnectedGamepad = _this._babylonGamepads[i];
  63628. disconnectedGamepad._isConnected = false;
  63629. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63630. break;
  63631. }
  63632. }
  63633. };
  63634. if (this._gamepadSupport) {
  63635. //first add already-connected gamepads
  63636. this._updateGamepadObjects();
  63637. if (this._babylonGamepads.length) {
  63638. this._startMonitoringGamepads();
  63639. }
  63640. // Checking if the gamepad connected event is supported (like in Firefox)
  63641. if (this._gamepadEventSupported) {
  63642. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63643. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63644. }
  63645. else {
  63646. this._startMonitoringGamepads();
  63647. }
  63648. }
  63649. }
  63650. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63651. get: function () {
  63652. return this._babylonGamepads;
  63653. },
  63654. enumerable: true,
  63655. configurable: true
  63656. });
  63657. GamepadManager.prototype.getGamepadByType = function (type) {
  63658. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63659. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63660. var gamepad = _a[_i];
  63661. if (gamepad && gamepad.type === type) {
  63662. return gamepad;
  63663. }
  63664. }
  63665. return null;
  63666. };
  63667. GamepadManager.prototype.dispose = function () {
  63668. if (this._gamepadEventSupported) {
  63669. if (this._onGamepadConnectedEvent) {
  63670. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63671. }
  63672. if (this._onGamepadDisconnectedEvent) {
  63673. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63674. }
  63675. this._onGamepadConnectedEvent = null;
  63676. this._onGamepadDisconnectedEvent = null;
  63677. }
  63678. this._babylonGamepads.forEach(function (gamepad) {
  63679. gamepad.dispose();
  63680. });
  63681. this.onGamepadConnectedObservable.clear();
  63682. this.onGamepadDisconnectedObservable.clear();
  63683. this._oneGamepadConnected = false;
  63684. this._stopMonitoringGamepads();
  63685. this._babylonGamepads = [];
  63686. };
  63687. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63688. if (!this._oneGamepadConnected) {
  63689. this._oneGamepadConnected = true;
  63690. }
  63691. var newGamepad;
  63692. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63693. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63694. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63695. }
  63696. else if (gamepad.pose) {
  63697. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63698. }
  63699. else {
  63700. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63701. }
  63702. this._babylonGamepads[newGamepad.index] = newGamepad;
  63703. return newGamepad;
  63704. };
  63705. GamepadManager.prototype._startMonitoringGamepads = function () {
  63706. if (!this._isMonitoring) {
  63707. this._isMonitoring = true;
  63708. //back-comp
  63709. if (!this._scene) {
  63710. this._checkGamepadsStatus();
  63711. }
  63712. }
  63713. };
  63714. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63715. this._isMonitoring = false;
  63716. };
  63717. GamepadManager.prototype._checkGamepadsStatus = function () {
  63718. var _this = this;
  63719. // Hack to be compatible Chrome
  63720. this._updateGamepadObjects();
  63721. for (var i in this._babylonGamepads) {
  63722. var gamepad = this._babylonGamepads[i];
  63723. if (!gamepad || !gamepad.isConnected) {
  63724. continue;
  63725. }
  63726. gamepad.update();
  63727. }
  63728. if (this._isMonitoring && !this._scene) {
  63729. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63730. }
  63731. };
  63732. // This function is called only on Chrome, which does not properly support
  63733. // connection/disconnection events and forces you to recopy again the gamepad object
  63734. GamepadManager.prototype._updateGamepadObjects = function () {
  63735. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63736. for (var i = 0; i < gamepads.length; i++) {
  63737. if (gamepads[i]) {
  63738. if (!this._babylonGamepads[gamepads[i].index]) {
  63739. var newGamepad = this._addNewGamepad(gamepads[i]);
  63740. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63741. }
  63742. else {
  63743. // Forced to copy again this object for Chrome for unknown reason
  63744. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63745. if (!this._babylonGamepads[i].isConnected) {
  63746. this._babylonGamepads[i]._isConnected = true;
  63747. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63748. }
  63749. }
  63750. }
  63751. }
  63752. };
  63753. return GamepadManager;
  63754. }());
  63755. BABYLON.GamepadManager = GamepadManager;
  63756. })(BABYLON || (BABYLON = {}));
  63757. //# sourceMappingURL=babylon.gamepadManager.js.map
  63758. var BABYLON;
  63759. (function (BABYLON) {
  63760. var StickValues = /** @class */ (function () {
  63761. function StickValues(x, y) {
  63762. this.x = x;
  63763. this.y = y;
  63764. }
  63765. return StickValues;
  63766. }());
  63767. BABYLON.StickValues = StickValues;
  63768. var Gamepad = /** @class */ (function () {
  63769. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63770. if (leftStickX === void 0) { leftStickX = 0; }
  63771. if (leftStickY === void 0) { leftStickY = 1; }
  63772. if (rightStickX === void 0) { rightStickX = 2; }
  63773. if (rightStickY === void 0) { rightStickY = 3; }
  63774. this.id = id;
  63775. this.index = index;
  63776. this.browserGamepad = browserGamepad;
  63777. this._isConnected = true;
  63778. this._invertLeftStickY = false;
  63779. this.type = Gamepad.GAMEPAD;
  63780. this._leftStickAxisX = leftStickX;
  63781. this._leftStickAxisY = leftStickY;
  63782. this._rightStickAxisX = rightStickX;
  63783. this._rightStickAxisY = rightStickY;
  63784. if (this.browserGamepad.axes.length >= 2) {
  63785. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63786. }
  63787. if (this.browserGamepad.axes.length >= 4) {
  63788. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63789. }
  63790. }
  63791. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63792. get: function () {
  63793. return this._isConnected;
  63794. },
  63795. enumerable: true,
  63796. configurable: true
  63797. });
  63798. Gamepad.prototype.onleftstickchanged = function (callback) {
  63799. this._onleftstickchanged = callback;
  63800. };
  63801. Gamepad.prototype.onrightstickchanged = function (callback) {
  63802. this._onrightstickchanged = callback;
  63803. };
  63804. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63805. get: function () {
  63806. return this._leftStick;
  63807. },
  63808. set: function (newValues) {
  63809. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63810. this._onleftstickchanged(newValues);
  63811. }
  63812. this._leftStick = newValues;
  63813. },
  63814. enumerable: true,
  63815. configurable: true
  63816. });
  63817. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63818. get: function () {
  63819. return this._rightStick;
  63820. },
  63821. set: function (newValues) {
  63822. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63823. this._onrightstickchanged(newValues);
  63824. }
  63825. this._rightStick = newValues;
  63826. },
  63827. enumerable: true,
  63828. configurable: true
  63829. });
  63830. Gamepad.prototype.update = function () {
  63831. if (this._leftStick) {
  63832. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63833. if (this._invertLeftStickY) {
  63834. this.leftStick.y *= -1;
  63835. }
  63836. }
  63837. if (this._rightStick) {
  63838. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63839. }
  63840. };
  63841. Gamepad.prototype.dispose = function () {
  63842. };
  63843. Gamepad.GAMEPAD = 0;
  63844. Gamepad.GENERIC = 1;
  63845. Gamepad.XBOX = 2;
  63846. Gamepad.POSE_ENABLED = 3;
  63847. return Gamepad;
  63848. }());
  63849. BABYLON.Gamepad = Gamepad;
  63850. var GenericPad = /** @class */ (function (_super) {
  63851. __extends(GenericPad, _super);
  63852. function GenericPad(id, index, browserGamepad) {
  63853. var _this = _super.call(this, id, index, browserGamepad) || this;
  63854. _this.onButtonDownObservable = new BABYLON.Observable();
  63855. _this.onButtonUpObservable = new BABYLON.Observable();
  63856. _this.type = Gamepad.GENERIC;
  63857. _this._buttons = new Array(browserGamepad.buttons.length);
  63858. return _this;
  63859. }
  63860. GenericPad.prototype.onbuttondown = function (callback) {
  63861. this._onbuttondown = callback;
  63862. };
  63863. GenericPad.prototype.onbuttonup = function (callback) {
  63864. this._onbuttonup = callback;
  63865. };
  63866. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63867. if (newValue !== currentValue) {
  63868. if (newValue === 1) {
  63869. if (this._onbuttondown) {
  63870. this._onbuttondown(buttonIndex);
  63871. }
  63872. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63873. }
  63874. if (newValue === 0) {
  63875. if (this._onbuttonup) {
  63876. this._onbuttonup(buttonIndex);
  63877. }
  63878. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63879. }
  63880. }
  63881. return newValue;
  63882. };
  63883. GenericPad.prototype.update = function () {
  63884. _super.prototype.update.call(this);
  63885. for (var index = 0; index < this._buttons.length; index++) {
  63886. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63887. }
  63888. };
  63889. GenericPad.prototype.dispose = function () {
  63890. _super.prototype.dispose.call(this);
  63891. this.onButtonDownObservable.clear();
  63892. this.onButtonUpObservable.clear();
  63893. };
  63894. return GenericPad;
  63895. }(Gamepad));
  63896. BABYLON.GenericPad = GenericPad;
  63897. })(BABYLON || (BABYLON = {}));
  63898. //# sourceMappingURL=babylon.gamepad.js.map
  63899. var BABYLON;
  63900. (function (BABYLON) {
  63901. var Xbox360Button;
  63902. (function (Xbox360Button) {
  63903. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63904. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63905. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63906. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63907. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63908. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63909. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63910. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63911. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63912. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63913. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63914. var Xbox360Dpad;
  63915. (function (Xbox360Dpad) {
  63916. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63917. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63918. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63919. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63920. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63921. var Xbox360Pad = /** @class */ (function (_super) {
  63922. __extends(Xbox360Pad, _super);
  63923. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63924. if (xboxOne === void 0) { xboxOne = false; }
  63925. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63926. _this._leftTrigger = 0;
  63927. _this._rightTrigger = 0;
  63928. _this.onButtonDownObservable = new BABYLON.Observable();
  63929. _this.onButtonUpObservable = new BABYLON.Observable();
  63930. _this.onPadDownObservable = new BABYLON.Observable();
  63931. _this.onPadUpObservable = new BABYLON.Observable();
  63932. _this._buttonA = 0;
  63933. _this._buttonB = 0;
  63934. _this._buttonX = 0;
  63935. _this._buttonY = 0;
  63936. _this._buttonBack = 0;
  63937. _this._buttonStart = 0;
  63938. _this._buttonLB = 0;
  63939. _this._buttonRB = 0;
  63940. _this._buttonLeftStick = 0;
  63941. _this._buttonRightStick = 0;
  63942. _this._dPadUp = 0;
  63943. _this._dPadDown = 0;
  63944. _this._dPadLeft = 0;
  63945. _this._dPadRight = 0;
  63946. _this._isXboxOnePad = false;
  63947. _this.type = BABYLON.Gamepad.XBOX;
  63948. _this._isXboxOnePad = xboxOne;
  63949. return _this;
  63950. }
  63951. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63952. this._onlefttriggerchanged = callback;
  63953. };
  63954. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63955. this._onrighttriggerchanged = callback;
  63956. };
  63957. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63958. get: function () {
  63959. return this._leftTrigger;
  63960. },
  63961. set: function (newValue) {
  63962. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63963. this._onlefttriggerchanged(newValue);
  63964. }
  63965. this._leftTrigger = newValue;
  63966. },
  63967. enumerable: true,
  63968. configurable: true
  63969. });
  63970. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63971. get: function () {
  63972. return this._rightTrigger;
  63973. },
  63974. set: function (newValue) {
  63975. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63976. this._onrighttriggerchanged(newValue);
  63977. }
  63978. this._rightTrigger = newValue;
  63979. },
  63980. enumerable: true,
  63981. configurable: true
  63982. });
  63983. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63984. this._onbuttondown = callback;
  63985. };
  63986. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63987. this._onbuttonup = callback;
  63988. };
  63989. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63990. this._ondpaddown = callback;
  63991. };
  63992. Xbox360Pad.prototype.ondpadup = function (callback) {
  63993. this._ondpadup = callback;
  63994. };
  63995. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63996. if (newValue !== currentValue) {
  63997. if (newValue === 1) {
  63998. if (this._onbuttondown) {
  63999. this._onbuttondown(buttonType);
  64000. }
  64001. this.onButtonDownObservable.notifyObservers(buttonType);
  64002. }
  64003. if (newValue === 0) {
  64004. if (this._onbuttonup) {
  64005. this._onbuttonup(buttonType);
  64006. }
  64007. this.onButtonUpObservable.notifyObservers(buttonType);
  64008. }
  64009. }
  64010. return newValue;
  64011. };
  64012. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64013. if (newValue !== currentValue) {
  64014. if (newValue === 1) {
  64015. if (this._ondpaddown) {
  64016. this._ondpaddown(buttonType);
  64017. }
  64018. this.onPadDownObservable.notifyObservers(buttonType);
  64019. }
  64020. if (newValue === 0) {
  64021. if (this._ondpadup) {
  64022. this._ondpadup(buttonType);
  64023. }
  64024. this.onPadUpObservable.notifyObservers(buttonType);
  64025. }
  64026. }
  64027. return newValue;
  64028. };
  64029. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64030. get: function () {
  64031. return this._buttonA;
  64032. },
  64033. set: function (value) {
  64034. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64035. },
  64036. enumerable: true,
  64037. configurable: true
  64038. });
  64039. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64040. get: function () {
  64041. return this._buttonB;
  64042. },
  64043. set: function (value) {
  64044. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64045. },
  64046. enumerable: true,
  64047. configurable: true
  64048. });
  64049. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64050. get: function () {
  64051. return this._buttonX;
  64052. },
  64053. set: function (value) {
  64054. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64055. },
  64056. enumerable: true,
  64057. configurable: true
  64058. });
  64059. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64060. get: function () {
  64061. return this._buttonY;
  64062. },
  64063. set: function (value) {
  64064. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64065. },
  64066. enumerable: true,
  64067. configurable: true
  64068. });
  64069. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64070. get: function () {
  64071. return this._buttonStart;
  64072. },
  64073. set: function (value) {
  64074. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64075. },
  64076. enumerable: true,
  64077. configurable: true
  64078. });
  64079. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64080. get: function () {
  64081. return this._buttonBack;
  64082. },
  64083. set: function (value) {
  64084. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64085. },
  64086. enumerable: true,
  64087. configurable: true
  64088. });
  64089. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64090. get: function () {
  64091. return this._buttonLB;
  64092. },
  64093. set: function (value) {
  64094. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64095. },
  64096. enumerable: true,
  64097. configurable: true
  64098. });
  64099. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64100. get: function () {
  64101. return this._buttonRB;
  64102. },
  64103. set: function (value) {
  64104. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64105. },
  64106. enumerable: true,
  64107. configurable: true
  64108. });
  64109. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64110. get: function () {
  64111. return this._buttonLeftStick;
  64112. },
  64113. set: function (value) {
  64114. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64115. },
  64116. enumerable: true,
  64117. configurable: true
  64118. });
  64119. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64120. get: function () {
  64121. return this._buttonRightStick;
  64122. },
  64123. set: function (value) {
  64124. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64125. },
  64126. enumerable: true,
  64127. configurable: true
  64128. });
  64129. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64130. get: function () {
  64131. return this._dPadUp;
  64132. },
  64133. set: function (value) {
  64134. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64135. },
  64136. enumerable: true,
  64137. configurable: true
  64138. });
  64139. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64140. get: function () {
  64141. return this._dPadDown;
  64142. },
  64143. set: function (value) {
  64144. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64145. },
  64146. enumerable: true,
  64147. configurable: true
  64148. });
  64149. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64150. get: function () {
  64151. return this._dPadLeft;
  64152. },
  64153. set: function (value) {
  64154. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64155. },
  64156. enumerable: true,
  64157. configurable: true
  64158. });
  64159. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64160. get: function () {
  64161. return this._dPadRight;
  64162. },
  64163. set: function (value) {
  64164. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64165. },
  64166. enumerable: true,
  64167. configurable: true
  64168. });
  64169. Xbox360Pad.prototype.update = function () {
  64170. _super.prototype.update.call(this);
  64171. if (this._isXboxOnePad) {
  64172. this.buttonA = this.browserGamepad.buttons[0].value;
  64173. this.buttonB = this.browserGamepad.buttons[1].value;
  64174. this.buttonX = this.browserGamepad.buttons[2].value;
  64175. this.buttonY = this.browserGamepad.buttons[3].value;
  64176. this.buttonLB = this.browserGamepad.buttons[4].value;
  64177. this.buttonRB = this.browserGamepad.buttons[5].value;
  64178. this.leftTrigger = this.browserGamepad.axes[2];
  64179. this.rightTrigger = this.browserGamepad.axes[5];
  64180. this.buttonBack = this.browserGamepad.buttons[9].value;
  64181. this.buttonStart = this.browserGamepad.buttons[8].value;
  64182. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64183. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64184. this.dPadUp = this.browserGamepad.buttons[11].value;
  64185. this.dPadDown = this.browserGamepad.buttons[12].value;
  64186. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64187. this.dPadRight = this.browserGamepad.buttons[14].value;
  64188. }
  64189. else {
  64190. this.buttonA = this.browserGamepad.buttons[0].value;
  64191. this.buttonB = this.browserGamepad.buttons[1].value;
  64192. this.buttonX = this.browserGamepad.buttons[2].value;
  64193. this.buttonY = this.browserGamepad.buttons[3].value;
  64194. this.buttonLB = this.browserGamepad.buttons[4].value;
  64195. this.buttonRB = this.browserGamepad.buttons[5].value;
  64196. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64197. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64198. this.buttonBack = this.browserGamepad.buttons[8].value;
  64199. this.buttonStart = this.browserGamepad.buttons[9].value;
  64200. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64201. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64202. this.dPadUp = this.browserGamepad.buttons[12].value;
  64203. this.dPadDown = this.browserGamepad.buttons[13].value;
  64204. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64205. this.dPadRight = this.browserGamepad.buttons[15].value;
  64206. }
  64207. };
  64208. Xbox360Pad.prototype.dispose = function () {
  64209. _super.prototype.dispose.call(this);
  64210. this.onButtonDownObservable.clear();
  64211. this.onButtonUpObservable.clear();
  64212. this.onPadDownObservable.clear();
  64213. this.onPadUpObservable.clear();
  64214. };
  64215. return Xbox360Pad;
  64216. }(BABYLON.Gamepad));
  64217. BABYLON.Xbox360Pad = Xbox360Pad;
  64218. })(BABYLON || (BABYLON = {}));
  64219. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64220. var BABYLON;
  64221. (function (BABYLON) {
  64222. var PoseEnabledControllerType;
  64223. (function (PoseEnabledControllerType) {
  64224. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64225. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64226. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64227. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64228. /**
  64229. * Google Daydream
  64230. */
  64231. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  64232. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  64233. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64234. var PoseEnabledControllerHelper = /** @class */ (function () {
  64235. function PoseEnabledControllerHelper() {
  64236. }
  64237. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64238. // Oculus Touch
  64239. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64240. return new BABYLON.OculusTouchController(vrGamepad);
  64241. }
  64242. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64243. return new BABYLON.WindowsMotionController(vrGamepad);
  64244. }
  64245. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64246. return new BABYLON.ViveController(vrGamepad);
  64247. }
  64248. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64249. return new BABYLON.GearVRController(vrGamepad);
  64250. }
  64251. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  64252. return new BABYLON.DaydreamController(vrGamepad);
  64253. }
  64254. else {
  64255. return new BABYLON.GenericController(vrGamepad);
  64256. }
  64257. };
  64258. return PoseEnabledControllerHelper;
  64259. }());
  64260. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64261. var PoseEnabledController = /** @class */ (function (_super) {
  64262. __extends(PoseEnabledController, _super);
  64263. function PoseEnabledController(browserGamepad) {
  64264. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64265. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64266. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64267. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64268. // Represents device position and rotation in babylon space
  64269. _this.devicePosition = BABYLON.Vector3.Zero();
  64270. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64271. _this.deviceScaleFactor = 1;
  64272. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64273. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64274. _this._workingMatrix = BABYLON.Matrix.Identity();
  64275. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64276. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64277. _this.position = BABYLON.Vector3.Zero();
  64278. _this.rotationQuaternion = new BABYLON.Quaternion();
  64279. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64280. _this._calculatedRotation = new BABYLON.Quaternion();
  64281. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64282. return _this;
  64283. }
  64284. PoseEnabledController.prototype.update = function () {
  64285. _super.prototype.update.call(this);
  64286. var pose = this.browserGamepad.pose;
  64287. this.updateFromDevice(pose);
  64288. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64289. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64290. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64291. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64292. if (this._mesh) {
  64293. this._mesh.position.copyFrom(this.devicePosition);
  64294. if (this._mesh.rotationQuaternion) {
  64295. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64296. }
  64297. }
  64298. };
  64299. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64300. if (poseData) {
  64301. this.rawPose = poseData;
  64302. if (poseData.position) {
  64303. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64304. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64305. this._deviceRoomPosition.z *= -1;
  64306. }
  64307. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64308. this._calculatedPosition.addInPlace(this.position);
  64309. }
  64310. var pose = this.rawPose;
  64311. if (poseData.orientation && pose.orientation) {
  64312. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64313. if (this._mesh) {
  64314. if (this._mesh.getScene().useRightHandedSystem) {
  64315. this._deviceRoomRotationQuaternion.z *= -1;
  64316. this._deviceRoomRotationQuaternion.w *= -1;
  64317. }
  64318. else {
  64319. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64320. }
  64321. }
  64322. // if the camera is set, rotate to the camera's rotation
  64323. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64324. }
  64325. }
  64326. };
  64327. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64328. if (this._mesh) {
  64329. this._mesh.parent = null;
  64330. }
  64331. this._mesh = mesh;
  64332. if (this._poseControlledCamera) {
  64333. this._mesh.parent = this._poseControlledCamera;
  64334. }
  64335. if (!this._mesh.rotationQuaternion) {
  64336. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64337. }
  64338. };
  64339. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64340. this._poseControlledCamera = camera;
  64341. if (this._mesh) {
  64342. this._mesh.parent = this._poseControlledCamera;
  64343. }
  64344. };
  64345. PoseEnabledController.prototype.dispose = function () {
  64346. if (this._mesh) {
  64347. this._mesh.dispose();
  64348. }
  64349. this._mesh = null;
  64350. _super.prototype.dispose.call(this);
  64351. };
  64352. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64353. get: function () {
  64354. return this._mesh;
  64355. },
  64356. enumerable: true,
  64357. configurable: true
  64358. });
  64359. PoseEnabledController.prototype.getForwardRay = function (length) {
  64360. if (length === void 0) { length = 100; }
  64361. if (!this.mesh) {
  64362. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64363. }
  64364. var m = this.mesh.getWorldMatrix();
  64365. var origin = m.getTranslation();
  64366. var forward = new BABYLON.Vector3(0, 0, -1);
  64367. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64368. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64369. return new BABYLON.Ray(origin, direction, length);
  64370. };
  64371. return PoseEnabledController;
  64372. }(BABYLON.Gamepad));
  64373. BABYLON.PoseEnabledController = PoseEnabledController;
  64374. })(BABYLON || (BABYLON = {}));
  64375. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64376. var BABYLON;
  64377. (function (BABYLON) {
  64378. var WebVRController = /** @class */ (function (_super) {
  64379. __extends(WebVRController, _super);
  64380. function WebVRController(vrGamepad) {
  64381. var _this = _super.call(this, vrGamepad) || this;
  64382. // Observables
  64383. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64384. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64385. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64386. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64387. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64388. _this.pad = { x: 0, y: 0 };
  64389. // avoid GC, store state in a tmp object
  64390. _this._changes = {
  64391. pressChanged: false,
  64392. touchChanged: false,
  64393. valueChanged: false,
  64394. changed: false
  64395. };
  64396. _this._buttons = new Array(vrGamepad.buttons.length);
  64397. _this.hand = vrGamepad.hand;
  64398. return _this;
  64399. }
  64400. WebVRController.prototype.onButtonStateChange = function (callback) {
  64401. this._onButtonStateChange = callback;
  64402. };
  64403. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64404. get: function () {
  64405. return this._defaultModel;
  64406. },
  64407. enumerable: true,
  64408. configurable: true
  64409. });
  64410. WebVRController.prototype.update = function () {
  64411. _super.prototype.update.call(this);
  64412. for (var index = 0; index < this._buttons.length; index++) {
  64413. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64414. }
  64415. ;
  64416. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64417. this.pad.x = this.leftStick.x;
  64418. this.pad.y = this.leftStick.y;
  64419. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64420. }
  64421. };
  64422. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64423. if (!newState) {
  64424. newState = {
  64425. pressed: false,
  64426. touched: false,
  64427. value: 0
  64428. };
  64429. }
  64430. if (!currentState) {
  64431. this._buttons[buttonIndex] = {
  64432. pressed: newState.pressed,
  64433. touched: newState.touched,
  64434. value: newState.value
  64435. };
  64436. return;
  64437. }
  64438. this._checkChanges(newState, currentState);
  64439. if (this._changes.changed) {
  64440. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64441. this._handleButtonChange(buttonIndex, newState, this._changes);
  64442. }
  64443. this._buttons[buttonIndex].pressed = newState.pressed;
  64444. this._buttons[buttonIndex].touched = newState.touched;
  64445. // oculus triggers are never 0, thou not touched.
  64446. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64447. };
  64448. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64449. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64450. this._changes.touchChanged = newState.touched !== currentState.touched;
  64451. this._changes.valueChanged = newState.value !== currentState.value;
  64452. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64453. return this._changes;
  64454. };
  64455. WebVRController.prototype.dispose = function () {
  64456. _super.prototype.dispose.call(this);
  64457. this.onTriggerStateChangedObservable.clear();
  64458. this.onMainButtonStateChangedObservable.clear();
  64459. this.onSecondaryButtonStateChangedObservable.clear();
  64460. this.onPadStateChangedObservable.clear();
  64461. this.onPadValuesChangedObservable.clear();
  64462. };
  64463. return WebVRController;
  64464. }(BABYLON.PoseEnabledController));
  64465. BABYLON.WebVRController = WebVRController;
  64466. })(BABYLON || (BABYLON = {}));
  64467. //# sourceMappingURL=babylon.webVRController.js.map
  64468. var BABYLON;
  64469. (function (BABYLON) {
  64470. var OculusTouchController = /** @class */ (function (_super) {
  64471. __extends(OculusTouchController, _super);
  64472. function OculusTouchController(vrGamepad) {
  64473. var _this = _super.call(this, vrGamepad) || this;
  64474. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64475. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64476. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64477. return _this;
  64478. }
  64479. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64480. var _this = this;
  64481. var meshName;
  64482. // Hand
  64483. if (this.hand === 'left') {
  64484. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64485. }
  64486. else {
  64487. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64488. }
  64489. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64490. /*
  64491. Parent Mesh name: oculus_touch_left
  64492. - body
  64493. - trigger
  64494. - thumbstick
  64495. - grip
  64496. - button_y
  64497. - button_x
  64498. - button_enter
  64499. */
  64500. _this._defaultModel = newMeshes[1];
  64501. _this.attachToMesh(_this._defaultModel);
  64502. if (meshLoaded) {
  64503. meshLoaded(_this._defaultModel);
  64504. }
  64505. });
  64506. };
  64507. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64508. // helper getters for left and right hand.
  64509. get: function () {
  64510. if (this.hand === 'right') {
  64511. return this.onMainButtonStateChangedObservable;
  64512. }
  64513. else {
  64514. throw new Error('No A button on left hand');
  64515. }
  64516. },
  64517. enumerable: true,
  64518. configurable: true
  64519. });
  64520. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64521. get: function () {
  64522. if (this.hand === 'right') {
  64523. return this.onSecondaryButtonStateChangedObservable;
  64524. }
  64525. else {
  64526. throw new Error('No B button on left hand');
  64527. }
  64528. },
  64529. enumerable: true,
  64530. configurable: true
  64531. });
  64532. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64533. get: function () {
  64534. if (this.hand === 'left') {
  64535. return this.onMainButtonStateChangedObservable;
  64536. }
  64537. else {
  64538. throw new Error('No X button on right hand');
  64539. }
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64545. get: function () {
  64546. if (this.hand === 'left') {
  64547. return this.onSecondaryButtonStateChangedObservable;
  64548. }
  64549. else {
  64550. throw new Error('No Y button on right hand');
  64551. }
  64552. },
  64553. enumerable: true,
  64554. configurable: true
  64555. });
  64556. /*
  64557. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64558. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64559. 2) secondary trigger (same)
  64560. 3) A (right) X (left), touch, pressed = value
  64561. 4) B / Y
  64562. 5) thumb rest
  64563. */
  64564. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64565. var notifyObject = state; //{ state: state, changes: changes };
  64566. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64567. switch (buttonIdx) {
  64568. case 0:
  64569. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64570. return;
  64571. case 1:// index trigger
  64572. if (this._defaultModel) {
  64573. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64574. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64575. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64576. }
  64577. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64578. return;
  64579. case 2:// secondary trigger
  64580. if (this._defaultModel) {
  64581. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64582. }
  64583. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64584. return;
  64585. case 3:
  64586. if (this._defaultModel) {
  64587. if (notifyObject.pressed) {
  64588. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64589. }
  64590. else {
  64591. (this._defaultModel.getChildren()[1]).position.y = 0;
  64592. }
  64593. }
  64594. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64595. return;
  64596. case 4:
  64597. if (this._defaultModel) {
  64598. if (notifyObject.pressed) {
  64599. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64600. }
  64601. else {
  64602. (this._defaultModel.getChildren()[2]).position.y = 0;
  64603. }
  64604. }
  64605. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64606. return;
  64607. case 5:
  64608. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64609. return;
  64610. }
  64611. };
  64612. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64613. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64614. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64615. return OculusTouchController;
  64616. }(BABYLON.WebVRController));
  64617. BABYLON.OculusTouchController = OculusTouchController;
  64618. })(BABYLON || (BABYLON = {}));
  64619. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64620. var BABYLON;
  64621. (function (BABYLON) {
  64622. var ViveController = /** @class */ (function (_super) {
  64623. __extends(ViveController, _super);
  64624. function ViveController(vrGamepad) {
  64625. var _this = _super.call(this, vrGamepad) || this;
  64626. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64627. _this._invertLeftStickY = true;
  64628. return _this;
  64629. }
  64630. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64631. var _this = this;
  64632. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64633. /*
  64634. Parent Mesh name: ViveWand
  64635. - body
  64636. - r_gripper
  64637. - l_gripper
  64638. - menu_button
  64639. - system_button
  64640. - trackpad
  64641. - trigger
  64642. - LED
  64643. */
  64644. _this._defaultModel = newMeshes[1];
  64645. _this.attachToMesh(_this._defaultModel);
  64646. if (meshLoaded) {
  64647. meshLoaded(_this._defaultModel);
  64648. }
  64649. });
  64650. };
  64651. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64652. get: function () {
  64653. return this.onMainButtonStateChangedObservable;
  64654. },
  64655. enumerable: true,
  64656. configurable: true
  64657. });
  64658. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64659. get: function () {
  64660. return this.onMainButtonStateChangedObservable;
  64661. },
  64662. enumerable: true,
  64663. configurable: true
  64664. });
  64665. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64666. get: function () {
  64667. return this.onSecondaryButtonStateChangedObservable;
  64668. },
  64669. enumerable: true,
  64670. configurable: true
  64671. });
  64672. /**
  64673. * Vive mapping:
  64674. * 0: touchpad
  64675. * 1: trigger
  64676. * 2: left AND right buttons
  64677. * 3: menu button
  64678. */
  64679. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64680. var notifyObject = state; //{ state: state, changes: changes };
  64681. switch (buttonIdx) {
  64682. case 0:
  64683. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64684. return;
  64685. case 1:// index trigger
  64686. if (this._defaultModel) {
  64687. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64688. }
  64689. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64690. return;
  64691. case 2:// left AND right button
  64692. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64693. return;
  64694. case 3:
  64695. if (this._defaultModel) {
  64696. if (notifyObject.pressed) {
  64697. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64698. }
  64699. else {
  64700. (this._defaultModel.getChildren()[2]).position.y = 0;
  64701. }
  64702. }
  64703. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64704. return;
  64705. }
  64706. };
  64707. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64708. ViveController.MODEL_FILENAME = 'wand.babylon';
  64709. return ViveController;
  64710. }(BABYLON.WebVRController));
  64711. BABYLON.ViveController = ViveController;
  64712. })(BABYLON || (BABYLON = {}));
  64713. //# sourceMappingURL=babylon.viveController.js.map
  64714. var BABYLON;
  64715. (function (BABYLON) {
  64716. var GenericController = /** @class */ (function (_super) {
  64717. __extends(GenericController, _super);
  64718. function GenericController(vrGamepad) {
  64719. return _super.call(this, vrGamepad) || this;
  64720. }
  64721. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64722. var _this = this;
  64723. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64724. _this._defaultModel = newMeshes[1];
  64725. _this.attachToMesh(_this._defaultModel);
  64726. if (meshLoaded) {
  64727. meshLoaded(_this._defaultModel);
  64728. }
  64729. });
  64730. };
  64731. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64732. console.log("Button id: " + buttonIdx + "state: ");
  64733. console.dir(state);
  64734. };
  64735. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64736. GenericController.MODEL_FILENAME = 'generic.babylon';
  64737. return GenericController;
  64738. }(BABYLON.WebVRController));
  64739. BABYLON.GenericController = GenericController;
  64740. })(BABYLON || (BABYLON = {}));
  64741. //# sourceMappingURL=babylon.genericController.js.map
  64742. var BABYLON;
  64743. (function (BABYLON) {
  64744. var LoadedMeshInfo = /** @class */ (function () {
  64745. function LoadedMeshInfo() {
  64746. this.buttonMeshes = {};
  64747. this.axisMeshes = {};
  64748. }
  64749. return LoadedMeshInfo;
  64750. }());
  64751. var WindowsMotionController = /** @class */ (function (_super) {
  64752. __extends(WindowsMotionController, _super);
  64753. function WindowsMotionController(vrGamepad) {
  64754. var _this = _super.call(this, vrGamepad) || this;
  64755. _this._mapping = {
  64756. // Semantic button names
  64757. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64758. // A mapping of the button name to glTF model node name
  64759. // that should be transformed by button value.
  64760. buttonMeshNames: {
  64761. 'trigger': 'SELECT',
  64762. 'menu': 'MENU',
  64763. 'grip': 'GRASP',
  64764. 'thumbstick': 'THUMBSTICK_PRESS',
  64765. 'trackpad': 'TOUCHPAD_PRESS'
  64766. },
  64767. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64768. buttonObservableNames: {
  64769. 'trigger': 'onTriggerStateChangedObservable',
  64770. 'menu': 'onSecondaryButtonStateChangedObservable',
  64771. 'grip': 'onMainButtonStateChangedObservable',
  64772. 'thumbstick': 'onPadStateChangedObservable',
  64773. 'trackpad': 'onTrackpadChangedObservable'
  64774. },
  64775. // A mapping of the axis name to glTF model node name
  64776. // that should be transformed by axis value.
  64777. // This array mirrors the browserGamepad.axes array, such that
  64778. // the mesh corresponding to axis 0 is in this array index 0.
  64779. axisMeshNames: [
  64780. 'THUMBSTICK_X',
  64781. 'THUMBSTICK_Y',
  64782. 'TOUCHPAD_TOUCH_X',
  64783. 'TOUCHPAD_TOUCH_Y'
  64784. ],
  64785. pointingPoseMeshName: 'POINTING_POSE'
  64786. };
  64787. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64788. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64789. _this.trackpad = { x: 0, y: 0 };
  64790. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64791. _this._loadedMeshInfo = null;
  64792. return _this;
  64793. }
  64794. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64795. get: function () {
  64796. return this.onTriggerStateChangedObservable;
  64797. },
  64798. enumerable: true,
  64799. configurable: true
  64800. });
  64801. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64802. get: function () {
  64803. return this.onSecondaryButtonStateChangedObservable;
  64804. },
  64805. enumerable: true,
  64806. configurable: true
  64807. });
  64808. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64809. get: function () {
  64810. return this.onMainButtonStateChangedObservable;
  64811. },
  64812. enumerable: true,
  64813. configurable: true
  64814. });
  64815. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64816. get: function () {
  64817. return this.onPadStateChangedObservable;
  64818. },
  64819. enumerable: true,
  64820. configurable: true
  64821. });
  64822. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64823. get: function () {
  64824. return this.onTrackpadChangedObservable;
  64825. },
  64826. enumerable: true,
  64827. configurable: true
  64828. });
  64829. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64830. get: function () {
  64831. return this.onTrackpadValuesChangedObservable;
  64832. },
  64833. enumerable: true,
  64834. configurable: true
  64835. });
  64836. /**
  64837. * Called once per frame by the engine.
  64838. */
  64839. WindowsMotionController.prototype.update = function () {
  64840. _super.prototype.update.call(this);
  64841. // Only need to animate axes if there is a loaded mesh
  64842. if (this._loadedMeshInfo) {
  64843. if (this.browserGamepad.axes) {
  64844. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64845. this.trackpad.x = this.browserGamepad["axes"][2];
  64846. this.trackpad.y = this.browserGamepad["axes"][3];
  64847. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64848. }
  64849. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64850. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64851. }
  64852. }
  64853. }
  64854. };
  64855. /**
  64856. * Called once for each button that changed state since the last frame
  64857. * @param buttonIdx Which button index changed
  64858. * @param state New state of the button
  64859. * @param changes Which properties on the state changed since last frame
  64860. */
  64861. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  64862. var buttonName = this._mapping.buttons[buttonIdx];
  64863. if (!buttonName) {
  64864. return;
  64865. }
  64866. // Only emit events for buttons that we know how to map from index to name
  64867. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64868. if (observable) {
  64869. observable.notifyObservers(state);
  64870. }
  64871. this.lerpButtonTransform(buttonName, state.value);
  64872. };
  64873. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64874. // If there is no loaded mesh, there is nothing to transform.
  64875. if (!this._loadedMeshInfo) {
  64876. return;
  64877. }
  64878. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64879. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64880. return;
  64881. }
  64882. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64883. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64884. };
  64885. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64886. if (!this._loadedMeshInfo) {
  64887. return;
  64888. }
  64889. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64890. if (!meshInfo) {
  64891. return;
  64892. }
  64893. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64894. return;
  64895. }
  64896. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64897. var lerpValue = axisValue * 0.5 + 0.5;
  64898. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64899. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64900. };
  64901. /**
  64902. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64903. * @param scene scene in which to add meshes
  64904. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64905. */
  64906. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64907. var _this = this;
  64908. if (forceDefault === void 0) { forceDefault = false; }
  64909. var path;
  64910. var filename;
  64911. // Checking if GLB loader is present
  64912. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64913. // Determine the device specific folder based on the ID suffix
  64914. var device = 'default';
  64915. if (this.id && !forceDefault) {
  64916. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64917. device = ((match && match[0]) || device);
  64918. }
  64919. // Hand
  64920. if (this.hand === 'left') {
  64921. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64922. }
  64923. else {
  64924. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64925. }
  64926. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64927. }
  64928. else {
  64929. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64930. path = BABYLON.GenericController.MODEL_BASE_URL;
  64931. filename = BABYLON.GenericController.MODEL_FILENAME;
  64932. }
  64933. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64934. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64935. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64936. if (!_this._loadedMeshInfo) {
  64937. return;
  64938. }
  64939. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64940. _this.attachToMesh(_this._defaultModel);
  64941. if (meshLoaded) {
  64942. meshLoaded(_this._defaultModel);
  64943. }
  64944. }, null, function (scene, message) {
  64945. BABYLON.Tools.Log(message);
  64946. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64947. if (!forceDefault) {
  64948. _this.initControllerMesh(scene, meshLoaded, true);
  64949. }
  64950. });
  64951. };
  64952. /**
  64953. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64954. * can be transformed by button presses and axes values, based on this._mapping.
  64955. *
  64956. * @param scene scene in which the meshes exist
  64957. * @param meshes list of meshes that make up the controller model to process
  64958. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64959. */
  64960. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64961. var loadedMeshInfo = null;
  64962. // Create a new mesh to contain the glTF hierarchy
  64963. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64964. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64965. var childMesh = null;
  64966. for (var i = 0; i < meshes.length; i++) {
  64967. var mesh = meshes[i];
  64968. if (!mesh.parent) {
  64969. // Exclude controller meshes from picking results
  64970. mesh.isPickable = false;
  64971. // Handle root node, attach to the new parentMesh
  64972. childMesh = mesh;
  64973. break;
  64974. }
  64975. }
  64976. if (childMesh) {
  64977. childMesh.setParent(parentMesh);
  64978. // Create our mesh info. Note that this method will always return non-null.
  64979. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64980. }
  64981. else {
  64982. BABYLON.Tools.Warn('Could not find root node in model file.');
  64983. }
  64984. return loadedMeshInfo;
  64985. };
  64986. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64987. var loadedMeshInfo = new LoadedMeshInfo();
  64988. var i;
  64989. loadedMeshInfo.rootNode = rootNode;
  64990. // Reset the caches
  64991. loadedMeshInfo.buttonMeshes = {};
  64992. loadedMeshInfo.axisMeshes = {};
  64993. // Button Meshes
  64994. for (i = 0; i < this._mapping.buttons.length; i++) {
  64995. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64996. if (!buttonMeshName) {
  64997. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64998. continue;
  64999. }
  65000. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65001. if (!buttonMesh) {
  65002. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65003. continue;
  65004. }
  65005. var buttonMeshInfo = {
  65006. index: i,
  65007. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65008. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65009. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65010. };
  65011. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65012. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65013. }
  65014. else {
  65015. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65016. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65017. '(VALUE: ' + !!buttonMeshInfo.value +
  65018. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65019. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65020. ')');
  65021. }
  65022. }
  65023. // Axis Meshes
  65024. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65025. var axisMeshName = this._mapping.axisMeshNames[i];
  65026. if (!axisMeshName) {
  65027. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65028. continue;
  65029. }
  65030. var axisMesh = getChildByName(rootNode, axisMeshName);
  65031. if (!axisMesh) {
  65032. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65033. continue;
  65034. }
  65035. var axisMeshInfo = {
  65036. index: i,
  65037. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65038. min: getImmediateChildByName(axisMesh, 'MIN'),
  65039. max: getImmediateChildByName(axisMesh, 'MAX')
  65040. };
  65041. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65042. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65043. }
  65044. else {
  65045. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65046. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65047. '(VALUE: ' + !!axisMeshInfo.value +
  65048. ', MIN: ' + !!axisMeshInfo.min +
  65049. ', MAX:' + !!axisMeshInfo.max +
  65050. ')');
  65051. }
  65052. }
  65053. // Pointing Ray
  65054. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65055. if (!loadedMeshInfo.pointingPoseNode) {
  65056. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65057. }
  65058. return loadedMeshInfo;
  65059. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65060. function getChildByName(node, name) {
  65061. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65062. }
  65063. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65064. function getImmediateChildByName(node, name) {
  65065. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65066. }
  65067. };
  65068. WindowsMotionController.prototype.getForwardRay = function (length) {
  65069. if (length === void 0) { length = 100; }
  65070. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65071. return _super.prototype.getForwardRay.call(this, length);
  65072. }
  65073. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65074. var origin = m.getTranslation();
  65075. var forward = new BABYLON.Vector3(0, 0, -1);
  65076. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65077. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65078. return new BABYLON.Ray(origin, direction, length);
  65079. };
  65080. WindowsMotionController.prototype.dispose = function () {
  65081. _super.prototype.dispose.call(this);
  65082. this.onTrackpadChangedObservable.clear();
  65083. };
  65084. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65085. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65086. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65087. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65088. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65089. return WindowsMotionController;
  65090. }(BABYLON.WebVRController));
  65091. BABYLON.WindowsMotionController = WindowsMotionController;
  65092. })(BABYLON || (BABYLON = {}));
  65093. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65094. var BABYLON;
  65095. (function (BABYLON) {
  65096. var GearVRController = /** @class */ (function (_super) {
  65097. __extends(GearVRController, _super);
  65098. function GearVRController(vrGamepad) {
  65099. var _this = _super.call(this, vrGamepad) || this;
  65100. _this._buttonIndexToObservableNameMap = [
  65101. 'onTrackpadChangedObservable',
  65102. 'onTriggerStateChangedObservable' // Trigger
  65103. ];
  65104. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65105. return _this;
  65106. }
  65107. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65108. var _this = this;
  65109. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65110. _this._defaultModel = newMeshes[1];
  65111. _this.attachToMesh(_this._defaultModel);
  65112. if (meshLoaded) {
  65113. meshLoaded(_this._defaultModel);
  65114. }
  65115. });
  65116. };
  65117. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65118. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65119. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65120. // Only emit events for buttons that we know how to map from index to observable
  65121. var observable = this[observableName];
  65122. if (observable) {
  65123. observable.notifyObservers(state);
  65124. }
  65125. }
  65126. };
  65127. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65128. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65129. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65130. return GearVRController;
  65131. }(BABYLON.WebVRController));
  65132. BABYLON.GearVRController = GearVRController;
  65133. })(BABYLON || (BABYLON = {}));
  65134. //# sourceMappingURL=babylon.gearVRController.js.map
  65135. var BABYLON;
  65136. (function (BABYLON) {
  65137. /**
  65138. * Google Daydream controller
  65139. */
  65140. var DaydreamController = /** @class */ (function (_super) {
  65141. __extends(DaydreamController, _super);
  65142. function DaydreamController(vrGamepad) {
  65143. var _this = _super.call(this, vrGamepad) || this;
  65144. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  65145. return _this;
  65146. }
  65147. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65148. var _this = this;
  65149. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  65150. _this._defaultModel = newMeshes[1];
  65151. _this.attachToMesh(_this._defaultModel);
  65152. if (meshLoaded) {
  65153. meshLoaded(_this._defaultModel);
  65154. }
  65155. });
  65156. };
  65157. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65158. // Daydream controller only has 1 GamepadButton (on the trackpad).
  65159. if (buttonIdx === 0) {
  65160. var observable = this.onTriggerStateChangedObservable;
  65161. if (observable) {
  65162. observable.notifyObservers(state);
  65163. }
  65164. }
  65165. else {
  65166. // If the app or home buttons are ever made available
  65167. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  65168. }
  65169. };
  65170. /**
  65171. * Base Url for the controller model.
  65172. */
  65173. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65174. /**
  65175. * File name for the controller model.
  65176. */
  65177. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  65178. /**
  65179. * Gamepad Id prefix used to identify Daydream Controller.
  65180. */
  65181. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  65182. return DaydreamController;
  65183. }(BABYLON.WebVRController));
  65184. BABYLON.DaydreamController = DaydreamController;
  65185. })(BABYLON || (BABYLON = {}));
  65186. //# sourceMappingURL=babylon.daydreamController.js.map
  65187. var BABYLON;
  65188. (function (BABYLON) {
  65189. var FollowCamera = /** @class */ (function (_super) {
  65190. __extends(FollowCamera, _super);
  65191. function FollowCamera(name, position, scene, lockedTarget) {
  65192. if (lockedTarget === void 0) { lockedTarget = null; }
  65193. var _this = _super.call(this, name, position, scene) || this;
  65194. _this.radius = 12;
  65195. _this.rotationOffset = 0;
  65196. _this.heightOffset = 4;
  65197. _this.cameraAcceleration = 0.05;
  65198. _this.maxCameraSpeed = 20;
  65199. _this.lockedTarget = lockedTarget;
  65200. return _this;
  65201. }
  65202. FollowCamera.prototype.getRadians = function (degrees) {
  65203. return degrees * Math.PI / 180;
  65204. };
  65205. FollowCamera.prototype.follow = function (cameraTarget) {
  65206. if (!cameraTarget)
  65207. return;
  65208. var yRotation;
  65209. if (cameraTarget.rotationQuaternion) {
  65210. var rotMatrix = new BABYLON.Matrix();
  65211. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65212. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65213. }
  65214. else {
  65215. yRotation = cameraTarget.rotation.y;
  65216. }
  65217. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65218. var targetPosition = cameraTarget.getAbsolutePosition();
  65219. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65220. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65221. var dx = targetX - this.position.x;
  65222. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65223. var dz = (targetZ) - this.position.z;
  65224. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65225. var vy = dy * this.cameraAcceleration;
  65226. var vz = dz * this.cameraAcceleration * 2;
  65227. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65228. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65229. }
  65230. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65231. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65232. }
  65233. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65234. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65235. }
  65236. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65237. this.setTarget(targetPosition);
  65238. };
  65239. FollowCamera.prototype._checkInputs = function () {
  65240. _super.prototype._checkInputs.call(this);
  65241. if (this.lockedTarget) {
  65242. this.follow(this.lockedTarget);
  65243. }
  65244. };
  65245. FollowCamera.prototype.getClassName = function () {
  65246. return "FollowCamera";
  65247. };
  65248. __decorate([
  65249. BABYLON.serialize()
  65250. ], FollowCamera.prototype, "radius", void 0);
  65251. __decorate([
  65252. BABYLON.serialize()
  65253. ], FollowCamera.prototype, "rotationOffset", void 0);
  65254. __decorate([
  65255. BABYLON.serialize()
  65256. ], FollowCamera.prototype, "heightOffset", void 0);
  65257. __decorate([
  65258. BABYLON.serialize()
  65259. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65260. __decorate([
  65261. BABYLON.serialize()
  65262. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65263. __decorate([
  65264. BABYLON.serializeAsMeshReference("lockedTargetId")
  65265. ], FollowCamera.prototype, "lockedTarget", void 0);
  65266. return FollowCamera;
  65267. }(BABYLON.TargetCamera));
  65268. BABYLON.FollowCamera = FollowCamera;
  65269. var ArcFollowCamera = /** @class */ (function (_super) {
  65270. __extends(ArcFollowCamera, _super);
  65271. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65272. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65273. _this.alpha = alpha;
  65274. _this.beta = beta;
  65275. _this.radius = radius;
  65276. _this.target = target;
  65277. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65278. _this.follow();
  65279. return _this;
  65280. }
  65281. ArcFollowCamera.prototype.follow = function () {
  65282. if (!this.target) {
  65283. return;
  65284. }
  65285. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65286. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65287. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65288. var targetPosition = this.target.getAbsolutePosition();
  65289. this.position = targetPosition.add(this._cartesianCoordinates);
  65290. this.setTarget(targetPosition);
  65291. };
  65292. ArcFollowCamera.prototype._checkInputs = function () {
  65293. _super.prototype._checkInputs.call(this);
  65294. this.follow();
  65295. };
  65296. ArcFollowCamera.prototype.getClassName = function () {
  65297. return "ArcFollowCamera";
  65298. };
  65299. return ArcFollowCamera;
  65300. }(BABYLON.TargetCamera));
  65301. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65302. })(BABYLON || (BABYLON = {}));
  65303. //# sourceMappingURL=babylon.followCamera.js.map
  65304. var BABYLON;
  65305. (function (BABYLON) {
  65306. // We're mainly based on the logic defined into the FreeCamera code
  65307. var UniversalCamera = /** @class */ (function (_super) {
  65308. __extends(UniversalCamera, _super);
  65309. //-- end properties for backward compatibility for inputs
  65310. function UniversalCamera(name, position, scene) {
  65311. var _this = _super.call(this, name, position, scene) || this;
  65312. _this.inputs.addGamepad();
  65313. return _this;
  65314. }
  65315. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65316. //-- Begin properties for backward compatibility for inputs
  65317. get: function () {
  65318. var gamepad = this.inputs.attached["gamepad"];
  65319. if (gamepad)
  65320. return gamepad.gamepadAngularSensibility;
  65321. return 0;
  65322. },
  65323. set: function (value) {
  65324. var gamepad = this.inputs.attached["gamepad"];
  65325. if (gamepad)
  65326. gamepad.gamepadAngularSensibility = value;
  65327. },
  65328. enumerable: true,
  65329. configurable: true
  65330. });
  65331. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65332. get: function () {
  65333. var gamepad = this.inputs.attached["gamepad"];
  65334. if (gamepad)
  65335. return gamepad.gamepadMoveSensibility;
  65336. return 0;
  65337. },
  65338. set: function (value) {
  65339. var gamepad = this.inputs.attached["gamepad"];
  65340. if (gamepad)
  65341. gamepad.gamepadMoveSensibility = value;
  65342. },
  65343. enumerable: true,
  65344. configurable: true
  65345. });
  65346. UniversalCamera.prototype.getClassName = function () {
  65347. return "UniversalCamera";
  65348. };
  65349. return UniversalCamera;
  65350. }(BABYLON.TouchCamera));
  65351. BABYLON.UniversalCamera = UniversalCamera;
  65352. })(BABYLON || (BABYLON = {}));
  65353. //# sourceMappingURL=babylon.universalCamera.js.map
  65354. var BABYLON;
  65355. (function (BABYLON) {
  65356. // We're mainly based on the logic defined into the FreeCamera code
  65357. var GamepadCamera = /** @class */ (function (_super) {
  65358. __extends(GamepadCamera, _super);
  65359. //-- end properties for backward compatibility for inputs
  65360. function GamepadCamera(name, position, scene) {
  65361. return _super.call(this, name, position, scene) || this;
  65362. }
  65363. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65364. //-- Begin properties for backward compatibility for inputs
  65365. get: function () {
  65366. var gamepad = this.inputs.attached["gamepad"];
  65367. if (gamepad)
  65368. return gamepad.gamepadAngularSensibility;
  65369. return 0;
  65370. },
  65371. set: function (value) {
  65372. var gamepad = this.inputs.attached["gamepad"];
  65373. if (gamepad)
  65374. gamepad.gamepadAngularSensibility = value;
  65375. },
  65376. enumerable: true,
  65377. configurable: true
  65378. });
  65379. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65380. get: function () {
  65381. var gamepad = this.inputs.attached["gamepad"];
  65382. if (gamepad)
  65383. return gamepad.gamepadMoveSensibility;
  65384. return 0;
  65385. },
  65386. set: function (value) {
  65387. var gamepad = this.inputs.attached["gamepad"];
  65388. if (gamepad)
  65389. gamepad.gamepadMoveSensibility = value;
  65390. },
  65391. enumerable: true,
  65392. configurable: true
  65393. });
  65394. GamepadCamera.prototype.getClassName = function () {
  65395. return "GamepadCamera";
  65396. };
  65397. return GamepadCamera;
  65398. }(BABYLON.UniversalCamera));
  65399. BABYLON.GamepadCamera = GamepadCamera;
  65400. })(BABYLON || (BABYLON = {}));
  65401. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65402. var BABYLON;
  65403. (function (BABYLON) {
  65404. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65405. function PostProcessRenderPipelineManager() {
  65406. this._renderPipelines = {};
  65407. }
  65408. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65409. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65410. };
  65411. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65412. if (unique === void 0) { unique = false; }
  65413. var renderPipeline = this._renderPipelines[renderPipelineName];
  65414. if (!renderPipeline) {
  65415. return;
  65416. }
  65417. renderPipeline._attachCameras(cameras, unique);
  65418. };
  65419. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65420. var renderPipeline = this._renderPipelines[renderPipelineName];
  65421. if (!renderPipeline) {
  65422. return;
  65423. }
  65424. renderPipeline._detachCameras(cameras);
  65425. };
  65426. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65427. var renderPipeline = this._renderPipelines[renderPipelineName];
  65428. if (!renderPipeline) {
  65429. return;
  65430. }
  65431. renderPipeline._enableEffect(renderEffectName, cameras);
  65432. };
  65433. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65434. var renderPipeline = this._renderPipelines[renderPipelineName];
  65435. if (!renderPipeline) {
  65436. return;
  65437. }
  65438. renderPipeline._disableEffect(renderEffectName, cameras);
  65439. };
  65440. PostProcessRenderPipelineManager.prototype.update = function () {
  65441. for (var renderPipelineName in this._renderPipelines) {
  65442. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65443. var pipeline = this._renderPipelines[renderPipelineName];
  65444. if (!pipeline.isSupported) {
  65445. pipeline.dispose();
  65446. delete this._renderPipelines[renderPipelineName];
  65447. }
  65448. else {
  65449. pipeline._update();
  65450. }
  65451. }
  65452. }
  65453. };
  65454. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65455. for (var renderPipelineName in this._renderPipelines) {
  65456. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65457. var pipeline = this._renderPipelines[renderPipelineName];
  65458. pipeline._rebuild();
  65459. }
  65460. }
  65461. };
  65462. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65463. for (var renderPipelineName in this._renderPipelines) {
  65464. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65465. var pipeline = this._renderPipelines[renderPipelineName];
  65466. pipeline.dispose();
  65467. }
  65468. }
  65469. };
  65470. return PostProcessRenderPipelineManager;
  65471. }());
  65472. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65473. })(BABYLON || (BABYLON = {}));
  65474. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65475. var BABYLON;
  65476. (function (BABYLON) {
  65477. /**
  65478. * This represents a set of one or more post processes in Babylon.
  65479. * A post process can be used to apply a shader to a texture after it is rendered.
  65480. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65481. */
  65482. var PostProcessRenderEffect = /** @class */ (function () {
  65483. /**
  65484. * Instantiates a post process render effect.
  65485. * A post process can be used to apply a shader to a texture after it is rendered.
  65486. * @param engine The engine the effect is tied to
  65487. * @param name The name of the effect
  65488. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65489. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65490. */
  65491. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65492. this._name = name;
  65493. this._singleInstance = singleInstance || true;
  65494. this._getPostProcesses = getPostProcesses;
  65495. this._cameras = {};
  65496. this._indicesForCamera = {};
  65497. this._postProcesses = {};
  65498. }
  65499. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65500. /**
  65501. * Checks if all the post processes in the effect are supported.
  65502. */
  65503. get: function () {
  65504. for (var index in this._postProcesses) {
  65505. for (var ppIndex in this._postProcesses[index]) {
  65506. if (!this._postProcesses[index][ppIndex].isSupported) {
  65507. return false;
  65508. }
  65509. }
  65510. }
  65511. return true;
  65512. },
  65513. enumerable: true,
  65514. configurable: true
  65515. });
  65516. /**
  65517. * Updates the current state of the effect
  65518. */
  65519. PostProcessRenderEffect.prototype._update = function () {
  65520. };
  65521. /**
  65522. * Attaches the effect on cameras
  65523. * @param cameras The camera to attach to.
  65524. */
  65525. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65526. var _this = this;
  65527. var cameraKey;
  65528. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65529. if (!cams) {
  65530. return;
  65531. }
  65532. for (var i = 0; i < cams.length; i++) {
  65533. var camera = cams[i];
  65534. var cameraName = camera.name;
  65535. if (this._singleInstance) {
  65536. cameraKey = 0;
  65537. }
  65538. else {
  65539. cameraKey = cameraName;
  65540. }
  65541. if (!this._postProcesses[cameraKey]) {
  65542. var postProcess = this._getPostProcesses();
  65543. if (postProcess) {
  65544. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65545. }
  65546. }
  65547. if (!this._indicesForCamera[cameraName]) {
  65548. this._indicesForCamera[cameraName] = [];
  65549. }
  65550. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65551. var index = camera.attachPostProcess(postProcess);
  65552. _this._indicesForCamera[cameraName].push(index);
  65553. });
  65554. if (!this._cameras[cameraName]) {
  65555. this._cameras[cameraName] = camera;
  65556. }
  65557. }
  65558. };
  65559. /**
  65560. * Detatches the effect on cameras
  65561. * @param cameras The camera to detatch from.
  65562. */
  65563. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65564. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65565. if (!cams) {
  65566. return;
  65567. }
  65568. for (var i = 0; i < cams.length; i++) {
  65569. var camera = cams[i];
  65570. var cameraName = camera.name;
  65571. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65572. camera.detachPostProcess(postProcess);
  65573. });
  65574. if (this._cameras[cameraName]) {
  65575. //this._indicesForCamera.splice(index, 1);
  65576. this._cameras[cameraName] = null;
  65577. }
  65578. }
  65579. };
  65580. /**
  65581. * Enables the effect on given cameras
  65582. * @param cameras The camera to enable.
  65583. */
  65584. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65585. var _this = this;
  65586. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65587. if (!cams) {
  65588. return;
  65589. }
  65590. for (var i = 0; i < cams.length; i++) {
  65591. var camera = cams[i];
  65592. var cameraName = camera.name;
  65593. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65594. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65595. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65596. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65597. });
  65598. }
  65599. }
  65600. }
  65601. };
  65602. /**
  65603. * Disables the effect on the given cameras
  65604. * @param cameras The camera to disable.
  65605. */
  65606. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65607. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65608. if (!cams) {
  65609. return;
  65610. }
  65611. for (var i = 0; i < cams.length; i++) {
  65612. var camera = cams[i];
  65613. var cameraName = camera.name;
  65614. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65615. camera.detachPostProcess(postProcess);
  65616. });
  65617. }
  65618. };
  65619. /**
  65620. * Gets a list of the post processes contained in the effect.
  65621. * @param camera The camera to get the post processes on.
  65622. * @returns The list of the post processes in the effect.
  65623. */
  65624. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65625. if (this._singleInstance) {
  65626. return this._postProcesses[0];
  65627. }
  65628. else {
  65629. if (!camera) {
  65630. return null;
  65631. }
  65632. return this._postProcesses[camera.name];
  65633. }
  65634. };
  65635. return PostProcessRenderEffect;
  65636. }());
  65637. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65638. })(BABYLON || (BABYLON = {}));
  65639. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65640. var BABYLON;
  65641. (function (BABYLON) {
  65642. var PostProcessRenderPipeline = /** @class */ (function () {
  65643. function PostProcessRenderPipeline(engine, name) {
  65644. this.engine = engine;
  65645. this._name = name;
  65646. this._renderEffects = {};
  65647. this._renderEffectsForIsolatedPass = new Array();
  65648. this._cameras = [];
  65649. }
  65650. PostProcessRenderPipeline.prototype.getClassName = function () {
  65651. return "PostProcessRenderPipeline";
  65652. };
  65653. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65654. get: function () {
  65655. for (var renderEffectName in this._renderEffects) {
  65656. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65657. if (!this._renderEffects[renderEffectName].isSupported) {
  65658. return false;
  65659. }
  65660. }
  65661. }
  65662. return true;
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65668. this._renderEffects[renderEffect._name] = renderEffect;
  65669. };
  65670. // private
  65671. PostProcessRenderPipeline.prototype._rebuild = function () {
  65672. };
  65673. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65674. var renderEffects = this._renderEffects[renderEffectName];
  65675. if (!renderEffects) {
  65676. return;
  65677. }
  65678. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65679. };
  65680. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65681. var renderEffects = this._renderEffects[renderEffectName];
  65682. if (!renderEffects) {
  65683. return;
  65684. }
  65685. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65686. };
  65687. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65688. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65689. if (!cams) {
  65690. return;
  65691. }
  65692. var indicesToDelete = [];
  65693. var i;
  65694. for (i = 0; i < cams.length; i++) {
  65695. var camera = cams[i];
  65696. var cameraName = camera.name;
  65697. if (this._cameras.indexOf(camera) === -1) {
  65698. this._cameras[cameraName] = camera;
  65699. }
  65700. else if (unique) {
  65701. indicesToDelete.push(i);
  65702. }
  65703. }
  65704. for (i = 0; i < indicesToDelete.length; i++) {
  65705. cameras.splice(indicesToDelete[i], 1);
  65706. }
  65707. for (var renderEffectName in this._renderEffects) {
  65708. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65709. this._renderEffects[renderEffectName]._attachCameras(cams);
  65710. }
  65711. }
  65712. };
  65713. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65714. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65715. if (!cams) {
  65716. return;
  65717. }
  65718. for (var renderEffectName in this._renderEffects) {
  65719. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65720. this._renderEffects[renderEffectName]._detachCameras(cams);
  65721. }
  65722. }
  65723. for (var i = 0; i < cams.length; i++) {
  65724. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65725. }
  65726. };
  65727. PostProcessRenderPipeline.prototype._update = function () {
  65728. for (var renderEffectName in this._renderEffects) {
  65729. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65730. this._renderEffects[renderEffectName]._update();
  65731. }
  65732. }
  65733. for (var i = 0; i < this._cameras.length; i++) {
  65734. var cameraName = this._cameras[i].name;
  65735. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65736. this._renderEffectsForIsolatedPass[cameraName]._update();
  65737. }
  65738. }
  65739. };
  65740. PostProcessRenderPipeline.prototype._reset = function () {
  65741. this._renderEffects = {};
  65742. this._renderEffectsForIsolatedPass = new Array();
  65743. };
  65744. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  65745. // 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)
  65746. var effectKeys = Object.keys(this._renderEffects);
  65747. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  65748. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  65749. if (postProcesses) {
  65750. postProcesses[0].samples = 4;
  65751. return true;
  65752. }
  65753. }
  65754. return false;
  65755. };
  65756. PostProcessRenderPipeline.prototype.dispose = function () {
  65757. // Must be implemented by children
  65758. };
  65759. __decorate([
  65760. BABYLON.serialize()
  65761. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65762. return PostProcessRenderPipeline;
  65763. }());
  65764. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65765. })(BABYLON || (BABYLON = {}));
  65766. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65767. var BABYLON;
  65768. (function (BABYLON) {
  65769. /**
  65770. * This represents a depth renderer in Babylon.
  65771. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  65772. */
  65773. var DepthRenderer = /** @class */ (function () {
  65774. /**
  65775. * Instantiates a depth renderer
  65776. * @param scene The scene the renderer belongs to
  65777. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  65778. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  65779. */
  65780. function DepthRenderer(scene, type, camera) {
  65781. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65782. if (camera === void 0) { camera = null; }
  65783. var _this = this;
  65784. this._scene = scene;
  65785. this._camera = camera;
  65786. var engine = scene.getEngine();
  65787. // Render target
  65788. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65789. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65790. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65791. this._depthMap.refreshRate = 1;
  65792. this._depthMap.renderParticles = false;
  65793. this._depthMap.renderList = null;
  65794. // Camera to get depth map from to support multiple concurrent cameras
  65795. this._depthMap.activeCamera = this._camera;
  65796. this._depthMap.ignoreCameraViewport = true;
  65797. this._depthMap.useCameraPostProcesses = false;
  65798. // set default depth value to 1.0 (far away)
  65799. this._depthMap.onClearObservable.add(function (engine) {
  65800. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65801. });
  65802. // Custom render function
  65803. var renderSubMesh = function (subMesh) {
  65804. var mesh = subMesh.getRenderingMesh();
  65805. var scene = _this._scene;
  65806. var engine = scene.getEngine();
  65807. var material = subMesh.getMaterial();
  65808. if (!material) {
  65809. return;
  65810. }
  65811. // Culling and reverse (right handed system)
  65812. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65813. // Managing instances
  65814. var batch = mesh._getInstancesRenderList(subMesh._id);
  65815. if (batch.mustReturn) {
  65816. return;
  65817. }
  65818. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65819. var camera = _this._camera || scene.activeCamera;
  65820. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  65821. engine.enableEffect(_this._effect);
  65822. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65823. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65824. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  65825. // Alpha test
  65826. if (material && material.needAlphaTesting()) {
  65827. var alphaTexture = material.getAlphaTestTexture();
  65828. if (alphaTexture) {
  65829. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65830. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65831. }
  65832. }
  65833. // Bones
  65834. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65835. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65836. }
  65837. // Draw
  65838. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65839. }
  65840. };
  65841. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65842. var index;
  65843. if (depthOnlySubMeshes.length) {
  65844. engine.setColorWrite(false);
  65845. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65846. renderSubMesh(depthOnlySubMeshes.data[index]);
  65847. }
  65848. engine.setColorWrite(true);
  65849. }
  65850. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65851. renderSubMesh(opaqueSubMeshes.data[index]);
  65852. }
  65853. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65854. renderSubMesh(alphaTestSubMeshes.data[index]);
  65855. }
  65856. };
  65857. }
  65858. /**
  65859. * Creates the depth rendering effect and checks if the effect is ready.
  65860. * @param subMesh The submesh to be used to render the depth map of
  65861. * @param useInstances If multiple world instances should be used
  65862. * @returns if the depth renderer is ready to render the depth map
  65863. */
  65864. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65865. var material = subMesh.getMaterial();
  65866. if (material.disableDepthWrite) {
  65867. return false;
  65868. }
  65869. var defines = [];
  65870. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65871. var mesh = subMesh.getMesh();
  65872. // Alpha test
  65873. if (material && material.needAlphaTesting()) {
  65874. defines.push("#define ALPHATEST");
  65875. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65876. attribs.push(BABYLON.VertexBuffer.UVKind);
  65877. defines.push("#define UV1");
  65878. }
  65879. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65880. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65881. defines.push("#define UV2");
  65882. }
  65883. }
  65884. // Bones
  65885. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65888. if (mesh.numBoneInfluencers > 4) {
  65889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65891. }
  65892. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65893. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65894. }
  65895. else {
  65896. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65897. }
  65898. // Instances
  65899. if (useInstances) {
  65900. defines.push("#define INSTANCES");
  65901. attribs.push("world0");
  65902. attribs.push("world1");
  65903. attribs.push("world2");
  65904. attribs.push("world3");
  65905. }
  65906. // Get correct effect
  65907. var join = defines.join("\n");
  65908. if (this._cachedDefines !== join) {
  65909. this._cachedDefines = join;
  65910. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65911. }
  65912. return this._effect.isReady();
  65913. };
  65914. /**
  65915. * Gets the texture which the depth map will be written to.
  65916. * @returns The depth map texture
  65917. */
  65918. DepthRenderer.prototype.getDepthMap = function () {
  65919. return this._depthMap;
  65920. };
  65921. /**
  65922. * Disposes of the depth renderer.
  65923. */
  65924. DepthRenderer.prototype.dispose = function () {
  65925. this._depthMap.dispose();
  65926. };
  65927. return DepthRenderer;
  65928. }());
  65929. BABYLON.DepthRenderer = DepthRenderer;
  65930. })(BABYLON || (BABYLON = {}));
  65931. //# sourceMappingURL=babylon.depthRenderer.js.map
  65932. var BABYLON;
  65933. (function (BABYLON) {
  65934. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65935. __extends(SSAORenderingPipeline, _super);
  65936. /**
  65937. * @constructor
  65938. * @param {string} name - The rendering pipeline name
  65939. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65940. * @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 }
  65941. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65942. */
  65943. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65944. var _this = _super.call(this, scene.getEngine(), name) || this;
  65945. // Members
  65946. /**
  65947. * The PassPostProcess id in the pipeline that contains the original scene color
  65948. * @type {string}
  65949. */
  65950. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65951. /**
  65952. * The SSAO PostProcess id in the pipeline
  65953. * @type {string}
  65954. */
  65955. _this.SSAORenderEffect = "SSAORenderEffect";
  65956. /**
  65957. * The horizontal blur PostProcess id in the pipeline
  65958. * @type {string}
  65959. */
  65960. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65961. /**
  65962. * The vertical blur PostProcess id in the pipeline
  65963. * @type {string}
  65964. */
  65965. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65966. /**
  65967. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65968. * @type {string}
  65969. */
  65970. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65971. /**
  65972. * The output strength of the SSAO post-process. Default value is 1.0.
  65973. * @type {number}
  65974. */
  65975. _this.totalStrength = 1.0;
  65976. /**
  65977. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65978. * @type {number}
  65979. */
  65980. _this.radius = 0.0001;
  65981. /**
  65982. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65983. * Must not be equal to fallOff and superior to fallOff.
  65984. * Default value is 0.975
  65985. * @type {number}
  65986. */
  65987. _this.area = 0.0075;
  65988. /**
  65989. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65990. * Must not be equal to area and inferior to area.
  65991. * Default value is 0.0
  65992. * @type {number}
  65993. */
  65994. _this.fallOff = 0.000001;
  65995. /**
  65996. * The base color of the SSAO post-process
  65997. * The final result is "base + ssao" between [0, 1]
  65998. * @type {number}
  65999. */
  66000. _this.base = 0.5;
  66001. _this._firstUpdate = true;
  66002. _this._scene = scene;
  66003. // Set up assets
  66004. _this._createRandomTexture();
  66005. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66006. var ssaoRatio = ratio.ssaoRatio || ratio;
  66007. var combineRatio = ratio.combineRatio || ratio;
  66008. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66009. _this._createSSAOPostProcess(ssaoRatio);
  66010. _this._createBlurPostProcess(ssaoRatio);
  66011. _this._createSSAOCombinePostProcess(combineRatio);
  66012. // Set up pipeline
  66013. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66014. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66015. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66016. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66017. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66018. // Finish
  66019. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66020. if (cameras)
  66021. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66022. return _this;
  66023. }
  66024. // Public Methods
  66025. /**
  66026. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66027. */
  66028. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66029. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66030. for (var i = 0; i < this._scene.cameras.length; i++) {
  66031. var camera = this._scene.cameras[i];
  66032. this._originalColorPostProcess.dispose(camera);
  66033. this._ssaoPostProcess.dispose(camera);
  66034. this._blurHPostProcess.dispose(camera);
  66035. this._blurVPostProcess.dispose(camera);
  66036. this._ssaoCombinePostProcess.dispose(camera);
  66037. }
  66038. this._randomTexture.dispose();
  66039. if (disableDepthRender)
  66040. this._scene.disableDepthRenderer();
  66041. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66042. _super.prototype.dispose.call(this);
  66043. };
  66044. // Private Methods
  66045. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66046. var _this = this;
  66047. var size = 16;
  66048. 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);
  66049. 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);
  66050. this._blurHPostProcess.onActivateObservable.add(function () {
  66051. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66052. _this._blurHPostProcess.kernel = size * dw;
  66053. });
  66054. this._blurVPostProcess.onActivateObservable.add(function () {
  66055. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66056. _this._blurVPostProcess.kernel = size * dw;
  66057. });
  66058. };
  66059. SSAORenderingPipeline.prototype._rebuild = function () {
  66060. this._firstUpdate = true;
  66061. _super.prototype._rebuild.call(this);
  66062. };
  66063. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66064. var _this = this;
  66065. var numSamples = 16;
  66066. var sampleSphere = [
  66067. 0.5381, 0.1856, -0.4319,
  66068. 0.1379, 0.2486, 0.4430,
  66069. 0.3371, 0.5679, -0.0057,
  66070. -0.6999, -0.0451, -0.0019,
  66071. 0.0689, -0.1598, -0.8547,
  66072. 0.0560, 0.0069, -0.1843,
  66073. -0.0146, 0.1402, 0.0762,
  66074. 0.0100, -0.1924, -0.0344,
  66075. -0.3577, -0.5301, -0.4358,
  66076. -0.3169, 0.1063, 0.0158,
  66077. 0.0103, -0.5869, 0.0046,
  66078. -0.0897, -0.4940, 0.3287,
  66079. 0.7119, -0.0154, -0.0918,
  66080. -0.0533, 0.0596, -0.5411,
  66081. 0.0352, -0.0631, 0.5460,
  66082. -0.4776, 0.2847, -0.0271
  66083. ];
  66084. var samplesFactor = 1.0 / numSamples;
  66085. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66086. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66087. "area", "fallOff", "base", "range", "viewport"
  66088. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66089. this._ssaoPostProcess.onApply = function (effect) {
  66090. if (_this._firstUpdate) {
  66091. effect.setArray3("sampleSphere", sampleSphere);
  66092. effect.setFloat("samplesFactor", samplesFactor);
  66093. effect.setFloat("randTextureTiles", 4.0);
  66094. }
  66095. effect.setFloat("totalStrength", _this.totalStrength);
  66096. effect.setFloat("radius", _this.radius);
  66097. effect.setFloat("area", _this.area);
  66098. effect.setFloat("fallOff", _this.fallOff);
  66099. effect.setFloat("base", _this.base);
  66100. effect.setTexture("textureSampler", _this._depthTexture);
  66101. effect.setTexture("randomSampler", _this._randomTexture);
  66102. };
  66103. };
  66104. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66105. var _this = this;
  66106. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66107. this._ssaoCombinePostProcess.onApply = function (effect) {
  66108. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66109. };
  66110. };
  66111. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66112. var size = 512;
  66113. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66114. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66115. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66116. var context = this._randomTexture.getContext();
  66117. var rand = function (min, max) {
  66118. return Math.random() * (max - min) + min;
  66119. };
  66120. var randVector = BABYLON.Vector3.Zero();
  66121. for (var x = 0; x < size; x++) {
  66122. for (var y = 0; y < size; y++) {
  66123. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66124. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66125. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66126. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66127. context.fillRect(x, y, 1, 1);
  66128. }
  66129. }
  66130. this._randomTexture.update(false);
  66131. };
  66132. __decorate([
  66133. BABYLON.serialize()
  66134. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66135. __decorate([
  66136. BABYLON.serialize()
  66137. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66138. __decorate([
  66139. BABYLON.serialize()
  66140. ], SSAORenderingPipeline.prototype, "area", void 0);
  66141. __decorate([
  66142. BABYLON.serialize()
  66143. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66144. __decorate([
  66145. BABYLON.serialize()
  66146. ], SSAORenderingPipeline.prototype, "base", void 0);
  66147. return SSAORenderingPipeline;
  66148. }(BABYLON.PostProcessRenderPipeline));
  66149. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66150. })(BABYLON || (BABYLON = {}));
  66151. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66152. var BABYLON;
  66153. (function (BABYLON) {
  66154. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66155. __extends(SSAO2RenderingPipeline, _super);
  66156. /**
  66157. * @constructor
  66158. * @param {string} name - The rendering pipeline name
  66159. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66160. * @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 }
  66161. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66162. */
  66163. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66164. var _this = _super.call(this, scene.getEngine(), name) || this;
  66165. // Members
  66166. /**
  66167. * The PassPostProcess id in the pipeline that contains the original scene color
  66168. * @type {string}
  66169. */
  66170. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66171. /**
  66172. * The SSAO PostProcess id in the pipeline
  66173. * @type {string}
  66174. */
  66175. _this.SSAORenderEffect = "SSAORenderEffect";
  66176. /**
  66177. * The horizontal blur PostProcess id in the pipeline
  66178. * @type {string}
  66179. */
  66180. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66181. /**
  66182. * The vertical blur PostProcess id in the pipeline
  66183. * @type {string}
  66184. */
  66185. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66186. /**
  66187. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66188. * @type {string}
  66189. */
  66190. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66191. /**
  66192. * The output strength of the SSAO post-process. Default value is 1.0.
  66193. * @type {number}
  66194. */
  66195. _this.totalStrength = 1.0;
  66196. /**
  66197. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66198. * @type {number}
  66199. */
  66200. _this.maxZ = 100.0;
  66201. /**
  66202. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66203. * @type {number}
  66204. */
  66205. _this.minZAspect = 0.2;
  66206. /**
  66207. * Number of samples used for the SSAO calculations. Default value is 8
  66208. * @type {number}
  66209. */
  66210. _this._samples = 8;
  66211. /**
  66212. * Are we using bilateral blur ?
  66213. * @type {boolean}
  66214. */
  66215. _this._expensiveBlur = true;
  66216. /**
  66217. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66218. * @type {number}
  66219. */
  66220. _this.radius = 2.0;
  66221. /**
  66222. * The base color of the SSAO post-process
  66223. * The final result is "base + ssao" between [0, 1]
  66224. * @type {number}
  66225. */
  66226. _this.base = 0.1;
  66227. _this._firstUpdate = true;
  66228. _this._scene = scene;
  66229. if (!_this.isSupported) {
  66230. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66231. return _this;
  66232. }
  66233. var ssaoRatio = ratio.ssaoRatio || ratio;
  66234. var blurRatio = ratio.blurRatio || ratio;
  66235. // Set up assets
  66236. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66237. _this._createRandomTexture();
  66238. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66239. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66240. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66241. _this._createSSAOPostProcess(1.0);
  66242. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66243. _this._createSSAOCombinePostProcess(blurRatio);
  66244. // Set up pipeline
  66245. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66246. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66247. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66248. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66249. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66250. // Finish
  66251. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66252. if (cameras)
  66253. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66254. return _this;
  66255. }
  66256. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66257. get: function () {
  66258. return this._samples;
  66259. },
  66260. set: function (n) {
  66261. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66262. this._samples = n;
  66263. this._sampleSphere = this._generateHemisphere();
  66264. this._firstUpdate = true;
  66265. },
  66266. enumerable: true,
  66267. configurable: true
  66268. });
  66269. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66270. get: function () {
  66271. return this._expensiveBlur;
  66272. },
  66273. set: function (b) {
  66274. 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"]);
  66275. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66276. this._expensiveBlur = b;
  66277. this._firstUpdate = true;
  66278. },
  66279. enumerable: true,
  66280. configurable: true
  66281. });
  66282. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66283. /**
  66284. * Support test.
  66285. * @type {boolean}
  66286. */
  66287. get: function () {
  66288. var engine = BABYLON.Engine.LastCreatedEngine;
  66289. if (!engine) {
  66290. return false;
  66291. }
  66292. return engine.getCaps().drawBuffersExtension;
  66293. },
  66294. enumerable: true,
  66295. configurable: true
  66296. });
  66297. // Public Methods
  66298. /**
  66299. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66300. */
  66301. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66302. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66303. for (var i = 0; i < this._scene.cameras.length; i++) {
  66304. var camera = this._scene.cameras[i];
  66305. this._originalColorPostProcess.dispose(camera);
  66306. this._ssaoPostProcess.dispose(camera);
  66307. this._blurHPostProcess.dispose(camera);
  66308. this._blurVPostProcess.dispose(camera);
  66309. this._ssaoCombinePostProcess.dispose(camera);
  66310. }
  66311. this._randomTexture.dispose();
  66312. if (disableGeometryBufferRenderer)
  66313. this._scene.disableGeometryBufferRenderer();
  66314. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66315. _super.prototype.dispose.call(this);
  66316. };
  66317. // Private Methods
  66318. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66319. var _this = this;
  66320. this._samplerOffsets = [];
  66321. var expensive = this.expensiveBlur;
  66322. for (var i = -8; i < 8; i++) {
  66323. this._samplerOffsets.push(i * 2 + 0.5);
  66324. }
  66325. 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");
  66326. this._blurHPostProcess.onApply = function (effect) {
  66327. if (!_this._scene.activeCamera) {
  66328. return;
  66329. }
  66330. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66331. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66332. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66333. effect.setFloat("radius", _this.radius);
  66334. effect.setTexture("depthSampler", _this._depthTexture);
  66335. if (_this._firstUpdate) {
  66336. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66337. }
  66338. };
  66339. 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");
  66340. this._blurVPostProcess.onApply = function (effect) {
  66341. if (!_this._scene.activeCamera) {
  66342. return;
  66343. }
  66344. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66345. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66346. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66347. effect.setFloat("radius", _this.radius);
  66348. effect.setTexture("depthSampler", _this._depthTexture);
  66349. if (_this._firstUpdate) {
  66350. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66351. _this._firstUpdate = false;
  66352. }
  66353. };
  66354. };
  66355. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66356. this._firstUpdate = true;
  66357. _super.prototype._rebuild.call(this);
  66358. };
  66359. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66360. var numSamples = this.samples;
  66361. var result = [];
  66362. var vector, scale;
  66363. var rand = function (min, max) {
  66364. return Math.random() * (max - min) + min;
  66365. };
  66366. var i = 0;
  66367. while (i < numSamples) {
  66368. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66369. vector.normalize();
  66370. scale = i / numSamples;
  66371. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66372. vector.scaleInPlace(scale);
  66373. result.push(vector.x, vector.y, vector.z);
  66374. i++;
  66375. }
  66376. return result;
  66377. };
  66378. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66379. var _this = this;
  66380. var numSamples = this.samples;
  66381. this._sampleSphere = this._generateHemisphere();
  66382. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66383. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66384. "base", "range", "projection", "near", "far", "texelSize",
  66385. "xViewport", "yViewport", "maxZ", "minZAspect"
  66386. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66387. this._ssaoPostProcess.onApply = function (effect) {
  66388. if (_this._firstUpdate) {
  66389. effect.setArray3("sampleSphere", _this._sampleSphere);
  66390. effect.setFloat("randTextureTiles", 4.0);
  66391. }
  66392. if (!_this._scene.activeCamera) {
  66393. return;
  66394. }
  66395. effect.setFloat("samplesFactor", 1 / _this.samples);
  66396. effect.setFloat("totalStrength", _this.totalStrength);
  66397. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66398. effect.setFloat("radius", _this.radius);
  66399. effect.setFloat("maxZ", _this.maxZ);
  66400. effect.setFloat("minZAspect", _this.minZAspect);
  66401. effect.setFloat("base", _this.base);
  66402. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66403. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66404. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66405. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66406. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66407. effect.setTexture("textureSampler", _this._depthTexture);
  66408. effect.setTexture("normalSampler", _this._normalTexture);
  66409. effect.setTexture("randomSampler", _this._randomTexture);
  66410. };
  66411. };
  66412. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66413. var _this = this;
  66414. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66415. this._ssaoCombinePostProcess.onApply = function (effect) {
  66416. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66417. };
  66418. };
  66419. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66420. var size = 512;
  66421. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66422. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66423. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66424. var context = this._randomTexture.getContext();
  66425. var rand = function (min, max) {
  66426. return Math.random() * (max - min) + min;
  66427. };
  66428. var randVector = BABYLON.Vector3.Zero();
  66429. for (var x = 0; x < size; x++) {
  66430. for (var y = 0; y < size; y++) {
  66431. randVector.x = rand(0.0, 1.0);
  66432. randVector.y = rand(0.0, 1.0);
  66433. randVector.z = 0.0;
  66434. randVector.normalize();
  66435. randVector.scaleInPlace(255);
  66436. randVector.x = Math.floor(randVector.x);
  66437. randVector.y = Math.floor(randVector.y);
  66438. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66439. context.fillRect(x, y, 1, 1);
  66440. }
  66441. }
  66442. this._randomTexture.update(false);
  66443. };
  66444. __decorate([
  66445. BABYLON.serialize()
  66446. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66447. __decorate([
  66448. BABYLON.serialize()
  66449. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66450. __decorate([
  66451. BABYLON.serialize()
  66452. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66453. __decorate([
  66454. BABYLON.serialize("samples")
  66455. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66456. __decorate([
  66457. BABYLON.serialize("expensiveBlur")
  66458. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66459. __decorate([
  66460. BABYLON.serialize()
  66461. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66462. __decorate([
  66463. BABYLON.serialize()
  66464. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66465. return SSAO2RenderingPipeline;
  66466. }(BABYLON.PostProcessRenderPipeline));
  66467. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66468. })(BABYLON || (BABYLON = {}));
  66469. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66470. // BABYLON.JS Chromatic Aberration GLSL Shader
  66471. // Author: Olivier Guyot
  66472. // Separates very slightly R, G and B colors on the edges of the screen
  66473. // Inspired by Francois Tarlier & Martins Upitis
  66474. var BABYLON;
  66475. (function (BABYLON) {
  66476. var LensRenderingPipeline = /** @class */ (function (_super) {
  66477. __extends(LensRenderingPipeline, _super);
  66478. /**
  66479. * @constructor
  66480. *
  66481. * Effect parameters are as follow:
  66482. * {
  66483. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66484. * edge_blur: number; // from 0 to x (1 for realism)
  66485. * distortion: number; // from 0 to x (1 for realism)
  66486. * grain_amount: number; // from 0 to 1
  66487. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66488. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66489. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66490. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66491. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66492. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66493. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66494. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66495. * }
  66496. * Note: if an effect parameter is unset, effect is disabled
  66497. *
  66498. * @param {string} name - The rendering pipeline name
  66499. * @param {object} parameters - An object containing all parameters (see above)
  66500. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66501. * @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)
  66502. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66503. */
  66504. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66505. if (ratio === void 0) { ratio = 1.0; }
  66506. var _this = _super.call(this, scene.getEngine(), name) || this;
  66507. // Lens effects can be of the following:
  66508. // - chromatic aberration (slight shift of RGB colors)
  66509. // - blur on the edge of the lens
  66510. // - lens distortion
  66511. // - depth-of-field blur & highlights enhancing
  66512. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66513. // - grain effect (noise or custom texture)
  66514. // Two additional texture samplers are needed:
  66515. // - depth map (for depth-of-field)
  66516. // - grain texture
  66517. /**
  66518. * The chromatic aberration PostProcess id in the pipeline
  66519. * @type {string}
  66520. */
  66521. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66522. /**
  66523. * The highlights enhancing PostProcess id in the pipeline
  66524. * @type {string}
  66525. */
  66526. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66527. /**
  66528. * The depth-of-field PostProcess id in the pipeline
  66529. * @type {string}
  66530. */
  66531. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66532. _this._scene = scene;
  66533. // Fetch texture samplers
  66534. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66535. if (parameters.grain_texture) {
  66536. _this._grainTexture = parameters.grain_texture;
  66537. }
  66538. else {
  66539. _this._createGrainTexture();
  66540. }
  66541. // save parameters
  66542. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66543. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66544. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66545. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66546. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66547. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66548. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66549. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66550. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66551. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66552. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66553. // Create effects
  66554. _this._createChromaticAberrationPostProcess(ratio);
  66555. _this._createHighlightsPostProcess(ratio);
  66556. _this._createDepthOfFieldPostProcess(ratio / 4);
  66557. // Set up pipeline
  66558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66559. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66561. if (_this._highlightsGain === -1) {
  66562. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66563. }
  66564. // Finish
  66565. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66566. if (cameras) {
  66567. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66568. }
  66569. return _this;
  66570. }
  66571. // public methods (self explanatory)
  66572. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66573. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66574. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66575. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66576. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66577. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66578. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66579. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66580. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66581. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66582. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66583. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66584. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66585. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66586. };
  66587. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66588. this._highlightsPostProcess.updateEffect();
  66589. };
  66590. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66591. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66592. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66593. this._highlightsGain = amount;
  66594. };
  66595. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66596. if (this._highlightsGain === -1) {
  66597. this._highlightsGain = 1.0;
  66598. }
  66599. this._highlightsThreshold = amount;
  66600. };
  66601. LensRenderingPipeline.prototype.disableHighlights = function () {
  66602. this._highlightsGain = -1;
  66603. };
  66604. /**
  66605. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66606. */
  66607. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66608. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66609. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66610. this._chromaticAberrationPostProcess = null;
  66611. this._highlightsPostProcess = null;
  66612. this._depthOfFieldPostProcess = null;
  66613. this._grainTexture.dispose();
  66614. if (disableDepthRender)
  66615. this._scene.disableDepthRenderer();
  66616. };
  66617. // colors shifting and distortion
  66618. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66619. var _this = this;
  66620. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66621. [], // samplers
  66622. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66623. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66624. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66625. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66626. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66627. };
  66628. };
  66629. // highlights enhancing
  66630. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66631. var _this = this;
  66632. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66633. [], // samplers
  66634. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66635. this._highlightsPostProcess.onApply = function (effect) {
  66636. effect.setFloat('gain', _this._highlightsGain);
  66637. effect.setFloat('threshold', _this._highlightsThreshold);
  66638. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66639. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66640. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66641. };
  66642. };
  66643. // colors shifting and distortion
  66644. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66645. var _this = this;
  66646. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66647. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66648. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66649. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66650. this._depthOfFieldPostProcess.onApply = function (effect) {
  66651. effect.setTexture("depthSampler", _this._depthTexture);
  66652. effect.setTexture("grainSampler", _this._grainTexture);
  66653. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66654. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66655. effect.setFloat('grain_amount', _this._grainAmount);
  66656. effect.setBool('blur_noise', _this._blurNoise);
  66657. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66658. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66659. effect.setFloat('distortion', _this._distortion);
  66660. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66661. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66662. effect.setFloat('aperture', _this._dofAperture);
  66663. effect.setFloat('darken', _this._dofDarken);
  66664. effect.setFloat('edge_blur', _this._edgeBlur);
  66665. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66666. if (_this._scene.activeCamera) {
  66667. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66668. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66669. }
  66670. };
  66671. };
  66672. // creates a black and white random noise texture, 512x512
  66673. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66674. var size = 512;
  66675. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66676. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66677. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66678. var context = this._grainTexture.getContext();
  66679. var rand = function (min, max) {
  66680. return Math.random() * (max - min) + min;
  66681. };
  66682. var value;
  66683. for (var x = 0; x < size; x++) {
  66684. for (var y = 0; y < size; y++) {
  66685. value = Math.floor(rand(0.42, 0.58) * 255);
  66686. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66687. context.fillRect(x, y, 1, 1);
  66688. }
  66689. }
  66690. this._grainTexture.update(false);
  66691. };
  66692. return LensRenderingPipeline;
  66693. }(BABYLON.PostProcessRenderPipeline));
  66694. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66695. })(BABYLON || (BABYLON = {}));
  66696. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66697. var BABYLON;
  66698. (function (BABYLON) {
  66699. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66700. __extends(StandardRenderingPipeline, _super);
  66701. /**
  66702. * @constructor
  66703. * @param {string} name - The rendering pipeline name
  66704. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66705. * @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)
  66706. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66707. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66708. */
  66709. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66710. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66711. var _this = _super.call(this, scene.getEngine(), name) || this;
  66712. _this.downSampleX4PostProcess = null;
  66713. _this.brightPassPostProcess = null;
  66714. _this.blurHPostProcesses = [];
  66715. _this.blurVPostProcesses = [];
  66716. _this.textureAdderPostProcess = null;
  66717. _this.volumetricLightPostProcess = null;
  66718. _this.volumetricLightSmoothXPostProcess = null;
  66719. _this.volumetricLightSmoothYPostProcess = null;
  66720. _this.volumetricLightMergePostProces = null;
  66721. _this.volumetricLightFinalPostProcess = null;
  66722. _this.luminancePostProcess = null;
  66723. _this.luminanceDownSamplePostProcesses = [];
  66724. _this.hdrPostProcess = null;
  66725. _this.textureAdderFinalPostProcess = null;
  66726. _this.lensFlareFinalPostProcess = null;
  66727. _this.hdrFinalPostProcess = null;
  66728. _this.lensFlarePostProcess = null;
  66729. _this.lensFlareComposePostProcess = null;
  66730. _this.motionBlurPostProcess = null;
  66731. _this.depthOfFieldPostProcess = null;
  66732. // Values
  66733. _this.brightThreshold = 1.0;
  66734. _this.blurWidth = 512.0;
  66735. _this.horizontalBlur = false;
  66736. _this.exposure = 1.0;
  66737. _this.lensTexture = null;
  66738. _this.volumetricLightCoefficient = 0.2;
  66739. _this.volumetricLightPower = 4.0;
  66740. _this.volumetricLightBlurScale = 64.0;
  66741. _this.sourceLight = null;
  66742. _this.hdrMinimumLuminance = 1.0;
  66743. _this.hdrDecreaseRate = 0.5;
  66744. _this.hdrIncreaseRate = 0.5;
  66745. _this.lensColorTexture = null;
  66746. _this.lensFlareStrength = 20.0;
  66747. _this.lensFlareGhostDispersal = 1.4;
  66748. _this.lensFlareHaloWidth = 0.7;
  66749. _this.lensFlareDistortionStrength = 16.0;
  66750. _this.lensStarTexture = null;
  66751. _this.lensFlareDirtTexture = null;
  66752. _this.depthOfFieldDistance = 10.0;
  66753. _this.depthOfFieldBlurWidth = 64.0;
  66754. _this.motionStrength = 1.0;
  66755. // IAnimatable
  66756. _this.animations = [];
  66757. _this._currentDepthOfFieldSource = null;
  66758. _this._hdrCurrentLuminance = 1.0;
  66759. // Getters and setters
  66760. _this._bloomEnabled = true;
  66761. _this._depthOfFieldEnabled = false;
  66762. _this._vlsEnabled = false;
  66763. _this._lensFlareEnabled = false;
  66764. _this._hdrEnabled = false;
  66765. _this._motionBlurEnabled = false;
  66766. _this._motionBlurSamples = 64.0;
  66767. _this._volumetricLightStepsCount = 50.0;
  66768. _this._cameras = cameras || [];
  66769. // Initialize
  66770. _this._scene = scene;
  66771. _this._basePostProcess = originalPostProcess;
  66772. _this._ratio = ratio;
  66773. // Misc
  66774. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66775. // Finish
  66776. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66777. _this._buildPipeline();
  66778. return _this;
  66779. }
  66780. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66781. get: function () {
  66782. return this._bloomEnabled;
  66783. },
  66784. set: function (enabled) {
  66785. if (this._bloomEnabled === enabled) {
  66786. return;
  66787. }
  66788. this._bloomEnabled = enabled;
  66789. this._buildPipeline();
  66790. },
  66791. enumerable: true,
  66792. configurable: true
  66793. });
  66794. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66795. get: function () {
  66796. return this._depthOfFieldEnabled;
  66797. },
  66798. set: function (enabled) {
  66799. if (this._depthOfFieldEnabled === enabled) {
  66800. return;
  66801. }
  66802. this._depthOfFieldEnabled = enabled;
  66803. this._buildPipeline();
  66804. },
  66805. enumerable: true,
  66806. configurable: true
  66807. });
  66808. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66809. get: function () {
  66810. return this._lensFlareEnabled;
  66811. },
  66812. set: function (enabled) {
  66813. if (this._lensFlareEnabled === enabled) {
  66814. return;
  66815. }
  66816. this._lensFlareEnabled = enabled;
  66817. this._buildPipeline();
  66818. },
  66819. enumerable: true,
  66820. configurable: true
  66821. });
  66822. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66823. get: function () {
  66824. return this._hdrEnabled;
  66825. },
  66826. set: function (enabled) {
  66827. if (this._hdrEnabled === enabled) {
  66828. return;
  66829. }
  66830. this._hdrEnabled = enabled;
  66831. this._buildPipeline();
  66832. },
  66833. enumerable: true,
  66834. configurable: true
  66835. });
  66836. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66837. get: function () {
  66838. return this._vlsEnabled;
  66839. },
  66840. set: function (enabled) {
  66841. if (this._vlsEnabled === enabled) {
  66842. return;
  66843. }
  66844. if (enabled) {
  66845. var geometry = this._scene.enableGeometryBufferRenderer();
  66846. if (!geometry) {
  66847. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66848. return;
  66849. }
  66850. }
  66851. this._vlsEnabled = enabled;
  66852. this._buildPipeline();
  66853. },
  66854. enumerable: true,
  66855. configurable: true
  66856. });
  66857. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66858. get: function () {
  66859. return this._motionBlurEnabled;
  66860. },
  66861. set: function (enabled) {
  66862. if (this._motionBlurEnabled === enabled) {
  66863. return;
  66864. }
  66865. this._motionBlurEnabled = enabled;
  66866. this._buildPipeline();
  66867. },
  66868. enumerable: true,
  66869. configurable: true
  66870. });
  66871. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66872. get: function () {
  66873. return this._volumetricLightStepsCount;
  66874. },
  66875. set: function (count) {
  66876. if (this.volumetricLightPostProcess) {
  66877. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66878. }
  66879. this._volumetricLightStepsCount = count;
  66880. },
  66881. enumerable: true,
  66882. configurable: true
  66883. });
  66884. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66885. get: function () {
  66886. return this._motionBlurSamples;
  66887. },
  66888. set: function (samples) {
  66889. if (this.motionBlurPostProcess) {
  66890. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66891. }
  66892. this._motionBlurSamples = samples;
  66893. },
  66894. enumerable: true,
  66895. configurable: true
  66896. });
  66897. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66898. var _this = this;
  66899. var ratio = this._ratio;
  66900. var scene = this._scene;
  66901. this._disposePostProcesses();
  66902. this._reset();
  66903. // Create pass post-process
  66904. if (!this._basePostProcess) {
  66905. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66906. this.originalPostProcess.onApply = function (effect) {
  66907. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66908. };
  66909. }
  66910. else {
  66911. this.originalPostProcess = this._basePostProcess;
  66912. }
  66913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66914. this._currentDepthOfFieldSource = this.originalPostProcess;
  66915. if (this._vlsEnabled) {
  66916. // Create volumetric light
  66917. this._createVolumetricLightPostProcess(scene, ratio);
  66918. // Create volumetric light final post-process
  66919. 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);
  66920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66921. }
  66922. if (this._bloomEnabled) {
  66923. // Create down sample X4 post-process
  66924. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66925. // Create bright pass post-process
  66926. this._createBrightPassPostProcess(scene, ratio / 2);
  66927. // Create gaussian blur post-processes (down sampling blurs)
  66928. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66929. // Create texture adder post-process
  66930. this._createTextureAdderPostProcess(scene, ratio);
  66931. // Create depth-of-field source post-process
  66932. 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);
  66933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66934. }
  66935. if (this._lensFlareEnabled) {
  66936. // Create lens flare post-process
  66937. this._createLensFlarePostProcess(scene, ratio);
  66938. // Create depth-of-field source post-process post lens-flare and disable it now
  66939. 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);
  66940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66941. }
  66942. if (this._hdrEnabled) {
  66943. // Create luminance
  66944. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66945. // Create HDR
  66946. this._createHdrPostProcess(scene, ratio);
  66947. // Create depth-of-field source post-process post hdr and disable it now
  66948. 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);
  66949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66950. }
  66951. if (this._depthOfFieldEnabled) {
  66952. // Create gaussian blur used by depth-of-field
  66953. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66954. // Create depth-of-field post-process
  66955. this._createDepthOfFieldPostProcess(scene, ratio);
  66956. }
  66957. if (this._motionBlurEnabled) {
  66958. // Create motion blur post-process
  66959. this._createMotionBlurPostProcess(scene, ratio);
  66960. }
  66961. if (this._cameras !== null) {
  66962. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66963. }
  66964. };
  66965. // Down Sample X4 Post-Processs
  66966. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66967. var _this = this;
  66968. var downSampleX4Offsets = new Array(32);
  66969. 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);
  66970. this.downSampleX4PostProcess.onApply = function (effect) {
  66971. var id = 0;
  66972. var width = _this.downSampleX4PostProcess.width;
  66973. var height = _this.downSampleX4PostProcess.height;
  66974. for (var i = -2; i < 2; i++) {
  66975. for (var j = -2; j < 2; j++) {
  66976. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66977. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66978. id += 2;
  66979. }
  66980. }
  66981. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66982. };
  66983. // Add to pipeline
  66984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66985. };
  66986. // Brightpass Post-Process
  66987. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66988. var _this = this;
  66989. var brightOffsets = new Array(8);
  66990. 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);
  66991. this.brightPassPostProcess.onApply = function (effect) {
  66992. var sU = (1.0 / _this.brightPassPostProcess.width);
  66993. var sV = (1.0 / _this.brightPassPostProcess.height);
  66994. brightOffsets[0] = -0.5 * sU;
  66995. brightOffsets[1] = 0.5 * sV;
  66996. brightOffsets[2] = 0.5 * sU;
  66997. brightOffsets[3] = 0.5 * sV;
  66998. brightOffsets[4] = -0.5 * sU;
  66999. brightOffsets[5] = -0.5 * sV;
  67000. brightOffsets[6] = 0.5 * sU;
  67001. brightOffsets[7] = -0.5 * sV;
  67002. effect.setArray2("dsOffsets", brightOffsets);
  67003. effect.setFloat("brightThreshold", _this.brightThreshold);
  67004. };
  67005. // Add to pipeline
  67006. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67007. };
  67008. // Create blur H&V post-processes
  67009. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67010. var _this = this;
  67011. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67012. var engine = scene.getEngine();
  67013. 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);
  67014. 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);
  67015. blurX.onActivateObservable.add(function () {
  67016. var dw = blurX.width / engine.getRenderWidth();
  67017. blurX.kernel = _this[blurWidthKey] * dw;
  67018. });
  67019. blurY.onActivateObservable.add(function () {
  67020. var dw = blurY.height / engine.getRenderHeight();
  67021. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67022. });
  67023. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67025. this.blurHPostProcesses.push(blurX);
  67026. this.blurVPostProcesses.push(blurY);
  67027. };
  67028. // Create texture adder post-process
  67029. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67030. var _this = this;
  67031. 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);
  67032. this.textureAdderPostProcess.onApply = function (effect) {
  67033. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67034. effect.setTexture("lensSampler", _this.lensTexture);
  67035. effect.setFloat("exposure", _this.exposure);
  67036. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67037. };
  67038. // Add to pipeline
  67039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67040. };
  67041. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67042. var _this = this;
  67043. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67044. geometryRenderer.enablePosition = true;
  67045. var geometry = geometryRenderer.getGBuffer();
  67046. // Base post-process
  67047. 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));
  67048. var depthValues = BABYLON.Vector2.Zero();
  67049. this.volumetricLightPostProcess.onApply = function (effect) {
  67050. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67051. var generator = _this.sourceLight.getShadowGenerator();
  67052. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67053. effect.setTexture("positionSampler", geometry.textures[2]);
  67054. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67055. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67056. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67057. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67058. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67059. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67060. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67061. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67062. effect.setVector2("depthValues", depthValues);
  67063. }
  67064. };
  67065. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67066. // Smooth
  67067. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67068. // Merge
  67069. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67070. this.volumetricLightMergePostProces.onApply = function (effect) {
  67071. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67072. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67073. };
  67074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67075. };
  67076. // Create luminance
  67077. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67078. var _this = this;
  67079. // Create luminance
  67080. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67081. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67082. var offsets = [];
  67083. this.luminancePostProcess.onApply = function (effect) {
  67084. var sU = (1.0 / _this.luminancePostProcess.width);
  67085. var sV = (1.0 / _this.luminancePostProcess.height);
  67086. offsets[0] = -0.5 * sU;
  67087. offsets[1] = 0.5 * sV;
  67088. offsets[2] = 0.5 * sU;
  67089. offsets[3] = 0.5 * sV;
  67090. offsets[4] = -0.5 * sU;
  67091. offsets[5] = -0.5 * sV;
  67092. offsets[6] = 0.5 * sU;
  67093. offsets[7] = -0.5 * sV;
  67094. effect.setArray2("lumOffsets", offsets);
  67095. };
  67096. // Add to pipeline
  67097. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67098. // Create down sample luminance
  67099. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67100. var size = Math.pow(3, i);
  67101. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67102. if (i === 0) {
  67103. defines += "#define FINAL_DOWN_SAMPLER";
  67104. }
  67105. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67106. this.luminanceDownSamplePostProcesses.push(postProcess);
  67107. }
  67108. // Create callbacks and add effects
  67109. var lastLuminance = this.luminancePostProcess;
  67110. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67111. var downSampleOffsets = new Array(18);
  67112. pp.onApply = function (effect) {
  67113. if (!lastLuminance) {
  67114. return;
  67115. }
  67116. var id = 0;
  67117. for (var x = -1; x < 2; x++) {
  67118. for (var y = -1; y < 2; y++) {
  67119. downSampleOffsets[id] = x / lastLuminance.width;
  67120. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67121. id += 2;
  67122. }
  67123. }
  67124. effect.setArray2("dsOffsets", downSampleOffsets);
  67125. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67126. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67127. lastLuminance = _this.luminancePostProcess;
  67128. }
  67129. else {
  67130. lastLuminance = pp;
  67131. }
  67132. };
  67133. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67134. pp.onAfterRender = function (effect) {
  67135. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67136. 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);
  67137. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67138. };
  67139. }
  67140. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67141. });
  67142. };
  67143. // Create HDR post-process
  67144. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67145. var _this = this;
  67146. 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);
  67147. var outputLiminance = 1;
  67148. var time = 0;
  67149. var lastTime = 0;
  67150. this.hdrPostProcess.onApply = function (effect) {
  67151. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67152. time += scene.getEngine().getDeltaTime();
  67153. if (outputLiminance < 0) {
  67154. outputLiminance = _this._hdrCurrentLuminance;
  67155. }
  67156. else {
  67157. var dt = (lastTime - time) / 1000.0;
  67158. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67159. outputLiminance += _this.hdrDecreaseRate * dt;
  67160. }
  67161. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67162. outputLiminance -= _this.hdrIncreaseRate * dt;
  67163. }
  67164. else {
  67165. outputLiminance = _this._hdrCurrentLuminance;
  67166. }
  67167. }
  67168. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67169. effect.setFloat("averageLuminance", outputLiminance);
  67170. lastTime = time;
  67171. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67172. };
  67173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67174. };
  67175. // Create lens flare post-process
  67176. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67177. var _this = this;
  67178. 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);
  67179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67180. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67181. 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);
  67182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67183. var resolution = new BABYLON.Vector2(0, 0);
  67184. // Lens flare
  67185. this.lensFlarePostProcess.onApply = function (effect) {
  67186. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67187. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67188. effect.setFloat("strength", _this.lensFlareStrength);
  67189. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67190. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67191. // Shift
  67192. resolution.x = _this.lensFlarePostProcess.width;
  67193. resolution.y = _this.lensFlarePostProcess.height;
  67194. effect.setVector2("resolution", resolution);
  67195. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67196. };
  67197. // Compose
  67198. 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);
  67199. 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);
  67200. this.lensFlareComposePostProcess.onApply = function (effect) {
  67201. if (!_this._scene.activeCamera) {
  67202. return;
  67203. }
  67204. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67205. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67206. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67207. // Lens start rotation matrix
  67208. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67209. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67210. 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));
  67211. camRot *= 4.0;
  67212. 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);
  67213. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67214. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67215. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67216. };
  67217. };
  67218. // Create depth-of-field post-process
  67219. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67220. var _this = this;
  67221. 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);
  67222. this.depthOfFieldPostProcess.onApply = function (effect) {
  67223. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67224. effect.setTexture("depthSampler", _this._getDepthTexture());
  67225. effect.setFloat("distance", _this.depthOfFieldDistance);
  67226. };
  67227. // Add to pipeline
  67228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67229. };
  67230. // Create motion blur post-process
  67231. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67232. var _this = this;
  67233. 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);
  67234. var motionScale = 0;
  67235. var prevViewProjection = BABYLON.Matrix.Identity();
  67236. var invViewProjection = BABYLON.Matrix.Identity();
  67237. var viewProjection = BABYLON.Matrix.Identity();
  67238. var screenSize = BABYLON.Vector2.Zero();
  67239. this.motionBlurPostProcess.onApply = function (effect) {
  67240. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67241. viewProjection.invertToRef(invViewProjection);
  67242. effect.setMatrix("inverseViewProjection", invViewProjection);
  67243. effect.setMatrix("prevViewProjection", prevViewProjection);
  67244. prevViewProjection = viewProjection;
  67245. screenSize.x = _this.motionBlurPostProcess.width;
  67246. screenSize.y = _this.motionBlurPostProcess.height;
  67247. effect.setVector2("screenSize", screenSize);
  67248. motionScale = scene.getEngine().getFps() / 60.0;
  67249. effect.setFloat("motionScale", motionScale);
  67250. effect.setFloat("motionStrength", _this.motionStrength);
  67251. effect.setTexture("depthSampler", _this._getDepthTexture());
  67252. };
  67253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67254. };
  67255. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67256. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67257. var renderer = this._scene.enableGeometryBufferRenderer();
  67258. return renderer.getGBuffer().textures[0];
  67259. }
  67260. return this._scene.enableDepthRenderer().getDepthMap();
  67261. };
  67262. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67263. for (var i = 0; i < this._cameras.length; i++) {
  67264. var camera = this._cameras[i];
  67265. if (this.originalPostProcess) {
  67266. this.originalPostProcess.dispose(camera);
  67267. }
  67268. if (this.downSampleX4PostProcess) {
  67269. this.downSampleX4PostProcess.dispose(camera);
  67270. }
  67271. if (this.brightPassPostProcess) {
  67272. this.brightPassPostProcess.dispose(camera);
  67273. }
  67274. if (this.textureAdderPostProcess) {
  67275. this.textureAdderPostProcess.dispose(camera);
  67276. }
  67277. if (this.textureAdderFinalPostProcess) {
  67278. this.textureAdderFinalPostProcess.dispose(camera);
  67279. }
  67280. if (this.volumetricLightPostProcess) {
  67281. this.volumetricLightPostProcess.dispose(camera);
  67282. }
  67283. if (this.volumetricLightSmoothXPostProcess) {
  67284. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67285. }
  67286. if (this.volumetricLightSmoothYPostProcess) {
  67287. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67288. }
  67289. if (this.volumetricLightMergePostProces) {
  67290. this.volumetricLightMergePostProces.dispose(camera);
  67291. }
  67292. if (this.volumetricLightFinalPostProcess) {
  67293. this.volumetricLightFinalPostProcess.dispose(camera);
  67294. }
  67295. if (this.lensFlarePostProcess) {
  67296. this.lensFlarePostProcess.dispose(camera);
  67297. }
  67298. if (this.lensFlareComposePostProcess) {
  67299. this.lensFlareComposePostProcess.dispose(camera);
  67300. }
  67301. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67302. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67303. }
  67304. if (this.luminancePostProcess) {
  67305. this.luminancePostProcess.dispose(camera);
  67306. }
  67307. if (this.hdrPostProcess) {
  67308. this.hdrPostProcess.dispose(camera);
  67309. }
  67310. if (this.hdrFinalPostProcess) {
  67311. this.hdrFinalPostProcess.dispose(camera);
  67312. }
  67313. if (this.depthOfFieldPostProcess) {
  67314. this.depthOfFieldPostProcess.dispose(camera);
  67315. }
  67316. if (this.motionBlurPostProcess) {
  67317. this.motionBlurPostProcess.dispose(camera);
  67318. }
  67319. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67320. this.blurHPostProcesses[j].dispose(camera);
  67321. }
  67322. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67323. this.blurVPostProcesses[j].dispose(camera);
  67324. }
  67325. }
  67326. this.originalPostProcess = null;
  67327. this.downSampleX4PostProcess = null;
  67328. this.brightPassPostProcess = null;
  67329. this.textureAdderPostProcess = null;
  67330. this.textureAdderFinalPostProcess = null;
  67331. this.volumetricLightPostProcess = null;
  67332. this.volumetricLightSmoothXPostProcess = null;
  67333. this.volumetricLightSmoothYPostProcess = null;
  67334. this.volumetricLightMergePostProces = null;
  67335. this.volumetricLightFinalPostProcess = null;
  67336. this.lensFlarePostProcess = null;
  67337. this.lensFlareComposePostProcess = null;
  67338. this.luminancePostProcess = null;
  67339. this.hdrPostProcess = null;
  67340. this.hdrFinalPostProcess = null;
  67341. this.depthOfFieldPostProcess = null;
  67342. this.motionBlurPostProcess = null;
  67343. this.luminanceDownSamplePostProcesses = [];
  67344. this.blurHPostProcesses = [];
  67345. this.blurVPostProcesses = [];
  67346. };
  67347. // Dispose
  67348. StandardRenderingPipeline.prototype.dispose = function () {
  67349. this._disposePostProcesses();
  67350. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67351. _super.prototype.dispose.call(this);
  67352. };
  67353. // Serialize rendering pipeline
  67354. StandardRenderingPipeline.prototype.serialize = function () {
  67355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67356. serializationObject.customType = "StandardRenderingPipeline";
  67357. return serializationObject;
  67358. };
  67359. /**
  67360. * Static members
  67361. */
  67362. // Parse serialized pipeline
  67363. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67364. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67365. };
  67366. // Luminance steps
  67367. StandardRenderingPipeline.LuminanceSteps = 6;
  67368. __decorate([
  67369. BABYLON.serialize()
  67370. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67371. __decorate([
  67372. BABYLON.serialize()
  67373. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67374. __decorate([
  67375. BABYLON.serialize()
  67376. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67377. __decorate([
  67378. BABYLON.serialize()
  67379. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67380. __decorate([
  67381. BABYLON.serializeAsTexture("lensTexture")
  67382. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67383. __decorate([
  67384. BABYLON.serialize()
  67385. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67386. __decorate([
  67387. BABYLON.serialize()
  67388. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67389. __decorate([
  67390. BABYLON.serialize()
  67391. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67392. __decorate([
  67393. BABYLON.serialize()
  67394. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67395. __decorate([
  67396. BABYLON.serialize()
  67397. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67398. __decorate([
  67399. BABYLON.serialize()
  67400. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67401. __decorate([
  67402. BABYLON.serializeAsTexture("lensColorTexture")
  67403. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67404. __decorate([
  67405. BABYLON.serialize()
  67406. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67407. __decorate([
  67408. BABYLON.serialize()
  67409. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67410. __decorate([
  67411. BABYLON.serialize()
  67412. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67413. __decorate([
  67414. BABYLON.serialize()
  67415. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67416. __decorate([
  67417. BABYLON.serializeAsTexture("lensStarTexture")
  67418. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67419. __decorate([
  67420. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67421. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67422. __decorate([
  67423. BABYLON.serialize()
  67424. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67425. __decorate([
  67426. BABYLON.serialize()
  67427. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67428. __decorate([
  67429. BABYLON.serialize()
  67430. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67431. __decorate([
  67432. BABYLON.serialize()
  67433. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67434. __decorate([
  67435. BABYLON.serialize()
  67436. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67437. __decorate([
  67438. BABYLON.serialize()
  67439. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67440. __decorate([
  67441. BABYLON.serialize()
  67442. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67443. __decorate([
  67444. BABYLON.serialize()
  67445. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67446. __decorate([
  67447. BABYLON.serialize()
  67448. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67449. __decorate([
  67450. BABYLON.serialize()
  67451. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67452. __decorate([
  67453. BABYLON.serialize()
  67454. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67455. __decorate([
  67456. BABYLON.serialize()
  67457. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67458. return StandardRenderingPipeline;
  67459. }(BABYLON.PostProcessRenderPipeline));
  67460. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67461. })(BABYLON || (BABYLON = {}));
  67462. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67463. var BABYLON;
  67464. (function (BABYLON) {
  67465. var FxaaPostProcess = /** @class */ (function (_super) {
  67466. __extends(FxaaPostProcess, _super);
  67467. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67468. if (camera === void 0) { camera = null; }
  67469. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67470. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67471. _this.onApplyObservable.add(function (effect) {
  67472. var texelSize = _this.texelSize;
  67473. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67474. });
  67475. return _this;
  67476. }
  67477. return FxaaPostProcess;
  67478. }(BABYLON.PostProcess));
  67479. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67480. })(BABYLON || (BABYLON = {}));
  67481. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67482. var BABYLON;
  67483. (function (BABYLON) {
  67484. /**
  67485. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67486. */
  67487. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67488. __extends(CircleOfConfusionPostProcess, _super);
  67489. /**
  67490. * Creates a new instance of @see CircleOfConfusionPostProcess
  67491. * @param name The name of the effect.
  67492. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67493. * @param options The required width/height ratio to downsize to before computing the render pass.
  67494. * @param camera The camera to apply the render pass to.
  67495. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67496. * @param engine The engine which the post process will be applied. (default: current engine)
  67497. * @param reusable If the post process can be reused on the same frame. (default: false)
  67498. * @param textureType Type of textures used when performing the post process. (default: 0)
  67499. */
  67500. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67501. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67502. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67503. /**
  67504. * 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.
  67505. */
  67506. _this.lensSize = 50;
  67507. /**
  67508. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67509. */
  67510. _this.fStop = 1.4;
  67511. /**
  67512. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67513. */
  67514. _this.focusDistance = 2000;
  67515. /**
  67516. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67517. */
  67518. _this.focalLength = 50;
  67519. _this.onApplyObservable.add(function (effect) {
  67520. effect.setTexture("depthSampler", depthTexture);
  67521. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67522. var aperture = _this.lensSize / _this.fStop;
  67523. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67524. effect.setFloat('focusDistance', _this.focusDistance);
  67525. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67526. effect.setFloat2('cameraMinMaxZ', depthTexture.activeCamera.minZ, depthTexture.activeCamera.maxZ);
  67527. });
  67528. return _this;
  67529. }
  67530. return CircleOfConfusionPostProcess;
  67531. }(BABYLON.PostProcess));
  67532. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67533. })(BABYLON || (BABYLON = {}));
  67534. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67535. var BABYLON;
  67536. (function (BABYLON) {
  67537. /**
  67538. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67539. */
  67540. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67541. __extends(DepthOfFieldMergePostProcess, _super);
  67542. /**
  67543. * Creates a new instance of @see CircleOfConfusionPostProcess
  67544. * @param name The name of the effect.
  67545. * @param original The non-blurred image to be modified
  67546. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67547. * @param blurSteps Incrimental bluring post processes.
  67548. * @param options The required width/height ratio to downsize to before computing the render pass.
  67549. * @param camera The camera to apply the render pass to.
  67550. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67551. * @param engine The engine which the post process will be applied. (default: current engine)
  67552. * @param reusable If the post process can be reused on the same frame. (default: false)
  67553. * @param textureType Type of textures used when performing the post process. (default: 0)
  67554. */
  67555. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67556. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67557. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67558. _this.onApplyObservable.add(function (effect) {
  67559. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67560. effect.setTextureFromPostProcess("originalSampler", original);
  67561. blurSteps.forEach(function (step, index) {
  67562. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67563. });
  67564. });
  67565. return _this;
  67566. }
  67567. return DepthOfFieldMergePostProcess;
  67568. }(BABYLON.PostProcess));
  67569. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67570. })(BABYLON || (BABYLON = {}));
  67571. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67572. var BABYLON;
  67573. (function (BABYLON) {
  67574. /**
  67575. * Specifies the level of max blur that should be applied when using the depth of field effect
  67576. */
  67577. var DepthOfFieldEffectBlurLevel;
  67578. (function (DepthOfFieldEffectBlurLevel) {
  67579. /**
  67580. * Subtle blur
  67581. */
  67582. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67583. /**
  67584. * Medium blur
  67585. */
  67586. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67587. /**
  67588. * Large blur
  67589. */
  67590. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67591. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67592. ;
  67593. /**
  67594. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67595. */
  67596. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67597. __extends(DepthOfFieldEffect, _super);
  67598. /**
  67599. * Creates a new instance of @see DepthOfFieldEffect
  67600. * @param scene The scene the effect belongs to.
  67601. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67602. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67603. */
  67604. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType) {
  67605. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67606. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67607. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67608. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67609. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67610. // Capture circle of confusion texture
  67611. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67612. _this._depthOfFieldPass.autoClear = false;
  67613. // 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)
  67614. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67615. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67616. _this._depthOfFieldBlurY = [];
  67617. _this._depthOfFieldBlurX = [];
  67618. var blurCount = 1;
  67619. var kernelSize = 15;
  67620. switch (blurLevel) {
  67621. case DepthOfFieldEffectBlurLevel.High: {
  67622. blurCount = 3;
  67623. kernelSize = 51;
  67624. break;
  67625. }
  67626. case DepthOfFieldEffectBlurLevel.Medium: {
  67627. blurCount = 2;
  67628. kernelSize = 31;
  67629. break;
  67630. }
  67631. default: {
  67632. kernelSize = 15;
  67633. blurCount = 1;
  67634. break;
  67635. }
  67636. }
  67637. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67638. for (var i = 0; i < blurCount; i++) {
  67639. 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);
  67640. blurY.autoClear = false;
  67641. 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);
  67642. blurX.autoClear = false;
  67643. _this._depthOfFieldBlurY.push(blurY);
  67644. _this._depthOfFieldBlurX.push(blurX);
  67645. }
  67646. // Merge blurred images with original image based on circleOfConfusion
  67647. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67648. _this._depthOfFieldMerge.autoClear = false;
  67649. // Set all post processes on the effect.
  67650. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67651. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67652. effects.push(_this._depthOfFieldBlurY[i]);
  67653. effects.push(_this._depthOfFieldBlurX[i]);
  67654. }
  67655. effects.push(_this._depthOfFieldMerge);
  67656. return effects;
  67657. }, true) || this;
  67658. return _this;
  67659. }
  67660. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67661. get: function () {
  67662. return this._circleOfConfusion.focalLength;
  67663. },
  67664. /**
  67665. * The focal the length of the camera used in the effect
  67666. */
  67667. set: function (value) {
  67668. this._circleOfConfusion.focalLength = value;
  67669. },
  67670. enumerable: true,
  67671. configurable: true
  67672. });
  67673. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67674. get: function () {
  67675. return this._circleOfConfusion.fStop;
  67676. },
  67677. /**
  67678. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67679. */
  67680. set: function (value) {
  67681. this._circleOfConfusion.fStop = value;
  67682. },
  67683. enumerable: true,
  67684. configurable: true
  67685. });
  67686. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67687. get: function () {
  67688. return this._circleOfConfusion.focusDistance;
  67689. },
  67690. /**
  67691. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67692. */
  67693. set: function (value) {
  67694. this._circleOfConfusion.focusDistance = value;
  67695. },
  67696. enumerable: true,
  67697. configurable: true
  67698. });
  67699. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67700. get: function () {
  67701. return this._circleOfConfusion.lensSize;
  67702. },
  67703. /**
  67704. * 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.
  67705. */
  67706. set: function (value) {
  67707. this._circleOfConfusion.lensSize = value;
  67708. },
  67709. enumerable: true,
  67710. configurable: true
  67711. });
  67712. /**
  67713. * Disposes each of the internal effects for a given camera.
  67714. * @param camera The camera to dispose the effect on.
  67715. */
  67716. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67717. this._depthOfFieldPass.dispose(camera);
  67718. this._circleOfConfusion.dispose(camera);
  67719. this._depthOfFieldBlurX.forEach(function (element) {
  67720. element.dispose(camera);
  67721. });
  67722. this._depthOfFieldBlurY.forEach(function (element) {
  67723. element.dispose(camera);
  67724. });
  67725. this._depthOfFieldMerge.dispose(camera);
  67726. };
  67727. return DepthOfFieldEffect;
  67728. }(BABYLON.PostProcessRenderEffect));
  67729. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67730. })(BABYLON || (BABYLON = {}));
  67731. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67732. var BABYLON;
  67733. (function (BABYLON) {
  67734. /**
  67735. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67736. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67737. */
  67738. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67739. __extends(DefaultRenderingPipeline, _super);
  67740. /**
  67741. * @constructor
  67742. * @param {string} name - The rendering pipeline name
  67743. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67744. * @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)
  67745. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67746. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67747. */
  67748. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67749. if (automaticBuild === void 0) { automaticBuild = true; }
  67750. var _this = _super.call(this, scene.getEngine(), name) || this;
  67751. /**
  67752. * ID of the sharpen post process,
  67753. */
  67754. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  67755. /**
  67756. * ID of the pass post process used for bloom,
  67757. */
  67758. _this.PassPostProcessId = "PassPostProcessEffect";
  67759. /**
  67760. * ID of the highlight post process used for bloom,
  67761. */
  67762. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67763. /**
  67764. * ID of the blurX post process used for bloom,
  67765. */
  67766. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67767. /**
  67768. * ID of the blurY post process used for bloom,
  67769. */
  67770. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67771. /**
  67772. * ID of the copy back post process used for bloom,
  67773. */
  67774. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67775. /**
  67776. * ID of the image processing post process;
  67777. */
  67778. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67779. /**
  67780. * ID of the Fast Approximate Anti-Aliasing post process;
  67781. */
  67782. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67783. /**
  67784. * ID of the final merge post process;
  67785. */
  67786. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67787. /**
  67788. * Animations which can be used to tweak settings over a period of time
  67789. */
  67790. _this.animations = [];
  67791. // Values
  67792. _this._sharpenEnabled = false;
  67793. _this._bloomEnabled = false;
  67794. _this._depthOfFieldEnabled = false;
  67795. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67796. _this._fxaaEnabled = false;
  67797. _this._msaaEnabled = false;
  67798. _this._imageProcessingEnabled = true;
  67799. _this._bloomScale = 0.6;
  67800. _this._buildAllowed = true;
  67801. /**
  67802. * Specifies the size of the bloom blur kernel, relative to the final output size
  67803. */
  67804. _this.bloomKernel = 64;
  67805. /**
  67806. * Specifies the weight of the bloom in the final rendering
  67807. */
  67808. _this._bloomWeight = 0.15;
  67809. _this._cameras = cameras || [];
  67810. _this._buildAllowed = automaticBuild;
  67811. // Initialize
  67812. _this._scene = scene;
  67813. var caps = _this._scene.getEngine().getCaps();
  67814. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67815. // Misc
  67816. if (_this._hdr) {
  67817. if (caps.textureHalfFloatRender) {
  67818. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67819. }
  67820. else if (caps.textureFloatRender) {
  67821. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67822. }
  67823. }
  67824. else {
  67825. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67826. }
  67827. // Attach
  67828. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67829. _this._buildPipeline();
  67830. return _this;
  67831. }
  67832. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  67833. get: function () {
  67834. return this._sharpenEnabled;
  67835. },
  67836. /**
  67837. * Enable or disable the sharpen process from the pipeline
  67838. */
  67839. set: function (enabled) {
  67840. if (this._sharpenEnabled === enabled) {
  67841. return;
  67842. }
  67843. this._sharpenEnabled = enabled;
  67844. this._buildPipeline();
  67845. },
  67846. enumerable: true,
  67847. configurable: true
  67848. });
  67849. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67850. get: function () {
  67851. return this._bloomWeight;
  67852. },
  67853. /**
  67854. * The strength of the bloom.
  67855. */
  67856. set: function (value) {
  67857. if (this._bloomWeight === value) {
  67858. return;
  67859. }
  67860. this._bloomWeight = value;
  67861. if (this._hdr && this.copyBack) {
  67862. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67863. }
  67864. },
  67865. enumerable: true,
  67866. configurable: true
  67867. });
  67868. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67869. get: function () {
  67870. return this._bloomScale;
  67871. },
  67872. /**
  67873. * The scale of the bloom, lower value will provide better performance.
  67874. */
  67875. set: function (value) {
  67876. if (this._bloomScale === value) {
  67877. return;
  67878. }
  67879. this._bloomScale = value;
  67880. this._buildPipeline();
  67881. },
  67882. enumerable: true,
  67883. configurable: true
  67884. });
  67885. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67886. get: function () {
  67887. return this._bloomEnabled;
  67888. },
  67889. /**
  67890. * Enable or disable the bloom from the pipeline
  67891. */
  67892. set: function (enabled) {
  67893. if (this._bloomEnabled === enabled) {
  67894. return;
  67895. }
  67896. this._bloomEnabled = enabled;
  67897. this._buildPipeline();
  67898. },
  67899. enumerable: true,
  67900. configurable: true
  67901. });
  67902. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67903. /**
  67904. * If the depth of field is enabled.
  67905. */
  67906. get: function () {
  67907. return this._depthOfFieldEnabled;
  67908. },
  67909. set: function (enabled) {
  67910. if (this._depthOfFieldEnabled === enabled) {
  67911. return;
  67912. }
  67913. this._depthOfFieldEnabled = enabled;
  67914. this._buildPipeline();
  67915. },
  67916. enumerable: true,
  67917. configurable: true
  67918. });
  67919. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67920. /**
  67921. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67922. */
  67923. get: function () {
  67924. return this._depthOfFieldBlurLevel;
  67925. },
  67926. set: function (value) {
  67927. if (this._depthOfFieldBlurLevel === value) {
  67928. return;
  67929. }
  67930. this._depthOfFieldBlurLevel = value;
  67931. this._buildPipeline();
  67932. },
  67933. enumerable: true,
  67934. configurable: true
  67935. });
  67936. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67937. get: function () {
  67938. return this._fxaaEnabled;
  67939. },
  67940. /**
  67941. * If the anti aliasing is enabled.
  67942. */
  67943. set: function (enabled) {
  67944. if (this._fxaaEnabled === enabled) {
  67945. return;
  67946. }
  67947. this._fxaaEnabled = enabled;
  67948. this._buildPipeline();
  67949. },
  67950. enumerable: true,
  67951. configurable: true
  67952. });
  67953. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  67954. get: function () {
  67955. return this._msaaEnabled;
  67956. },
  67957. /**
  67958. * If the multisample anti-aliasing is enabled.
  67959. */
  67960. set: function (enabled) {
  67961. if (this._msaaEnabled === enabled) {
  67962. return;
  67963. }
  67964. this._msaaEnabled = enabled;
  67965. this._buildPipeline();
  67966. },
  67967. enumerable: true,
  67968. configurable: true
  67969. });
  67970. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67971. get: function () {
  67972. return this._imageProcessingEnabled;
  67973. },
  67974. /**
  67975. * If image processing is enabled.
  67976. */
  67977. set: function (enabled) {
  67978. if (this._imageProcessingEnabled === enabled) {
  67979. return;
  67980. }
  67981. this._imageProcessingEnabled = enabled;
  67982. this._buildPipeline();
  67983. },
  67984. enumerable: true,
  67985. configurable: true
  67986. });
  67987. /**
  67988. * Force the compilation of the entire pipeline.
  67989. */
  67990. DefaultRenderingPipeline.prototype.prepare = function () {
  67991. var previousState = this._buildAllowed;
  67992. this._buildAllowed = true;
  67993. this._buildPipeline();
  67994. this._buildAllowed = previousState;
  67995. };
  67996. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67997. var _this = this;
  67998. if (!this._buildAllowed) {
  67999. return;
  68000. }
  68001. var engine = this._scene.getEngine();
  68002. this._disposePostProcesses();
  68003. this._reset();
  68004. if (this.sharpenEnabled) {
  68005. this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68006. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.SharpenPostProcessId, function () { return _this.sharpen; }, true));
  68007. }
  68008. if (this.depthOfFieldEnabled) {
  68009. // Enable and get current depth map
  68010. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  68011. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, depthTexture, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68012. this.addEffect(this.depthOfField);
  68013. }
  68014. if (this.bloomEnabled) {
  68015. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68016. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68017. if (!this._hdr) {
  68018. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68019. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68020. this.highlights.autoClear = false;
  68021. this.highlights.alwaysForcePOT = true;
  68022. }
  68023. 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);
  68024. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68025. this.blurX.alwaysForcePOT = true;
  68026. this.blurX.autoClear = false;
  68027. this.blurX.onActivateObservable.add(function () {
  68028. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68029. _this.blurX.kernel = _this.bloomKernel * dw;
  68030. });
  68031. 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);
  68032. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68033. this.blurY.alwaysForcePOT = true;
  68034. this.blurY.autoClear = false;
  68035. this.blurY.onActivateObservable.add(function () {
  68036. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68037. _this.blurY.kernel = _this.bloomKernel * dh;
  68038. });
  68039. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68040. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68041. this.copyBack.alwaysForcePOT = true;
  68042. if (this._hdr) {
  68043. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68044. var w = this.bloomWeight;
  68045. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68046. }
  68047. else {
  68048. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68049. }
  68050. this.copyBack.autoClear = false;
  68051. }
  68052. if (this._imageProcessingEnabled) {
  68053. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68054. if (this._hdr) {
  68055. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68056. }
  68057. else {
  68058. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68059. }
  68060. }
  68061. if (this.fxaaEnabled) {
  68062. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68063. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68064. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68065. }
  68066. else if (this._hdr && this.imageProcessing) {
  68067. this.finalMerge = this.imageProcessing;
  68068. }
  68069. else {
  68070. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68071. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68072. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68073. }
  68074. if (this.bloomEnabled) {
  68075. if (this._hdr) {
  68076. this.copyBack.shareOutputWith(this.blurX);
  68077. if (this.imageProcessing) {
  68078. this.imageProcessing.shareOutputWith(this.pass);
  68079. this.imageProcessing.autoClear = false;
  68080. }
  68081. else if (this.fxaa) {
  68082. this.fxaa.shareOutputWith(this.pass);
  68083. }
  68084. else {
  68085. this.finalMerge.shareOutputWith(this.pass);
  68086. }
  68087. }
  68088. else {
  68089. if (this.fxaa) {
  68090. this.fxaa.shareOutputWith(this.pass);
  68091. }
  68092. else {
  68093. this.finalMerge.shareOutputWith(this.pass);
  68094. }
  68095. }
  68096. }
  68097. if (this._cameras !== null) {
  68098. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68099. }
  68100. if (this.msaaEnabled) {
  68101. if (!this._enableMSAAOnFirstPostProcess()) {
  68102. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  68103. }
  68104. }
  68105. };
  68106. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68107. for (var i = 0; i < this._cameras.length; i++) {
  68108. var camera = this._cameras[i];
  68109. if (this.sharpen) {
  68110. this.sharpen.dispose(camera);
  68111. }
  68112. if (this.pass) {
  68113. this.pass.dispose(camera);
  68114. }
  68115. if (this.highlights) {
  68116. this.highlights.dispose(camera);
  68117. }
  68118. if (this.blurX) {
  68119. this.blurX.dispose(camera);
  68120. }
  68121. if (this.blurY) {
  68122. this.blurY.dispose(camera);
  68123. }
  68124. if (this.copyBack) {
  68125. this.copyBack.dispose(camera);
  68126. }
  68127. if (this.imageProcessing) {
  68128. this.imageProcessing.dispose(camera);
  68129. }
  68130. if (this.fxaa) {
  68131. this.fxaa.dispose(camera);
  68132. }
  68133. if (this.finalMerge) {
  68134. this.finalMerge.dispose(camera);
  68135. }
  68136. if (this.depthOfField) {
  68137. this.depthOfField.disposeEffects(camera);
  68138. }
  68139. }
  68140. this.sharpen = null;
  68141. this.pass = null;
  68142. this.highlights = null;
  68143. this.blurX = null;
  68144. this.blurY = null;
  68145. this.copyBack = null;
  68146. this.imageProcessing = null;
  68147. this.fxaa = null;
  68148. this.finalMerge = null;
  68149. this.depthOfField = null;
  68150. };
  68151. /**
  68152. * Dispose of the pipeline and stop all post processes
  68153. */
  68154. DefaultRenderingPipeline.prototype.dispose = function () {
  68155. this._disposePostProcesses();
  68156. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68157. _super.prototype.dispose.call(this);
  68158. };
  68159. /**
  68160. * Serialize the rendering pipeline (Used when exporting)
  68161. * @returns the serialized object
  68162. */
  68163. DefaultRenderingPipeline.prototype.serialize = function () {
  68164. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68165. serializationObject.customType = "DefaultRenderingPipeline";
  68166. return serializationObject;
  68167. };
  68168. /**
  68169. * Parse the serialized pipeline
  68170. * @param source Source pipeline.
  68171. * @param scene The scene to load the pipeline to.
  68172. * @param rootUrl The URL of the serialized pipeline.
  68173. * @returns An instantiated pipeline from the serialized object.
  68174. */
  68175. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68176. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68177. };
  68178. __decorate([
  68179. BABYLON.serialize()
  68180. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  68181. __decorate([
  68182. BABYLON.serialize()
  68183. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68184. __decorate([
  68185. BABYLON.serialize()
  68186. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68187. __decorate([
  68188. BABYLON.serialize()
  68189. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68190. __decorate([
  68191. BABYLON.serialize()
  68192. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68193. __decorate([
  68194. BABYLON.serialize()
  68195. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68196. __decorate([
  68197. BABYLON.serialize()
  68198. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68199. __decorate([
  68200. BABYLON.serialize()
  68201. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68202. __decorate([
  68203. BABYLON.serialize()
  68204. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68205. __decorate([
  68206. BABYLON.serialize()
  68207. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68208. __decorate([
  68209. BABYLON.serialize()
  68210. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  68211. __decorate([
  68212. BABYLON.serialize()
  68213. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68214. return DefaultRenderingPipeline;
  68215. }(BABYLON.PostProcessRenderPipeline));
  68216. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68217. })(BABYLON || (BABYLON = {}));
  68218. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68219. var BABYLON;
  68220. (function (BABYLON) {
  68221. /**
  68222. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68223. */
  68224. var GeometryBufferRenderer = /** @class */ (function () {
  68225. /**
  68226. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68227. * @param scene The scene the buffer belongs to
  68228. * @param ratio How big is the buffer related to the main canvas.
  68229. */
  68230. function GeometryBufferRenderer(scene, ratio) {
  68231. if (ratio === void 0) { ratio = 1; }
  68232. this._enablePosition = false;
  68233. this._scene = scene;
  68234. this._ratio = ratio;
  68235. // Render target
  68236. this._createRenderTargets();
  68237. }
  68238. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68239. /**
  68240. * Set the render list (meshes to be rendered) used in the G buffer.
  68241. */
  68242. set: function (meshes) {
  68243. this._multiRenderTarget.renderList = meshes;
  68244. },
  68245. enumerable: true,
  68246. configurable: true
  68247. });
  68248. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68249. /**
  68250. * Gets wether or not G buffer are supported by the running hardware.
  68251. * This requires draw buffer supports
  68252. */
  68253. get: function () {
  68254. return this._multiRenderTarget.isSupported;
  68255. },
  68256. enumerable: true,
  68257. configurable: true
  68258. });
  68259. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68260. /**
  68261. * Gets wether or not position are enabled for the G buffer.
  68262. */
  68263. get: function () {
  68264. return this._enablePosition;
  68265. },
  68266. /**
  68267. * Sets wether or not position are enabled for the G buffer.
  68268. */
  68269. set: function (enable) {
  68270. this._enablePosition = enable;
  68271. this.dispose();
  68272. this._createRenderTargets();
  68273. },
  68274. enumerable: true,
  68275. configurable: true
  68276. });
  68277. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68278. /**
  68279. * Gets the scene associated with the buffer.
  68280. */
  68281. get: function () {
  68282. return this._scene;
  68283. },
  68284. enumerable: true,
  68285. configurable: true
  68286. });
  68287. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68288. /**
  68289. * Gets the ratio used by the buffer during its creation.
  68290. * How big is the buffer related to the main canvas.
  68291. */
  68292. get: function () {
  68293. return this._ratio;
  68294. },
  68295. enumerable: true,
  68296. configurable: true
  68297. });
  68298. /**
  68299. * Checks wether everything is ready to render a submesh to the G buffer.
  68300. * @param subMesh the submesh to check readiness for
  68301. * @param useInstances is the mesh drawn using instance or not
  68302. * @returns true if ready otherwise false
  68303. */
  68304. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68305. var material = subMesh.getMaterial();
  68306. if (material && material.disableDepthWrite) {
  68307. return false;
  68308. }
  68309. var defines = [];
  68310. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68311. var mesh = subMesh.getMesh();
  68312. // Alpha test
  68313. if (material && material.needAlphaTesting()) {
  68314. defines.push("#define ALPHATEST");
  68315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68316. attribs.push(BABYLON.VertexBuffer.UVKind);
  68317. defines.push("#define UV1");
  68318. }
  68319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68320. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68321. defines.push("#define UV2");
  68322. }
  68323. }
  68324. // Buffers
  68325. if (this._enablePosition) {
  68326. defines.push("#define POSITION");
  68327. }
  68328. // Bones
  68329. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68332. if (mesh.numBoneInfluencers > 4) {
  68333. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68334. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68335. }
  68336. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68337. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68338. }
  68339. else {
  68340. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68341. }
  68342. // Instances
  68343. if (useInstances) {
  68344. defines.push("#define INSTANCES");
  68345. attribs.push("world0");
  68346. attribs.push("world1");
  68347. attribs.push("world2");
  68348. attribs.push("world3");
  68349. }
  68350. // Get correct effect
  68351. var join = defines.join("\n");
  68352. if (this._cachedDefines !== join) {
  68353. this._cachedDefines = join;
  68354. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68355. }
  68356. return this._effect.isReady();
  68357. };
  68358. /**
  68359. * Gets the current underlying G Buffer.
  68360. * @returns the buffer
  68361. */
  68362. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68363. return this._multiRenderTarget;
  68364. };
  68365. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68366. /**
  68367. * Gets the number of samples used to render the buffer (anti aliasing).
  68368. */
  68369. get: function () {
  68370. return this._multiRenderTarget.samples;
  68371. },
  68372. /**
  68373. * Sets the number of samples used to render the buffer (anti aliasing).
  68374. */
  68375. set: function (value) {
  68376. this._multiRenderTarget.samples = value;
  68377. },
  68378. enumerable: true,
  68379. configurable: true
  68380. });
  68381. /**
  68382. * Disposes the renderer and frees up associated resources.
  68383. */
  68384. GeometryBufferRenderer.prototype.dispose = function () {
  68385. this.getGBuffer().dispose();
  68386. };
  68387. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68388. var _this = this;
  68389. var engine = this._scene.getEngine();
  68390. var count = this._enablePosition ? 3 : 2;
  68391. 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 });
  68392. if (!this.isSupported) {
  68393. return;
  68394. }
  68395. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68396. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68397. this._multiRenderTarget.refreshRate = 1;
  68398. this._multiRenderTarget.renderParticles = false;
  68399. this._multiRenderTarget.renderList = null;
  68400. // set default depth value to 1.0 (far away)
  68401. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68402. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68403. });
  68404. // Custom render function
  68405. var renderSubMesh = function (subMesh) {
  68406. var mesh = subMesh.getRenderingMesh();
  68407. var scene = _this._scene;
  68408. var engine = scene.getEngine();
  68409. var material = subMesh.getMaterial();
  68410. if (!material) {
  68411. return;
  68412. }
  68413. // Culling
  68414. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68415. // Managing instances
  68416. var batch = mesh._getInstancesRenderList(subMesh._id);
  68417. if (batch.mustReturn) {
  68418. return;
  68419. }
  68420. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68421. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68422. engine.enableEffect(_this._effect);
  68423. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68424. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68425. _this._effect.setMatrix("view", scene.getViewMatrix());
  68426. // Alpha test
  68427. if (material && material.needAlphaTesting()) {
  68428. var alphaTexture = material.getAlphaTestTexture();
  68429. if (alphaTexture) {
  68430. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68431. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68432. }
  68433. }
  68434. // Bones
  68435. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68436. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68437. }
  68438. // Draw
  68439. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68440. }
  68441. };
  68442. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68443. var index;
  68444. if (depthOnlySubMeshes.length) {
  68445. engine.setColorWrite(false);
  68446. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68447. renderSubMesh(depthOnlySubMeshes.data[index]);
  68448. }
  68449. engine.setColorWrite(true);
  68450. }
  68451. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68452. renderSubMesh(opaqueSubMeshes.data[index]);
  68453. }
  68454. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68455. renderSubMesh(alphaTestSubMeshes.data[index]);
  68456. }
  68457. };
  68458. };
  68459. return GeometryBufferRenderer;
  68460. }());
  68461. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68462. })(BABYLON || (BABYLON = {}));
  68463. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68464. var BABYLON;
  68465. (function (BABYLON) {
  68466. var RefractionPostProcess = /** @class */ (function (_super) {
  68467. __extends(RefractionPostProcess, _super);
  68468. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68469. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68470. _this.color = color;
  68471. _this.depth = depth;
  68472. _this.colorLevel = colorLevel;
  68473. _this._ownRefractionTexture = true;
  68474. _this.onActivateObservable.add(function (cam) {
  68475. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68476. });
  68477. _this.onApplyObservable.add(function (effect) {
  68478. effect.setColor3("baseColor", _this.color);
  68479. effect.setFloat("depth", _this.depth);
  68480. effect.setFloat("colorLevel", _this.colorLevel);
  68481. effect.setTexture("refractionSampler", _this._refTexture);
  68482. });
  68483. return _this;
  68484. }
  68485. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68486. /**
  68487. * Gets or sets the refraction texture
  68488. * Please note that you are responsible for disposing the texture if you set it manually
  68489. */
  68490. get: function () {
  68491. return this._refTexture;
  68492. },
  68493. set: function (value) {
  68494. if (this._refTexture && this._ownRefractionTexture) {
  68495. this._refTexture.dispose();
  68496. }
  68497. this._refTexture = value;
  68498. this._ownRefractionTexture = false;
  68499. },
  68500. enumerable: true,
  68501. configurable: true
  68502. });
  68503. // Methods
  68504. RefractionPostProcess.prototype.dispose = function (camera) {
  68505. if (this._refTexture && this._ownRefractionTexture) {
  68506. this._refTexture.dispose();
  68507. this._refTexture = null;
  68508. }
  68509. _super.prototype.dispose.call(this, camera);
  68510. };
  68511. return RefractionPostProcess;
  68512. }(BABYLON.PostProcess));
  68513. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68514. })(BABYLON || (BABYLON = {}));
  68515. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68516. var BABYLON;
  68517. (function (BABYLON) {
  68518. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68519. __extends(BlackAndWhitePostProcess, _super);
  68520. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68521. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68522. _this.degree = 1;
  68523. _this.onApplyObservable.add(function (effect) {
  68524. effect.setFloat("degree", _this.degree);
  68525. });
  68526. return _this;
  68527. }
  68528. return BlackAndWhitePostProcess;
  68529. }(BABYLON.PostProcess));
  68530. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68531. })(BABYLON || (BABYLON = {}));
  68532. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68533. var BABYLON;
  68534. (function (BABYLON) {
  68535. /**
  68536. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  68537. * input texture to perform effects such as edge detection or sharpening
  68538. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68539. */
  68540. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68541. __extends(ConvolutionPostProcess, _super);
  68542. /**
  68543. * Creates a new instance of @see ConvolutionPostProcess
  68544. * @param name The name of the effect.
  68545. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  68546. * @param options The required width/height ratio to downsize to before computing the render pass.
  68547. * @param camera The camera to apply the render pass to.
  68548. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68549. * @param engine The engine which the post process will be applied. (default: current engine)
  68550. * @param reusable If the post process can be reused on the same frame. (default: false)
  68551. * @param textureType Type of textures used when performing the post process. (default: 0)
  68552. */
  68553. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  68554. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68555. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68556. _this.kernel = kernel;
  68557. _this.onApply = function (effect) {
  68558. effect.setFloat2("screenSize", _this.width, _this.height);
  68559. effect.setArray("kernel", _this.kernel);
  68560. };
  68561. return _this;
  68562. }
  68563. // Statics
  68564. /**
  68565. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68566. */
  68567. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68568. /**
  68569. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68570. */
  68571. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68572. /**
  68573. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68574. */
  68575. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68576. /**
  68577. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68578. */
  68579. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68580. /**
  68581. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68582. */
  68583. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68584. /**
  68585. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  68586. */
  68587. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68588. return ConvolutionPostProcess;
  68589. }(BABYLON.PostProcess));
  68590. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68591. })(BABYLON || (BABYLON = {}));
  68592. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68593. var BABYLON;
  68594. (function (BABYLON) {
  68595. /**
  68596. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68597. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68598. */
  68599. var SharpenPostProcess = /** @class */ (function (_super) {
  68600. __extends(SharpenPostProcess, _super);
  68601. /**
  68602. * Creates a new instance of @see ConvolutionPostProcess
  68603. * @param name The name of the effect.
  68604. * @param options The required width/height ratio to downsize to before computing the render pass.
  68605. * @param camera The camera to apply the render pass to.
  68606. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68607. * @param engine The engine which the post process will be applied. (default: current engine)
  68608. * @param reusable If the post process can be reused on the same frame. (default: false)
  68609. * @param textureType Type of textures used when performing the post process. (default: 0)
  68610. */
  68611. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68613. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68614. /**
  68615. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68616. */
  68617. _this.colorAmount = 1.0;
  68618. /**
  68619. * How much sharpness should be applied (default: 0.3)
  68620. */
  68621. _this.edgeAmount = 0.3;
  68622. _this.onApply = function (effect) {
  68623. effect.setFloat2("screenSize", _this.width, _this.height);
  68624. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68625. };
  68626. return _this;
  68627. }
  68628. return SharpenPostProcess;
  68629. }(BABYLON.PostProcess));
  68630. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68631. })(BABYLON || (BABYLON = {}));
  68632. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68633. var BABYLON;
  68634. (function (BABYLON) {
  68635. var FilterPostProcess = /** @class */ (function (_super) {
  68636. __extends(FilterPostProcess, _super);
  68637. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68638. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68639. _this.kernelMatrix = kernelMatrix;
  68640. _this.onApply = function (effect) {
  68641. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68642. };
  68643. return _this;
  68644. }
  68645. return FilterPostProcess;
  68646. }(BABYLON.PostProcess));
  68647. BABYLON.FilterPostProcess = FilterPostProcess;
  68648. })(BABYLON || (BABYLON = {}));
  68649. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68650. var BABYLON;
  68651. (function (BABYLON) {
  68652. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68653. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68654. __extends(VolumetricLightScatteringPostProcess, _super);
  68655. /**
  68656. * @constructor
  68657. * @param {string} name - The post-process name
  68658. * @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)
  68659. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68660. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68661. * @param {number} samples - The post-process quality, default 100
  68662. * @param {number} samplingMode - The post-process filtering mode
  68663. * @param {BABYLON.Engine} engine - The babylon engine
  68664. * @param {boolean} reusable - If the post-process is reusable
  68665. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68666. */
  68667. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68668. if (samples === void 0) { samples = 100; }
  68669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68670. 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;
  68671. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68672. /**
  68673. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68674. * @type {Vector3}
  68675. */
  68676. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68677. /**
  68678. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68679. * @type {boolean}
  68680. */
  68681. _this.useCustomMeshPosition = false;
  68682. /**
  68683. * If the post-process should inverse the light scattering direction
  68684. * @type {boolean}
  68685. */
  68686. _this.invert = true;
  68687. /**
  68688. * Array containing the excluded meshes not rendered in the internal pass
  68689. */
  68690. _this.excludedMeshes = new Array();
  68691. /**
  68692. * Controls the overall intensity of the post-process
  68693. * @type {number}
  68694. */
  68695. _this.exposure = 0.3;
  68696. /**
  68697. * Dissipates each sample's contribution in range [0, 1]
  68698. * @type {number}
  68699. */
  68700. _this.decay = 0.96815;
  68701. /**
  68702. * Controls the overall intensity of each sample
  68703. * @type {number}
  68704. */
  68705. _this.weight = 0.58767;
  68706. /**
  68707. * Controls the density of each sample
  68708. * @type {number}
  68709. */
  68710. _this.density = 0.926;
  68711. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68712. engine = scene.getEngine();
  68713. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68714. // Configure mesh
  68715. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68716. // Configure
  68717. _this._createPass(scene, ratio.passRatio || ratio);
  68718. _this.onActivate = function (camera) {
  68719. if (!_this.isSupported) {
  68720. _this.dispose(camera);
  68721. }
  68722. _this.onActivate = null;
  68723. };
  68724. _this.onApplyObservable.add(function (effect) {
  68725. _this._updateMeshScreenCoordinates(scene);
  68726. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68727. effect.setFloat("exposure", _this.exposure);
  68728. effect.setFloat("decay", _this.decay);
  68729. effect.setFloat("weight", _this.weight);
  68730. effect.setFloat("density", _this.density);
  68731. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68732. });
  68733. return _this;
  68734. }
  68735. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68736. get: function () {
  68737. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68738. return false;
  68739. },
  68740. set: function (useDiffuseColor) {
  68741. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68742. },
  68743. enumerable: true,
  68744. configurable: true
  68745. });
  68746. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68747. return "VolumetricLightScatteringPostProcess";
  68748. };
  68749. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68750. var mesh = subMesh.getMesh();
  68751. // Render this.mesh as default
  68752. if (mesh === this.mesh && mesh.material) {
  68753. return mesh.material.isReady(mesh);
  68754. }
  68755. var defines = [];
  68756. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68757. var material = subMesh.getMaterial();
  68758. // Alpha test
  68759. if (material) {
  68760. if (material.needAlphaTesting()) {
  68761. defines.push("#define ALPHATEST");
  68762. }
  68763. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68764. attribs.push(BABYLON.VertexBuffer.UVKind);
  68765. defines.push("#define UV1");
  68766. }
  68767. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68768. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68769. defines.push("#define UV2");
  68770. }
  68771. }
  68772. // Bones
  68773. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68774. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68775. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68778. }
  68779. else {
  68780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68781. }
  68782. // Instances
  68783. if (useInstances) {
  68784. defines.push("#define INSTANCES");
  68785. attribs.push("world0");
  68786. attribs.push("world1");
  68787. attribs.push("world2");
  68788. attribs.push("world3");
  68789. }
  68790. // Get correct effect
  68791. var join = defines.join("\n");
  68792. if (this._cachedDefines !== join) {
  68793. this._cachedDefines = join;
  68794. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68795. }
  68796. return this._volumetricLightScatteringPass.isReady();
  68797. };
  68798. /**
  68799. * Sets the new light position for light scattering effect
  68800. * @param {BABYLON.Vector3} The new custom light position
  68801. */
  68802. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68803. this.customMeshPosition = position;
  68804. };
  68805. /**
  68806. * Returns the light position for light scattering effect
  68807. * @return {BABYLON.Vector3} The custom light position
  68808. */
  68809. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68810. return this.customMeshPosition;
  68811. };
  68812. /**
  68813. * Disposes the internal assets and detaches the post-process from the camera
  68814. */
  68815. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68816. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68817. if (rttIndex !== -1) {
  68818. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68819. }
  68820. this._volumetricLightScatteringRTT.dispose();
  68821. _super.prototype.dispose.call(this, camera);
  68822. };
  68823. /**
  68824. * Returns the render target texture used by the post-process
  68825. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68826. */
  68827. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68828. return this._volumetricLightScatteringRTT;
  68829. };
  68830. // Private methods
  68831. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68832. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68833. return true;
  68834. }
  68835. return false;
  68836. };
  68837. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68838. var _this = this;
  68839. var engine = scene.getEngine();
  68840. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68841. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68842. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68843. this._volumetricLightScatteringRTT.renderList = null;
  68844. this._volumetricLightScatteringRTT.renderParticles = false;
  68845. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68846. var camera = this.getCamera();
  68847. if (camera) {
  68848. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68849. }
  68850. else {
  68851. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68852. }
  68853. // Custom render function for submeshes
  68854. var renderSubMesh = function (subMesh) {
  68855. var mesh = subMesh.getRenderingMesh();
  68856. if (_this._meshExcluded(mesh)) {
  68857. return;
  68858. }
  68859. var material = subMesh.getMaterial();
  68860. if (!material) {
  68861. return;
  68862. }
  68863. var scene = mesh.getScene();
  68864. var engine = scene.getEngine();
  68865. // Culling
  68866. engine.setState(material.backFaceCulling);
  68867. // Managing instances
  68868. var batch = mesh._getInstancesRenderList(subMesh._id);
  68869. if (batch.mustReturn) {
  68870. return;
  68871. }
  68872. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68873. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68874. var effect = _this._volumetricLightScatteringPass;
  68875. if (mesh === _this.mesh) {
  68876. if (subMesh.effect) {
  68877. effect = subMesh.effect;
  68878. }
  68879. else {
  68880. effect = material.getEffect();
  68881. }
  68882. }
  68883. engine.enableEffect(effect);
  68884. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68885. if (mesh === _this.mesh) {
  68886. material.bind(mesh.getWorldMatrix(), mesh);
  68887. }
  68888. else {
  68889. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68890. // Alpha test
  68891. if (material && material.needAlphaTesting()) {
  68892. var alphaTexture = material.getAlphaTestTexture();
  68893. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68894. if (alphaTexture) {
  68895. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68896. }
  68897. }
  68898. // Bones
  68899. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68900. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68901. }
  68902. }
  68903. // Draw
  68904. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68905. }
  68906. };
  68907. // Render target texture callbacks
  68908. var savedSceneClearColor;
  68909. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68910. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68911. savedSceneClearColor = scene.clearColor;
  68912. scene.clearColor = sceneClearColor;
  68913. });
  68914. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68915. scene.clearColor = savedSceneClearColor;
  68916. });
  68917. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68918. var engine = scene.getEngine();
  68919. var index;
  68920. if (depthOnlySubMeshes.length) {
  68921. engine.setColorWrite(false);
  68922. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68923. renderSubMesh(depthOnlySubMeshes.data[index]);
  68924. }
  68925. engine.setColorWrite(true);
  68926. }
  68927. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68928. renderSubMesh(opaqueSubMeshes.data[index]);
  68929. }
  68930. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68931. renderSubMesh(alphaTestSubMeshes.data[index]);
  68932. }
  68933. if (transparentSubMeshes.length) {
  68934. // Sort sub meshes
  68935. for (index = 0; index < transparentSubMeshes.length; index++) {
  68936. var submesh = transparentSubMeshes.data[index];
  68937. var boundingInfo = submesh.getBoundingInfo();
  68938. if (boundingInfo && scene.activeCamera) {
  68939. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68940. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68941. }
  68942. }
  68943. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68944. sortedArray.sort(function (a, b) {
  68945. // Alpha index first
  68946. if (a._alphaIndex > b._alphaIndex) {
  68947. return 1;
  68948. }
  68949. if (a._alphaIndex < b._alphaIndex) {
  68950. return -1;
  68951. }
  68952. // Then distance to camera
  68953. if (a._distanceToCamera < b._distanceToCamera) {
  68954. return 1;
  68955. }
  68956. if (a._distanceToCamera > b._distanceToCamera) {
  68957. return -1;
  68958. }
  68959. return 0;
  68960. });
  68961. // Render sub meshes
  68962. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68963. for (index = 0; index < sortedArray.length; index++) {
  68964. renderSubMesh(sortedArray[index]);
  68965. }
  68966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68967. }
  68968. };
  68969. };
  68970. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68971. var transform = scene.getTransformMatrix();
  68972. var meshPosition;
  68973. if (this.useCustomMeshPosition) {
  68974. meshPosition = this.customMeshPosition;
  68975. }
  68976. else if (this.attachedNode) {
  68977. meshPosition = this.attachedNode.position;
  68978. }
  68979. else {
  68980. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  68981. }
  68982. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  68983. this._screenCoordinates.x = pos.x / this._viewPort.width;
  68984. this._screenCoordinates.y = pos.y / this._viewPort.height;
  68985. if (this.invert)
  68986. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  68987. };
  68988. // Static methods
  68989. /**
  68990. * Creates a default mesh for the Volumeric Light Scattering post-process
  68991. * @param {string} The mesh name
  68992. * @param {BABYLON.Scene} The scene where to create the mesh
  68993. * @return {BABYLON.Mesh} the default mesh
  68994. */
  68995. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  68996. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  68997. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  68998. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  68999. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  69000. mesh.material = material;
  69001. return mesh;
  69002. };
  69003. __decorate([
  69004. BABYLON.serializeAsVector3()
  69005. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  69006. __decorate([
  69007. BABYLON.serialize()
  69008. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  69009. __decorate([
  69010. BABYLON.serialize()
  69011. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  69012. __decorate([
  69013. BABYLON.serializeAsMeshReference()
  69014. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  69015. __decorate([
  69016. BABYLON.serialize()
  69017. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  69018. __decorate([
  69019. BABYLON.serialize()
  69020. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  69021. __decorate([
  69022. BABYLON.serialize()
  69023. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  69024. __decorate([
  69025. BABYLON.serialize()
  69026. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  69027. __decorate([
  69028. BABYLON.serialize()
  69029. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  69030. return VolumetricLightScatteringPostProcess;
  69031. }(BABYLON.PostProcess));
  69032. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  69033. })(BABYLON || (BABYLON = {}));
  69034. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  69035. //
  69036. // This post-process allows the modification of rendered colors by using
  69037. // a 'look-up table' (LUT). This effect is also called Color Grading.
  69038. //
  69039. // The object needs to be provided an url to a texture containing the color
  69040. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  69041. // Use an image editing software to tweak the LUT to match your needs.
  69042. //
  69043. // For an example of a color LUT, see here:
  69044. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  69045. // For explanations on color grading, see here:
  69046. // http://udn.epicgames.com/Three/ColorGrading.html
  69047. //
  69048. var BABYLON;
  69049. (function (BABYLON) {
  69050. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  69051. __extends(ColorCorrectionPostProcess, _super);
  69052. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  69053. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  69054. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69055. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69056. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69057. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69058. _this.onApply = function (effect) {
  69059. effect.setTexture("colorTable", _this._colorTableTexture);
  69060. };
  69061. return _this;
  69062. }
  69063. return ColorCorrectionPostProcess;
  69064. }(BABYLON.PostProcess));
  69065. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69066. })(BABYLON || (BABYLON = {}));
  69067. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69068. var BABYLON;
  69069. (function (BABYLON) {
  69070. var TonemappingOperator;
  69071. (function (TonemappingOperator) {
  69072. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69073. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69074. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69075. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69076. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69077. ;
  69078. var TonemapPostProcess = /** @class */ (function (_super) {
  69079. __extends(TonemapPostProcess, _super);
  69080. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69082. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69083. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69084. _this._operator = _operator;
  69085. _this.exposureAdjustment = exposureAdjustment;
  69086. var defines = "#define ";
  69087. if (_this._operator === TonemappingOperator.Hable)
  69088. defines += "HABLE_TONEMAPPING";
  69089. else if (_this._operator === TonemappingOperator.Reinhard)
  69090. defines += "REINHARD_TONEMAPPING";
  69091. else if (_this._operator === TonemappingOperator.HejiDawson)
  69092. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69093. else if (_this._operator === TonemappingOperator.Photographic)
  69094. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69095. //sadly a second call to create the effect.
  69096. _this.updateEffect(defines);
  69097. _this.onApply = function (effect) {
  69098. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69099. };
  69100. return _this;
  69101. }
  69102. return TonemapPostProcess;
  69103. }(BABYLON.PostProcess));
  69104. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69105. })(BABYLON || (BABYLON = {}));
  69106. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69107. var BABYLON;
  69108. (function (BABYLON) {
  69109. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69110. __extends(DisplayPassPostProcess, _super);
  69111. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69112. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69113. }
  69114. return DisplayPassPostProcess;
  69115. }(BABYLON.PostProcess));
  69116. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69117. })(BABYLON || (BABYLON = {}));
  69118. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69119. var BABYLON;
  69120. (function (BABYLON) {
  69121. var HighlightsPostProcess = /** @class */ (function (_super) {
  69122. __extends(HighlightsPostProcess, _super);
  69123. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69124. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69125. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69126. }
  69127. return HighlightsPostProcess;
  69128. }(BABYLON.PostProcess));
  69129. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69130. })(BABYLON || (BABYLON = {}));
  69131. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69132. var BABYLON;
  69133. (function (BABYLON) {
  69134. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69135. __extends(ImageProcessingPostProcess, _super);
  69136. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69137. if (camera === void 0) { camera = null; }
  69138. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69139. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69140. _this._fromLinearSpace = true;
  69141. /**
  69142. * Defines cache preventing GC.
  69143. */
  69144. _this._defines = {
  69145. IMAGEPROCESSING: false,
  69146. VIGNETTE: false,
  69147. VIGNETTEBLENDMODEMULTIPLY: false,
  69148. VIGNETTEBLENDMODEOPAQUE: false,
  69149. TONEMAPPING: false,
  69150. CONTRAST: false,
  69151. COLORCURVES: false,
  69152. COLORGRADING: false,
  69153. COLORGRADING3D: false,
  69154. FROMLINEARSPACE: false,
  69155. SAMPLER3DGREENDEPTH: false,
  69156. SAMPLER3DBGRMAP: false,
  69157. IMAGEPROCESSINGPOSTPROCESS: false,
  69158. EXPOSURE: false,
  69159. };
  69160. // Setup the configuration as forced by the constructor. This would then not force the
  69161. // scene materials output in linear space and let untouched the default forward pass.
  69162. if (imageProcessingConfiguration) {
  69163. imageProcessingConfiguration.applyByPostProcess = true;
  69164. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69165. // This will cause the shader to be compiled
  69166. _this.fromLinearSpace = false;
  69167. }
  69168. else {
  69169. _this._attachImageProcessingConfiguration(null, true);
  69170. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69171. }
  69172. _this.onApply = function (effect) {
  69173. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69174. };
  69175. return _this;
  69176. }
  69177. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69178. /**
  69179. * Gets the image processing configuration used either in this material.
  69180. */
  69181. get: function () {
  69182. return this._imageProcessingConfiguration;
  69183. },
  69184. /**
  69185. * Sets the Default image processing configuration used either in the this material.
  69186. *
  69187. * If sets to null, the scene one is in use.
  69188. */
  69189. set: function (value) {
  69190. this._attachImageProcessingConfiguration(value);
  69191. },
  69192. enumerable: true,
  69193. configurable: true
  69194. });
  69195. /**
  69196. * Attaches a new image processing configuration to the PBR Material.
  69197. * @param configuration
  69198. */
  69199. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69200. var _this = this;
  69201. if (doNotBuild === void 0) { doNotBuild = false; }
  69202. if (configuration === this._imageProcessingConfiguration) {
  69203. return;
  69204. }
  69205. // Detaches observer.
  69206. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69207. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69208. }
  69209. // Pick the scene configuration if needed.
  69210. if (!configuration) {
  69211. var scene = null;
  69212. var engine = this.getEngine();
  69213. var camera = this.getCamera();
  69214. if (camera) {
  69215. scene = camera.getScene();
  69216. }
  69217. else if (engine && engine.scenes) {
  69218. var scenes = engine.scenes;
  69219. scene = scenes[scenes.length - 1];
  69220. }
  69221. else {
  69222. scene = BABYLON.Engine.LastCreatedScene;
  69223. }
  69224. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69225. }
  69226. else {
  69227. this._imageProcessingConfiguration = configuration;
  69228. }
  69229. // Attaches observer.
  69230. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69231. _this._updateParameters();
  69232. });
  69233. // Ensure the effect will be rebuilt.
  69234. if (!doNotBuild) {
  69235. this._updateParameters();
  69236. }
  69237. };
  69238. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69239. /**
  69240. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69241. */
  69242. get: function () {
  69243. return this.imageProcessingConfiguration.colorCurves;
  69244. },
  69245. /**
  69246. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69247. */
  69248. set: function (value) {
  69249. this.imageProcessingConfiguration.colorCurves = value;
  69250. },
  69251. enumerable: true,
  69252. configurable: true
  69253. });
  69254. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69255. /**
  69256. * Gets wether the color curves effect is enabled.
  69257. */
  69258. get: function () {
  69259. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69260. },
  69261. /**
  69262. * Sets wether the color curves effect is enabled.
  69263. */
  69264. set: function (value) {
  69265. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69266. },
  69267. enumerable: true,
  69268. configurable: true
  69269. });
  69270. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69271. /**
  69272. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69273. */
  69274. get: function () {
  69275. return this.imageProcessingConfiguration.colorGradingTexture;
  69276. },
  69277. /**
  69278. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69279. */
  69280. set: function (value) {
  69281. this.imageProcessingConfiguration.colorGradingTexture = value;
  69282. },
  69283. enumerable: true,
  69284. configurable: true
  69285. });
  69286. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69287. /**
  69288. * Gets wether the color grading effect is enabled.
  69289. */
  69290. get: function () {
  69291. return this.imageProcessingConfiguration.colorGradingEnabled;
  69292. },
  69293. /**
  69294. * Gets wether the color grading effect is enabled.
  69295. */
  69296. set: function (value) {
  69297. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69298. },
  69299. enumerable: true,
  69300. configurable: true
  69301. });
  69302. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69303. /**
  69304. * Gets exposure used in the effect.
  69305. */
  69306. get: function () {
  69307. return this.imageProcessingConfiguration.exposure;
  69308. },
  69309. /**
  69310. * Sets exposure used in the effect.
  69311. */
  69312. set: function (value) {
  69313. this.imageProcessingConfiguration.exposure = value;
  69314. },
  69315. enumerable: true,
  69316. configurable: true
  69317. });
  69318. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69319. /**
  69320. * Gets wether tonemapping is enabled or not.
  69321. */
  69322. get: function () {
  69323. return this._imageProcessingConfiguration.toneMappingEnabled;
  69324. },
  69325. /**
  69326. * Sets wether tonemapping is enabled or not
  69327. */
  69328. set: function (value) {
  69329. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69330. },
  69331. enumerable: true,
  69332. configurable: true
  69333. });
  69334. ;
  69335. ;
  69336. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69337. /**
  69338. * Gets contrast used in the effect.
  69339. */
  69340. get: function () {
  69341. return this.imageProcessingConfiguration.contrast;
  69342. },
  69343. /**
  69344. * Sets contrast used in the effect.
  69345. */
  69346. set: function (value) {
  69347. this.imageProcessingConfiguration.contrast = value;
  69348. },
  69349. enumerable: true,
  69350. configurable: true
  69351. });
  69352. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69353. /**
  69354. * Gets Vignette stretch size.
  69355. */
  69356. get: function () {
  69357. return this.imageProcessingConfiguration.vignetteStretch;
  69358. },
  69359. /**
  69360. * Sets Vignette stretch size.
  69361. */
  69362. set: function (value) {
  69363. this.imageProcessingConfiguration.vignetteStretch = value;
  69364. },
  69365. enumerable: true,
  69366. configurable: true
  69367. });
  69368. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69369. /**
  69370. * Gets Vignette centre X Offset.
  69371. */
  69372. get: function () {
  69373. return this.imageProcessingConfiguration.vignetteCentreX;
  69374. },
  69375. /**
  69376. * Sets Vignette centre X Offset.
  69377. */
  69378. set: function (value) {
  69379. this.imageProcessingConfiguration.vignetteCentreX = value;
  69380. },
  69381. enumerable: true,
  69382. configurable: true
  69383. });
  69384. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69385. /**
  69386. * Gets Vignette centre Y Offset.
  69387. */
  69388. get: function () {
  69389. return this.imageProcessingConfiguration.vignetteCentreY;
  69390. },
  69391. /**
  69392. * Sets Vignette centre Y Offset.
  69393. */
  69394. set: function (value) {
  69395. this.imageProcessingConfiguration.vignetteCentreY = value;
  69396. },
  69397. enumerable: true,
  69398. configurable: true
  69399. });
  69400. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69401. /**
  69402. * Gets Vignette weight or intensity of the vignette effect.
  69403. */
  69404. get: function () {
  69405. return this.imageProcessingConfiguration.vignetteWeight;
  69406. },
  69407. /**
  69408. * Sets Vignette weight or intensity of the vignette effect.
  69409. */
  69410. set: function (value) {
  69411. this.imageProcessingConfiguration.vignetteWeight = value;
  69412. },
  69413. enumerable: true,
  69414. configurable: true
  69415. });
  69416. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69417. /**
  69418. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69419. * if vignetteEnabled is set to true.
  69420. */
  69421. get: function () {
  69422. return this.imageProcessingConfiguration.vignetteColor;
  69423. },
  69424. /**
  69425. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69426. * if vignetteEnabled is set to true.
  69427. */
  69428. set: function (value) {
  69429. this.imageProcessingConfiguration.vignetteColor = value;
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69435. /**
  69436. * Gets Camera field of view used by the Vignette effect.
  69437. */
  69438. get: function () {
  69439. return this.imageProcessingConfiguration.vignetteCameraFov;
  69440. },
  69441. /**
  69442. * Sets Camera field of view used by the Vignette effect.
  69443. */
  69444. set: function (value) {
  69445. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69446. },
  69447. enumerable: true,
  69448. configurable: true
  69449. });
  69450. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69451. /**
  69452. * Gets the vignette blend mode allowing different kind of effect.
  69453. */
  69454. get: function () {
  69455. return this.imageProcessingConfiguration.vignetteBlendMode;
  69456. },
  69457. /**
  69458. * Sets the vignette blend mode allowing different kind of effect.
  69459. */
  69460. set: function (value) {
  69461. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69462. },
  69463. enumerable: true,
  69464. configurable: true
  69465. });
  69466. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69467. /**
  69468. * Gets wether the vignette effect is enabled.
  69469. */
  69470. get: function () {
  69471. return this.imageProcessingConfiguration.vignetteEnabled;
  69472. },
  69473. /**
  69474. * Sets wether the vignette effect is enabled.
  69475. */
  69476. set: function (value) {
  69477. this.imageProcessingConfiguration.vignetteEnabled = value;
  69478. },
  69479. enumerable: true,
  69480. configurable: true
  69481. });
  69482. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69483. /**
  69484. * Gets wether the input of the processing is in Gamma or Linear Space.
  69485. */
  69486. get: function () {
  69487. return this._fromLinearSpace;
  69488. },
  69489. /**
  69490. * Sets wether the input of the processing is in Gamma or Linear Space.
  69491. */
  69492. set: function (value) {
  69493. if (this._fromLinearSpace === value) {
  69494. return;
  69495. }
  69496. this._fromLinearSpace = value;
  69497. this._updateParameters();
  69498. },
  69499. enumerable: true,
  69500. configurable: true
  69501. });
  69502. ImageProcessingPostProcess.prototype.getClassName = function () {
  69503. return "ImageProcessingPostProcess";
  69504. };
  69505. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69506. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69507. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69508. var defines = "";
  69509. for (var define in this._defines) {
  69510. if (this._defines[define]) {
  69511. defines += "#define " + define + ";\r\n";
  69512. }
  69513. }
  69514. var samplers = ["textureSampler"];
  69515. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69516. var uniforms = ["scale"];
  69517. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69518. this.updateEffect(defines, uniforms, samplers);
  69519. };
  69520. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69521. _super.prototype.dispose.call(this, camera);
  69522. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69523. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69524. }
  69525. this.imageProcessingConfiguration.applyByPostProcess = false;
  69526. };
  69527. __decorate([
  69528. BABYLON.serialize()
  69529. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69530. return ImageProcessingPostProcess;
  69531. }(BABYLON.PostProcess));
  69532. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69533. })(BABYLON || (BABYLON = {}));
  69534. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69535. var BABYLON;
  69536. (function (BABYLON) {
  69537. /**
  69538. * The Blur Post Process which blurs an image based on a kernel and direction.
  69539. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69540. */
  69541. var BlurPostProcess = /** @class */ (function (_super) {
  69542. __extends(BlurPostProcess, _super);
  69543. /**
  69544. * Creates a new instance of @see BlurPostProcess
  69545. * @param name The name of the effect.
  69546. * @param direction The direction in which to blur the image.
  69547. * @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.
  69548. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69549. * @param camera The camera to apply the render pass to.
  69550. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69551. * @param engine The engine which the post process will be applied. (default: current engine)
  69552. * @param reusable If the post process can be reused on the same frame. (default: false)
  69553. * @param textureType Type of textures used when performing the post process. (default: 0)
  69554. */
  69555. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69557. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69558. if (defines === void 0) { defines = ""; }
  69559. 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;
  69560. _this.direction = direction;
  69561. _this._packedFloat = false;
  69562. _this._staticDefines = "";
  69563. _this._staticDefines = defines;
  69564. _this.onApplyObservable.add(function (effect) {
  69565. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69566. });
  69567. _this.kernel = kernel;
  69568. return _this;
  69569. }
  69570. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69571. /**
  69572. * Gets the length in pixels of the blur sample region
  69573. */
  69574. get: function () {
  69575. return this._idealKernel;
  69576. },
  69577. /**
  69578. * Sets the length in pixels of the blur sample region
  69579. */
  69580. set: function (v) {
  69581. if (this._idealKernel === v) {
  69582. return;
  69583. }
  69584. v = Math.max(v, 1);
  69585. this._idealKernel = v;
  69586. this._kernel = this._nearestBestKernel(v);
  69587. this._updateParameters();
  69588. },
  69589. enumerable: true,
  69590. configurable: true
  69591. });
  69592. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69593. /**
  69594. * Gets wether or not the blur is unpacking/repacking floats
  69595. */
  69596. get: function () {
  69597. return this._packedFloat;
  69598. },
  69599. /**
  69600. * Sets wether or not the blur needs to unpack/repack floats
  69601. */
  69602. set: function (v) {
  69603. if (this._packedFloat === v) {
  69604. return;
  69605. }
  69606. this._packedFloat = v;
  69607. this._updateParameters();
  69608. },
  69609. enumerable: true,
  69610. configurable: true
  69611. });
  69612. BlurPostProcess.prototype._updateParameters = function () {
  69613. // Generate sampling offsets and weights
  69614. var N = this._kernel;
  69615. var centerIndex = (N - 1) / 2;
  69616. // Generate Gaussian sampling weights over kernel
  69617. var offsets = [];
  69618. var weights = [];
  69619. var totalWeight = 0;
  69620. for (var i = 0; i < N; i++) {
  69621. var u = i / (N - 1);
  69622. var w = this._gaussianWeight(u * 2.0 - 1);
  69623. offsets[i] = (i - centerIndex);
  69624. weights[i] = w;
  69625. totalWeight += w;
  69626. }
  69627. // Normalize weights
  69628. for (var i = 0; i < weights.length; i++) {
  69629. weights[i] /= totalWeight;
  69630. }
  69631. // Optimize: combine samples to take advantage of hardware linear sampling
  69632. // Walk from left to center, combining pairs (symmetrically)
  69633. var linearSamplingWeights = [];
  69634. var linearSamplingOffsets = [];
  69635. var linearSamplingMap = [];
  69636. for (var i = 0; i <= centerIndex; i += 2) {
  69637. var j = Math.min(i + 1, Math.floor(centerIndex));
  69638. var singleCenterSample = i === j;
  69639. if (singleCenterSample) {
  69640. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69641. }
  69642. else {
  69643. var sharedCell = j === centerIndex;
  69644. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69645. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69646. if (offsetLinear === 0) {
  69647. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69648. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69649. }
  69650. else {
  69651. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69652. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69653. }
  69654. }
  69655. }
  69656. for (var i = 0; i < linearSamplingMap.length; i++) {
  69657. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69658. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69659. }
  69660. // Replace with optimized
  69661. offsets = linearSamplingOffsets;
  69662. weights = linearSamplingWeights;
  69663. // Generate shaders
  69664. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69665. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69666. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69667. var defines = "";
  69668. defines += this._staticDefines;
  69669. for (var i = 0; i < varyingCount; i++) {
  69670. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69671. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69672. }
  69673. var depCount = 0;
  69674. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69675. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69676. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69677. depCount++;
  69678. }
  69679. if (this.packedFloat) {
  69680. defines += "#define PACKEDFLOAT 1";
  69681. }
  69682. this.updateEffect(defines, null, null, {
  69683. varyingCount: varyingCount,
  69684. depCount: depCount
  69685. });
  69686. };
  69687. /**
  69688. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69689. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69690. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69691. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69692. * The gaps between physical kernels are compensated for in the weighting of the samples
  69693. * @param idealKernel Ideal blur kernel.
  69694. * @return Nearest best kernel.
  69695. */
  69696. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69697. var v = Math.round(idealKernel);
  69698. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69699. var k = _a[_i];
  69700. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69701. return Math.max(k, 3);
  69702. }
  69703. }
  69704. return Math.max(v, 3);
  69705. };
  69706. /**
  69707. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69708. * @param x The point on the Gaussian distribution to sample.
  69709. * @return the value of the Gaussian function at x.
  69710. */
  69711. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69712. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69713. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69714. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69715. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69716. // truncated at around 1.3% of peak strength.
  69717. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69718. var sigma = (1 / 3);
  69719. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69720. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69721. var weight = (1.0 / denominator) * Math.exp(exponent);
  69722. return weight;
  69723. };
  69724. /**
  69725. * Generates a string that can be used as a floating point number in GLSL.
  69726. * @param x Value to print.
  69727. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69728. * @return GLSL float string.
  69729. */
  69730. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69731. if (decimalFigures === void 0) { decimalFigures = 8; }
  69732. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69733. };
  69734. return BlurPostProcess;
  69735. }(BABYLON.PostProcess));
  69736. BABYLON.BlurPostProcess = BlurPostProcess;
  69737. })(BABYLON || (BABYLON = {}));
  69738. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69739. var BABYLON;
  69740. (function (BABYLON) {
  69741. var Bone = /** @class */ (function (_super) {
  69742. __extends(Bone, _super);
  69743. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69744. if (parentBone === void 0) { parentBone = null; }
  69745. if (localMatrix === void 0) { localMatrix = null; }
  69746. if (restPose === void 0) { restPose = null; }
  69747. if (baseMatrix === void 0) { baseMatrix = null; }
  69748. if (index === void 0) { index = null; }
  69749. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69750. _this.name = name;
  69751. _this.children = new Array();
  69752. _this.animations = new Array();
  69753. // Set this value to map this bone to a different index in the transform matrices.
  69754. // Set this value to -1 to exclude the bone from the transform matrices.
  69755. _this._index = null;
  69756. _this._worldTransform = new BABYLON.Matrix();
  69757. _this._absoluteTransform = new BABYLON.Matrix();
  69758. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69759. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69760. _this._scaleVector = BABYLON.Vector3.One();
  69761. _this._negateScaleChildren = BABYLON.Vector3.One();
  69762. _this._scalingDeterminant = 1;
  69763. _this._skeleton = skeleton;
  69764. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69765. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69766. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69767. _this._index = index;
  69768. skeleton.bones.push(_this);
  69769. _this.setParent(parentBone, false);
  69770. _this._updateDifferenceMatrix();
  69771. return _this;
  69772. }
  69773. Object.defineProperty(Bone.prototype, "_matrix", {
  69774. get: function () {
  69775. return this._localMatrix;
  69776. },
  69777. set: function (val) {
  69778. if (this._localMatrix) {
  69779. this._localMatrix.copyFrom(val);
  69780. }
  69781. else {
  69782. this._localMatrix = val;
  69783. }
  69784. },
  69785. enumerable: true,
  69786. configurable: true
  69787. });
  69788. // Members
  69789. Bone.prototype.getSkeleton = function () {
  69790. return this._skeleton;
  69791. };
  69792. Bone.prototype.getParent = function () {
  69793. return this._parent;
  69794. };
  69795. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69796. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69797. if (this._parent === parent) {
  69798. return;
  69799. }
  69800. if (this._parent) {
  69801. var index = this._parent.children.indexOf(this);
  69802. if (index !== -1) {
  69803. this._parent.children.splice(index, 1);
  69804. }
  69805. }
  69806. this._parent = parent;
  69807. if (this._parent) {
  69808. this._parent.children.push(this);
  69809. }
  69810. if (updateDifferenceMatrix) {
  69811. this._updateDifferenceMatrix();
  69812. }
  69813. };
  69814. Bone.prototype.getLocalMatrix = function () {
  69815. return this._localMatrix;
  69816. };
  69817. Bone.prototype.getBaseMatrix = function () {
  69818. return this._baseMatrix;
  69819. };
  69820. Bone.prototype.getRestPose = function () {
  69821. return this._restPose;
  69822. };
  69823. Bone.prototype.returnToRest = function () {
  69824. this.updateMatrix(this._restPose.clone());
  69825. };
  69826. Bone.prototype.getWorldMatrix = function () {
  69827. return this._worldTransform;
  69828. };
  69829. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69830. return this._invertedAbsoluteTransform;
  69831. };
  69832. Bone.prototype.getAbsoluteTransform = function () {
  69833. return this._absoluteTransform;
  69834. };
  69835. Object.defineProperty(Bone.prototype, "position", {
  69836. // Properties (matches AbstractMesh properties)
  69837. get: function () {
  69838. return this.getPosition();
  69839. },
  69840. set: function (newPosition) {
  69841. this.setPosition(newPosition);
  69842. },
  69843. enumerable: true,
  69844. configurable: true
  69845. });
  69846. Object.defineProperty(Bone.prototype, "rotation", {
  69847. get: function () {
  69848. return this.getRotation();
  69849. },
  69850. set: function (newRotation) {
  69851. this.setRotation(newRotation);
  69852. },
  69853. enumerable: true,
  69854. configurable: true
  69855. });
  69856. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69857. get: function () {
  69858. return this.getRotationQuaternion();
  69859. },
  69860. set: function (newRotation) {
  69861. this.setRotationQuaternion(newRotation);
  69862. },
  69863. enumerable: true,
  69864. configurable: true
  69865. });
  69866. Object.defineProperty(Bone.prototype, "scaling", {
  69867. get: function () {
  69868. return this.getScale();
  69869. },
  69870. set: function (newScaling) {
  69871. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69872. },
  69873. enumerable: true,
  69874. configurable: true
  69875. });
  69876. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  69877. /**
  69878. * Gets the animation properties override
  69879. */
  69880. get: function () {
  69881. return this._skeleton.animationPropertiesOverride;
  69882. },
  69883. enumerable: true,
  69884. configurable: true
  69885. });
  69886. // Methods
  69887. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69888. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69889. this._baseMatrix = matrix.clone();
  69890. this._localMatrix = matrix.clone();
  69891. this._skeleton._markAsDirty();
  69892. if (updateDifferenceMatrix) {
  69893. this._updateDifferenceMatrix();
  69894. }
  69895. };
  69896. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69897. if (!rootMatrix) {
  69898. rootMatrix = this._baseMatrix;
  69899. }
  69900. if (this._parent) {
  69901. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69902. }
  69903. else {
  69904. this._absoluteTransform.copyFrom(rootMatrix);
  69905. }
  69906. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69907. for (var index = 0; index < this.children.length; index++) {
  69908. this.children[index]._updateDifferenceMatrix();
  69909. }
  69910. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69911. };
  69912. Bone.prototype.markAsDirty = function () {
  69913. this._currentRenderId++;
  69914. this._skeleton._markAsDirty();
  69915. };
  69916. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69917. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69918. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69919. // all animation may be coming from a library skeleton, so may need to create animation
  69920. if (this.animations.length === 0) {
  69921. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69922. this.animations[0].setKeys([]);
  69923. }
  69924. // get animation info / verify there is such a range from the source bone
  69925. var sourceRange = source.animations[0].getRange(rangeName);
  69926. if (!sourceRange) {
  69927. return false;
  69928. }
  69929. var from = sourceRange.from;
  69930. var to = sourceRange.to;
  69931. var sourceKeys = source.animations[0].getKeys();
  69932. // rescaling prep
  69933. var sourceBoneLength = source.length;
  69934. var sourceParent = source.getParent();
  69935. var parent = this.getParent();
  69936. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69937. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69938. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69939. var destKeys = this.animations[0].getKeys();
  69940. // loop vars declaration
  69941. var orig;
  69942. var origTranslation;
  69943. var mat;
  69944. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69945. orig = sourceKeys[key];
  69946. if (orig.frame >= from && orig.frame <= to) {
  69947. if (rescaleAsRequired) {
  69948. mat = orig.value.clone();
  69949. // scale based on parent ratio, when bone has parent
  69950. if (parentScalingReqd) {
  69951. origTranslation = mat.getTranslation();
  69952. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69953. // scale based on skeleton dimension ratio when root bone, and value is passed
  69954. }
  69955. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69956. origTranslation = mat.getTranslation();
  69957. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69958. // use original when root bone, and no data for skelDimensionsRatio
  69959. }
  69960. else {
  69961. mat = orig.value;
  69962. }
  69963. }
  69964. else {
  69965. mat = orig.value;
  69966. }
  69967. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69968. }
  69969. }
  69970. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69971. return true;
  69972. };
  69973. /**
  69974. * Translate the bone in local or world space.
  69975. * @param vec The amount to translate the bone.
  69976. * @param space The space that the translation is in.
  69977. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69978. */
  69979. Bone.prototype.translate = function (vec, space, mesh) {
  69980. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69981. var lm = this.getLocalMatrix();
  69982. if (space == BABYLON.Space.LOCAL) {
  69983. lm.m[12] += vec.x;
  69984. lm.m[13] += vec.y;
  69985. lm.m[14] += vec.z;
  69986. }
  69987. else {
  69988. var wm = null;
  69989. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69990. if (mesh) {
  69991. wm = mesh.getWorldMatrix();
  69992. }
  69993. this._skeleton.computeAbsoluteTransforms();
  69994. var tmat = Bone._tmpMats[0];
  69995. var tvec = Bone._tmpVecs[0];
  69996. if (this._parent) {
  69997. if (mesh && wm) {
  69998. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69999. tmat.multiplyToRef(wm, tmat);
  70000. }
  70001. else {
  70002. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70003. }
  70004. }
  70005. tmat.m[12] = 0;
  70006. tmat.m[13] = 0;
  70007. tmat.m[14] = 0;
  70008. tmat.invert();
  70009. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  70010. lm.m[12] += tvec.x;
  70011. lm.m[13] += tvec.y;
  70012. lm.m[14] += tvec.z;
  70013. }
  70014. this.markAsDirty();
  70015. };
  70016. /**
  70017. * Set the postion of the bone in local or world space.
  70018. * @param position The position to set the bone.
  70019. * @param space The space that the position is in.
  70020. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70021. */
  70022. Bone.prototype.setPosition = function (position, space, mesh) {
  70023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70024. var lm = this.getLocalMatrix();
  70025. if (space == BABYLON.Space.LOCAL) {
  70026. lm.m[12] = position.x;
  70027. lm.m[13] = position.y;
  70028. lm.m[14] = position.z;
  70029. }
  70030. else {
  70031. var wm = null;
  70032. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70033. if (mesh) {
  70034. wm = mesh.getWorldMatrix();
  70035. }
  70036. this._skeleton.computeAbsoluteTransforms();
  70037. var tmat = Bone._tmpMats[0];
  70038. var vec = Bone._tmpVecs[0];
  70039. if (this._parent) {
  70040. if (mesh && wm) {
  70041. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70042. tmat.multiplyToRef(wm, tmat);
  70043. }
  70044. else {
  70045. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70046. }
  70047. }
  70048. tmat.invert();
  70049. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70050. lm.m[12] = vec.x;
  70051. lm.m[13] = vec.y;
  70052. lm.m[14] = vec.z;
  70053. }
  70054. this.markAsDirty();
  70055. };
  70056. /**
  70057. * Set the absolute postion of the bone (world space).
  70058. * @param position The position to set the bone.
  70059. * @param mesh The mesh that this bone is attached to.
  70060. */
  70061. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70062. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70063. };
  70064. /**
  70065. * Set the scale of the bone on the x, y and z axes.
  70066. * @param x The scale of the bone on the x axis.
  70067. * @param x The scale of the bone on the y axis.
  70068. * @param z The scale of the bone on the z axis.
  70069. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70070. */
  70071. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70072. if (scaleChildren === void 0) { scaleChildren = false; }
  70073. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70074. if (!scaleChildren) {
  70075. this._negateScaleChildren.x = 1 / x;
  70076. this._negateScaleChildren.y = 1 / y;
  70077. this._negateScaleChildren.z = 1 / z;
  70078. }
  70079. this._syncScaleVector();
  70080. }
  70081. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70082. };
  70083. /**
  70084. * Scale the bone on the x, y and z axes.
  70085. * @param x The amount to scale the bone on the x axis.
  70086. * @param x The amount to scale the bone on the y axis.
  70087. * @param z The amount to scale the bone on the z axis.
  70088. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70089. */
  70090. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70091. if (scaleChildren === void 0) { scaleChildren = false; }
  70092. var locMat = this.getLocalMatrix();
  70093. var origLocMat = Bone._tmpMats[0];
  70094. origLocMat.copyFrom(locMat);
  70095. var origLocMatInv = Bone._tmpMats[1];
  70096. origLocMatInv.copyFrom(origLocMat);
  70097. origLocMatInv.invert();
  70098. var scaleMat = Bone._tmpMats[2];
  70099. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70100. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70101. this._scaleVector.x *= x;
  70102. this._scaleVector.y *= y;
  70103. this._scaleVector.z *= z;
  70104. locMat.multiplyToRef(origLocMatInv, locMat);
  70105. locMat.multiplyToRef(scaleMat, locMat);
  70106. locMat.multiplyToRef(origLocMat, locMat);
  70107. var parent = this.getParent();
  70108. if (parent) {
  70109. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70110. }
  70111. else {
  70112. this.getAbsoluteTransform().copyFrom(locMat);
  70113. }
  70114. var len = this.children.length;
  70115. scaleMat.invert();
  70116. for (var i = 0; i < len; i++) {
  70117. var child = this.children[i];
  70118. var cm = child.getLocalMatrix();
  70119. cm.multiplyToRef(scaleMat, cm);
  70120. var lm = child.getLocalMatrix();
  70121. lm.m[12] *= x;
  70122. lm.m[13] *= y;
  70123. lm.m[14] *= z;
  70124. }
  70125. this.computeAbsoluteTransforms();
  70126. if (scaleChildren) {
  70127. for (var i = 0; i < len; i++) {
  70128. this.children[i].scale(x, y, z, scaleChildren);
  70129. }
  70130. }
  70131. this.markAsDirty();
  70132. };
  70133. /**
  70134. * Set the yaw, pitch, and roll of the bone in local or world space.
  70135. * @param yaw The rotation of the bone on the y axis.
  70136. * @param pitch The rotation of the bone on the x axis.
  70137. * @param roll The rotation of the bone on the z axis.
  70138. * @param space The space that the axes of rotation are in.
  70139. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70140. */
  70141. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70142. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70143. var rotMat = Bone._tmpMats[0];
  70144. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70145. var rotMatInv = Bone._tmpMats[1];
  70146. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70147. rotMatInv.multiplyToRef(rotMat, rotMat);
  70148. this._rotateWithMatrix(rotMat, space, mesh);
  70149. };
  70150. /**
  70151. * Rotate the bone on an axis in local or world space.
  70152. * @param axis The axis to rotate the bone on.
  70153. * @param amount The amount to rotate the bone.
  70154. * @param space The space that the axis is in.
  70155. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70156. */
  70157. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70158. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70159. var rmat = Bone._tmpMats[0];
  70160. rmat.m[12] = 0;
  70161. rmat.m[13] = 0;
  70162. rmat.m[14] = 0;
  70163. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70164. this._rotateWithMatrix(rmat, space, mesh);
  70165. };
  70166. /**
  70167. * Set the rotation of the bone to a particular axis angle in local or world space.
  70168. * @param axis The axis to rotate the bone on.
  70169. * @param angle The angle that the bone should be rotated to.
  70170. * @param space The space that the axis is in.
  70171. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70172. */
  70173. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70175. var rotMat = Bone._tmpMats[0];
  70176. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70177. var rotMatInv = Bone._tmpMats[1];
  70178. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70179. rotMatInv.multiplyToRef(rotMat, rotMat);
  70180. this._rotateWithMatrix(rotMat, space, mesh);
  70181. };
  70182. /**
  70183. * Set the euler rotation of the bone in local of world space.
  70184. * @param rotation The euler rotation that the bone should be set to.
  70185. * @param space The space that the rotation is in.
  70186. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70187. */
  70188. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70190. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70191. };
  70192. /**
  70193. * Set the quaternion rotation of the bone in local of world space.
  70194. * @param quat The quaternion rotation that the bone should be set to.
  70195. * @param space The space that the rotation is in.
  70196. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70197. */
  70198. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70200. var rotMatInv = Bone._tmpMats[0];
  70201. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70202. var rotMat = Bone._tmpMats[1];
  70203. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70204. rotMatInv.multiplyToRef(rotMat, rotMat);
  70205. this._rotateWithMatrix(rotMat, space, mesh);
  70206. };
  70207. /**
  70208. * Set the rotation matrix of the bone in local of world space.
  70209. * @param rotMat The rotation matrix that the bone should be set to.
  70210. * @param space The space that the rotation is in.
  70211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70212. */
  70213. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70214. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70215. var rotMatInv = Bone._tmpMats[0];
  70216. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70217. var rotMat2 = Bone._tmpMats[1];
  70218. rotMat2.copyFrom(rotMat);
  70219. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70220. this._rotateWithMatrix(rotMat2, space, mesh);
  70221. };
  70222. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70223. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70224. var lmat = this.getLocalMatrix();
  70225. var lx = lmat.m[12];
  70226. var ly = lmat.m[13];
  70227. var lz = lmat.m[14];
  70228. var parent = this.getParent();
  70229. var parentScale = Bone._tmpMats[3];
  70230. var parentScaleInv = Bone._tmpMats[4];
  70231. if (parent) {
  70232. if (space == BABYLON.Space.WORLD) {
  70233. if (mesh) {
  70234. parentScale.copyFrom(mesh.getWorldMatrix());
  70235. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70236. }
  70237. else {
  70238. parentScale.copyFrom(parent.getAbsoluteTransform());
  70239. }
  70240. }
  70241. else {
  70242. parentScale = parent._scaleMatrix;
  70243. }
  70244. parentScaleInv.copyFrom(parentScale);
  70245. parentScaleInv.invert();
  70246. lmat.multiplyToRef(parentScale, lmat);
  70247. lmat.multiplyToRef(rmat, lmat);
  70248. lmat.multiplyToRef(parentScaleInv, lmat);
  70249. }
  70250. else {
  70251. if (space == BABYLON.Space.WORLD && mesh) {
  70252. parentScale.copyFrom(mesh.getWorldMatrix());
  70253. parentScaleInv.copyFrom(parentScale);
  70254. parentScaleInv.invert();
  70255. lmat.multiplyToRef(parentScale, lmat);
  70256. lmat.multiplyToRef(rmat, lmat);
  70257. lmat.multiplyToRef(parentScaleInv, lmat);
  70258. }
  70259. else {
  70260. lmat.multiplyToRef(rmat, lmat);
  70261. }
  70262. }
  70263. lmat.m[12] = lx;
  70264. lmat.m[13] = ly;
  70265. lmat.m[14] = lz;
  70266. this.computeAbsoluteTransforms();
  70267. this.markAsDirty();
  70268. };
  70269. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70270. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70271. if (space == BABYLON.Space.WORLD) {
  70272. var scaleMatrix = Bone._tmpMats[2];
  70273. scaleMatrix.copyFrom(this._scaleMatrix);
  70274. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70275. if (mesh) {
  70276. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70277. var meshScale = Bone._tmpMats[3];
  70278. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70279. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70280. }
  70281. rotMatInv.invert();
  70282. scaleMatrix.m[0] *= this._scalingDeterminant;
  70283. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70284. }
  70285. else {
  70286. rotMatInv.copyFrom(this.getLocalMatrix());
  70287. rotMatInv.invert();
  70288. var scaleMatrix = Bone._tmpMats[2];
  70289. scaleMatrix.copyFrom(this._scaleMatrix);
  70290. if (this._parent) {
  70291. var pscaleMatrix = Bone._tmpMats[3];
  70292. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70293. pscaleMatrix.invert();
  70294. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70295. }
  70296. else {
  70297. scaleMatrix.m[0] *= this._scalingDeterminant;
  70298. }
  70299. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70300. }
  70301. };
  70302. /**
  70303. * Get the scale of the bone
  70304. * @returns the scale of the bone
  70305. */
  70306. Bone.prototype.getScale = function () {
  70307. return this._scaleVector.clone();
  70308. };
  70309. /**
  70310. * Copy the scale of the bone to a vector3.
  70311. * @param result The vector3 to copy the scale to
  70312. */
  70313. Bone.prototype.getScaleToRef = function (result) {
  70314. result.copyFrom(this._scaleVector);
  70315. };
  70316. /**
  70317. * Get the position of the bone in local or world space.
  70318. * @param space The space that the returned position is in.
  70319. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70320. * @returns The position of the bone
  70321. */
  70322. Bone.prototype.getPosition = function (space, mesh) {
  70323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70324. if (mesh === void 0) { mesh = null; }
  70325. var pos = BABYLON.Vector3.Zero();
  70326. this.getPositionToRef(space, mesh, pos);
  70327. return pos;
  70328. };
  70329. /**
  70330. * Copy the position of the bone to a vector3 in local or world space.
  70331. * @param space The space that the returned position is in.
  70332. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70333. * @param result The vector3 to copy the position to.
  70334. */
  70335. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70337. if (space == BABYLON.Space.LOCAL) {
  70338. var lm = this.getLocalMatrix();
  70339. result.x = lm.m[12];
  70340. result.y = lm.m[13];
  70341. result.z = lm.m[14];
  70342. }
  70343. else {
  70344. var wm = null;
  70345. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70346. if (mesh) {
  70347. wm = mesh.getWorldMatrix();
  70348. }
  70349. this._skeleton.computeAbsoluteTransforms();
  70350. var tmat = Bone._tmpMats[0];
  70351. if (mesh && wm) {
  70352. tmat.copyFrom(this.getAbsoluteTransform());
  70353. tmat.multiplyToRef(wm, tmat);
  70354. }
  70355. else {
  70356. tmat = this.getAbsoluteTransform();
  70357. }
  70358. result.x = tmat.m[12];
  70359. result.y = tmat.m[13];
  70360. result.z = tmat.m[14];
  70361. }
  70362. };
  70363. /**
  70364. * Get the absolute position of the bone (world space).
  70365. * @param mesh The mesh that this bone is attached to.
  70366. * @returns The absolute position of the bone
  70367. */
  70368. Bone.prototype.getAbsolutePosition = function (mesh) {
  70369. if (mesh === void 0) { mesh = null; }
  70370. var pos = BABYLON.Vector3.Zero();
  70371. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70372. return pos;
  70373. };
  70374. /**
  70375. * Copy the absolute position of the bone (world space) to the result param.
  70376. * @param mesh The mesh that this bone is attached to.
  70377. * @param result The vector3 to copy the absolute position to.
  70378. */
  70379. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70380. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70381. };
  70382. /**
  70383. * Compute the absolute transforms of this bone and its children.
  70384. */
  70385. Bone.prototype.computeAbsoluteTransforms = function () {
  70386. if (this._parent) {
  70387. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70388. }
  70389. else {
  70390. this._absoluteTransform.copyFrom(this._localMatrix);
  70391. var poseMatrix = this._skeleton.getPoseMatrix();
  70392. if (poseMatrix) {
  70393. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70394. }
  70395. }
  70396. var children = this.children;
  70397. var len = children.length;
  70398. for (var i = 0; i < len; i++) {
  70399. children[i].computeAbsoluteTransforms();
  70400. }
  70401. };
  70402. Bone.prototype._syncScaleVector = function () {
  70403. var lm = this.getLocalMatrix();
  70404. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70405. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70406. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70407. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70408. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70409. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70410. this._scaleVector.x = xs * Math.sqrt(xsq);
  70411. this._scaleVector.y = ys * Math.sqrt(ysq);
  70412. this._scaleVector.z = zs * Math.sqrt(zsq);
  70413. if (this._parent) {
  70414. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70415. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70416. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70417. }
  70418. 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);
  70419. };
  70420. /**
  70421. * Get the world direction from an axis that is in the local space of the bone.
  70422. * @param localAxis The local direction that is used to compute the world direction.
  70423. * @param mesh The mesh that this bone is attached to.
  70424. * @returns The world direction
  70425. */
  70426. Bone.prototype.getDirection = function (localAxis, mesh) {
  70427. if (mesh === void 0) { mesh = null; }
  70428. var result = BABYLON.Vector3.Zero();
  70429. this.getDirectionToRef(localAxis, mesh, result);
  70430. return result;
  70431. };
  70432. /**
  70433. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70434. * @param localAxis The local direction that is used to compute the world direction.
  70435. * @param mesh The mesh that this bone is attached to.
  70436. * @param result The vector3 that the world direction will be copied to.
  70437. */
  70438. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70439. if (mesh === void 0) { mesh = null; }
  70440. var wm = null;
  70441. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70442. if (mesh) {
  70443. wm = mesh.getWorldMatrix();
  70444. }
  70445. this._skeleton.computeAbsoluteTransforms();
  70446. var mat = Bone._tmpMats[0];
  70447. mat.copyFrom(this.getAbsoluteTransform());
  70448. if (mesh && wm) {
  70449. mat.multiplyToRef(wm, mat);
  70450. }
  70451. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70452. result.normalize();
  70453. };
  70454. /**
  70455. * Get the euler rotation of the bone in local or world space.
  70456. * @param space The space that the rotation should be in.
  70457. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70458. * @returns The euler rotation
  70459. */
  70460. Bone.prototype.getRotation = function (space, mesh) {
  70461. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70462. if (mesh === void 0) { mesh = null; }
  70463. var result = BABYLON.Vector3.Zero();
  70464. this.getRotationToRef(space, mesh, result);
  70465. return result;
  70466. };
  70467. /**
  70468. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70469. * @param space The space that the rotation should be in.
  70470. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70471. * @param result The vector3 that the rotation should be copied to.
  70472. */
  70473. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70474. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70475. if (mesh === void 0) { mesh = null; }
  70476. var quat = Bone._tmpQuat;
  70477. this.getRotationQuaternionToRef(space, mesh, quat);
  70478. quat.toEulerAnglesToRef(result);
  70479. };
  70480. /**
  70481. * Get the quaternion rotation of the bone in either local or world space.
  70482. * @param space The space that the rotation should be in.
  70483. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70484. * @returns The quaternion rotation
  70485. */
  70486. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70488. if (mesh === void 0) { mesh = null; }
  70489. var result = BABYLON.Quaternion.Identity();
  70490. this.getRotationQuaternionToRef(space, mesh, result);
  70491. return result;
  70492. };
  70493. /**
  70494. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70495. * @param space The space that the rotation should be in.
  70496. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70497. * @param result The quaternion that the rotation should be copied to.
  70498. */
  70499. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70501. if (mesh === void 0) { mesh = null; }
  70502. if (space == BABYLON.Space.LOCAL) {
  70503. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70504. }
  70505. else {
  70506. var mat = Bone._tmpMats[0];
  70507. var amat = this.getAbsoluteTransform();
  70508. if (mesh) {
  70509. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70510. }
  70511. else {
  70512. mat.copyFrom(amat);
  70513. }
  70514. mat.m[0] *= this._scalingDeterminant;
  70515. mat.m[1] *= this._scalingDeterminant;
  70516. mat.m[2] *= this._scalingDeterminant;
  70517. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70518. }
  70519. };
  70520. /**
  70521. * Get the rotation matrix of the bone in local or world space.
  70522. * @param space The space that the rotation should be in.
  70523. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70524. * @returns The rotation matrix
  70525. */
  70526. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70527. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70528. var result = BABYLON.Matrix.Identity();
  70529. this.getRotationMatrixToRef(space, mesh, result);
  70530. return result;
  70531. };
  70532. /**
  70533. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70534. * @param space The space that the rotation should be in.
  70535. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70536. * @param result The quaternion that the rotation should be copied to.
  70537. */
  70538. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70539. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70540. if (space == BABYLON.Space.LOCAL) {
  70541. this.getLocalMatrix().getRotationMatrixToRef(result);
  70542. }
  70543. else {
  70544. var mat = Bone._tmpMats[0];
  70545. var amat = this.getAbsoluteTransform();
  70546. if (mesh) {
  70547. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70548. }
  70549. else {
  70550. mat.copyFrom(amat);
  70551. }
  70552. mat.m[0] *= this._scalingDeterminant;
  70553. mat.m[1] *= this._scalingDeterminant;
  70554. mat.m[2] *= this._scalingDeterminant;
  70555. mat.getRotationMatrixToRef(result);
  70556. }
  70557. };
  70558. /**
  70559. * Get the world position of a point that is in the local space of the bone.
  70560. * @param position The local position
  70561. * @param mesh The mesh that this bone is attached to.
  70562. * @returns The world position
  70563. */
  70564. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70565. if (mesh === void 0) { mesh = null; }
  70566. var result = BABYLON.Vector3.Zero();
  70567. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70568. return result;
  70569. };
  70570. /**
  70571. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70572. * @param position The local position
  70573. * @param mesh The mesh that this bone is attached to.
  70574. * @param result The vector3 that the world position should be copied to.
  70575. */
  70576. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70577. if (mesh === void 0) { mesh = null; }
  70578. var wm = null;
  70579. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70580. if (mesh) {
  70581. wm = mesh.getWorldMatrix();
  70582. }
  70583. this._skeleton.computeAbsoluteTransforms();
  70584. var tmat = Bone._tmpMats[0];
  70585. if (mesh && wm) {
  70586. tmat.copyFrom(this.getAbsoluteTransform());
  70587. tmat.multiplyToRef(wm, tmat);
  70588. }
  70589. else {
  70590. tmat = this.getAbsoluteTransform();
  70591. }
  70592. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70593. };
  70594. /**
  70595. * Get the local position of a point that is in world space.
  70596. * @param position The world position
  70597. * @param mesh The mesh that this bone is attached to.
  70598. * @returns The local position
  70599. */
  70600. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70601. if (mesh === void 0) { mesh = null; }
  70602. var result = BABYLON.Vector3.Zero();
  70603. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70604. return result;
  70605. };
  70606. /**
  70607. * Get the local position of a point that is in world space and copy it to the result param.
  70608. * @param position The world position
  70609. * @param mesh The mesh that this bone is attached to.
  70610. * @param result The vector3 that the local position should be copied to.
  70611. */
  70612. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70613. if (mesh === void 0) { mesh = null; }
  70614. var wm = null;
  70615. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70616. if (mesh) {
  70617. wm = mesh.getWorldMatrix();
  70618. }
  70619. this._skeleton.computeAbsoluteTransforms();
  70620. var tmat = Bone._tmpMats[0];
  70621. tmat.copyFrom(this.getAbsoluteTransform());
  70622. if (mesh && wm) {
  70623. tmat.multiplyToRef(wm, tmat);
  70624. }
  70625. tmat.invert();
  70626. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70627. };
  70628. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70629. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70630. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70631. return Bone;
  70632. }(BABYLON.Node));
  70633. BABYLON.Bone = Bone;
  70634. })(BABYLON || (BABYLON = {}));
  70635. //# sourceMappingURL=babylon.bone.js.map
  70636. var BABYLON;
  70637. (function (BABYLON) {
  70638. var BoneIKController = /** @class */ (function () {
  70639. function BoneIKController(mesh, bone, options) {
  70640. this.targetPosition = BABYLON.Vector3.Zero();
  70641. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70642. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70643. this.poleAngle = 0;
  70644. this.slerpAmount = 1;
  70645. this._bone1Quat = BABYLON.Quaternion.Identity();
  70646. this._bone1Mat = BABYLON.Matrix.Identity();
  70647. this._bone2Ang = Math.PI;
  70648. this._maxAngle = Math.PI;
  70649. this._rightHandedSystem = false;
  70650. this._bendAxis = BABYLON.Vector3.Right();
  70651. this._slerping = false;
  70652. this._adjustRoll = 0;
  70653. this._bone2 = bone;
  70654. this._bone1 = bone.getParent();
  70655. if (!this._bone1) {
  70656. return;
  70657. }
  70658. this.mesh = mesh;
  70659. var bonePos = bone.getPosition();
  70660. if (bone.getAbsoluteTransform().determinant() > 0) {
  70661. this._rightHandedSystem = true;
  70662. this._bendAxis.x = 0;
  70663. this._bendAxis.y = 0;
  70664. this._bendAxis.z = -1;
  70665. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70666. this._adjustRoll = Math.PI * .5;
  70667. this._bendAxis.z = 1;
  70668. }
  70669. }
  70670. if (this._bone1.length) {
  70671. var boneScale1 = this._bone1.getScale();
  70672. var boneScale2 = this._bone2.getScale();
  70673. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70674. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70675. }
  70676. else if (this._bone1.children[0]) {
  70677. mesh.computeWorldMatrix(true);
  70678. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70679. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70680. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70681. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70682. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70683. }
  70684. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70685. this.maxAngle = Math.PI;
  70686. if (options) {
  70687. if (options.targetMesh) {
  70688. this.targetMesh = options.targetMesh;
  70689. this.targetMesh.computeWorldMatrix(true);
  70690. }
  70691. if (options.poleTargetMesh) {
  70692. this.poleTargetMesh = options.poleTargetMesh;
  70693. this.poleTargetMesh.computeWorldMatrix(true);
  70694. }
  70695. else if (options.poleTargetBone) {
  70696. this.poleTargetBone = options.poleTargetBone;
  70697. }
  70698. else if (this._bone1.getParent()) {
  70699. this.poleTargetBone = this._bone1.getParent();
  70700. }
  70701. if (options.poleTargetLocalOffset) {
  70702. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70703. }
  70704. if (options.poleAngle) {
  70705. this.poleAngle = options.poleAngle;
  70706. }
  70707. if (options.bendAxis) {
  70708. this._bendAxis.copyFrom(options.bendAxis);
  70709. }
  70710. if (options.maxAngle) {
  70711. this.maxAngle = options.maxAngle;
  70712. }
  70713. if (options.slerpAmount) {
  70714. this.slerpAmount = options.slerpAmount;
  70715. }
  70716. }
  70717. }
  70718. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70719. get: function () {
  70720. return this._maxAngle;
  70721. },
  70722. set: function (value) {
  70723. this._setMaxAngle(value);
  70724. },
  70725. enumerable: true,
  70726. configurable: true
  70727. });
  70728. BoneIKController.prototype._setMaxAngle = function (ang) {
  70729. if (ang < 0) {
  70730. ang = 0;
  70731. }
  70732. if (ang > Math.PI || ang == undefined) {
  70733. ang = Math.PI;
  70734. }
  70735. this._maxAngle = ang;
  70736. var a = this._bone1Length;
  70737. var b = this._bone2Length;
  70738. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70739. };
  70740. BoneIKController.prototype.update = function () {
  70741. var bone1 = this._bone1;
  70742. if (!bone1) {
  70743. return;
  70744. }
  70745. var target = this.targetPosition;
  70746. var poleTarget = this.poleTargetPosition;
  70747. var mat1 = BoneIKController._tmpMats[0];
  70748. var mat2 = BoneIKController._tmpMats[1];
  70749. if (this.targetMesh) {
  70750. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70751. }
  70752. if (this.poleTargetBone) {
  70753. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70754. }
  70755. else if (this.poleTargetMesh) {
  70756. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70757. }
  70758. var bonePos = BoneIKController._tmpVecs[0];
  70759. var zaxis = BoneIKController._tmpVecs[1];
  70760. var xaxis = BoneIKController._tmpVecs[2];
  70761. var yaxis = BoneIKController._tmpVecs[3];
  70762. var upAxis = BoneIKController._tmpVecs[4];
  70763. var _tmpQuat = BoneIKController._tmpQuat;
  70764. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70765. poleTarget.subtractToRef(bonePos, upAxis);
  70766. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70767. upAxis.y = 1;
  70768. }
  70769. else {
  70770. upAxis.normalize();
  70771. }
  70772. target.subtractToRef(bonePos, yaxis);
  70773. yaxis.normalize();
  70774. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70775. zaxis.normalize();
  70776. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70777. xaxis.normalize();
  70778. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70779. var a = this._bone1Length;
  70780. var b = this._bone2Length;
  70781. var c = BABYLON.Vector3.Distance(bonePos, target);
  70782. if (this._maxReach > 0) {
  70783. c = Math.min(this._maxReach, c);
  70784. }
  70785. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70786. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70787. if (acosa > 1) {
  70788. acosa = 1;
  70789. }
  70790. if (acosb > 1) {
  70791. acosb = 1;
  70792. }
  70793. if (acosa < -1) {
  70794. acosa = -1;
  70795. }
  70796. if (acosb < -1) {
  70797. acosb = -1;
  70798. }
  70799. var angA = Math.acos(acosa);
  70800. var angB = Math.acos(acosb);
  70801. var angC = -angA - angB;
  70802. if (this._rightHandedSystem) {
  70803. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70804. mat2.multiplyToRef(mat1, mat1);
  70805. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70806. mat2.multiplyToRef(mat1, mat1);
  70807. }
  70808. else {
  70809. var _tmpVec = BoneIKController._tmpVecs[5];
  70810. _tmpVec.copyFrom(this._bendAxis);
  70811. _tmpVec.x *= -1;
  70812. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70813. mat2.multiplyToRef(mat1, mat1);
  70814. }
  70815. if (this.poleAngle) {
  70816. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70817. mat1.multiplyToRef(mat2, mat1);
  70818. }
  70819. if (this._bone1) {
  70820. if (this.slerpAmount < 1) {
  70821. if (!this._slerping) {
  70822. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70823. }
  70824. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70825. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70826. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70827. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70828. this._slerping = true;
  70829. }
  70830. else {
  70831. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70832. this._bone1Mat.copyFrom(mat1);
  70833. this._slerping = false;
  70834. }
  70835. }
  70836. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70837. this._bone2Ang = angC;
  70838. };
  70839. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70840. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70841. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70842. return BoneIKController;
  70843. }());
  70844. BABYLON.BoneIKController = BoneIKController;
  70845. })(BABYLON || (BABYLON = {}));
  70846. //# sourceMappingURL=babylon.boneIKController.js.map
  70847. var BABYLON;
  70848. (function (BABYLON) {
  70849. var BoneLookController = /** @class */ (function () {
  70850. /**
  70851. * Create a BoneLookController
  70852. * @param mesh the mesh that the bone belongs to
  70853. * @param bone the bone that will be looking to the target
  70854. * @param target the target Vector3 to look at
  70855. * @param settings optional settings:
  70856. * - maxYaw: the maximum angle the bone will yaw to
  70857. * - minYaw: the minimum angle the bone will yaw to
  70858. * - maxPitch: the maximum angle the bone will pitch to
  70859. * - minPitch: the minimum angle the bone will yaw to
  70860. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70861. * - upAxis: the up axis of the coordinate system
  70862. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70863. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70864. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70865. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70866. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70867. * - adjustRoll: used to make an adjustment to the roll of the bone
  70868. **/
  70869. function BoneLookController(mesh, bone, target, options) {
  70870. /**
  70871. * The up axis of the coordinate system that is used when the bone is rotated.
  70872. */
  70873. this.upAxis = BABYLON.Vector3.Up();
  70874. /**
  70875. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70876. */
  70877. this.upAxisSpace = BABYLON.Space.LOCAL;
  70878. /**
  70879. * Used to make an adjustment to the yaw of the bone.
  70880. */
  70881. this.adjustYaw = 0;
  70882. /**
  70883. * Used to make an adjustment to the pitch of the bone.
  70884. */
  70885. this.adjustPitch = 0;
  70886. /**
  70887. * Used to make an adjustment to the roll of the bone.
  70888. */
  70889. this.adjustRoll = 0;
  70890. /**
  70891. * 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).
  70892. */
  70893. this.slerpAmount = 1;
  70894. this._boneQuat = BABYLON.Quaternion.Identity();
  70895. this._slerping = false;
  70896. this._firstFrameSkipped = false;
  70897. this._fowardAxis = BABYLON.Vector3.Forward();
  70898. this.mesh = mesh;
  70899. this.bone = bone;
  70900. this.target = target;
  70901. if (options) {
  70902. if (options.adjustYaw) {
  70903. this.adjustYaw = options.adjustYaw;
  70904. }
  70905. if (options.adjustPitch) {
  70906. this.adjustPitch = options.adjustPitch;
  70907. }
  70908. if (options.adjustRoll) {
  70909. this.adjustRoll = options.adjustRoll;
  70910. }
  70911. if (options.maxYaw != null) {
  70912. this.maxYaw = options.maxYaw;
  70913. }
  70914. else {
  70915. this.maxYaw = Math.PI;
  70916. }
  70917. if (options.minYaw != null) {
  70918. this.minYaw = options.minYaw;
  70919. }
  70920. else {
  70921. this.minYaw = -Math.PI;
  70922. }
  70923. if (options.maxPitch != null) {
  70924. this.maxPitch = options.maxPitch;
  70925. }
  70926. else {
  70927. this.maxPitch = Math.PI;
  70928. }
  70929. if (options.minPitch != null) {
  70930. this.minPitch = options.minPitch;
  70931. }
  70932. else {
  70933. this.minPitch = -Math.PI;
  70934. }
  70935. if (options.slerpAmount != null) {
  70936. this.slerpAmount = options.slerpAmount;
  70937. }
  70938. if (options.upAxis != null) {
  70939. this.upAxis = options.upAxis;
  70940. }
  70941. if (options.upAxisSpace != null) {
  70942. this.upAxisSpace = options.upAxisSpace;
  70943. }
  70944. if (options.yawAxis != null || options.pitchAxis != null) {
  70945. var newYawAxis = BABYLON.Axis.Y;
  70946. var newPitchAxis = BABYLON.Axis.X;
  70947. if (options.yawAxis != null) {
  70948. newYawAxis = options.yawAxis.clone();
  70949. newYawAxis.normalize();
  70950. }
  70951. if (options.pitchAxis != null) {
  70952. newPitchAxis = options.pitchAxis.clone();
  70953. newPitchAxis.normalize();
  70954. }
  70955. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70956. this._transformYawPitch = BABYLON.Matrix.Identity();
  70957. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70958. this._transformYawPitchInv = this._transformYawPitch.clone();
  70959. this._transformYawPitch.invert();
  70960. }
  70961. }
  70962. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70963. this.upAxisSpace = BABYLON.Space.LOCAL;
  70964. }
  70965. }
  70966. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70967. /**
  70968. * Get/set the minimum yaw angle that the bone can look to.
  70969. */
  70970. get: function () {
  70971. return this._minYaw;
  70972. },
  70973. set: function (value) {
  70974. this._minYaw = value;
  70975. this._minYawSin = Math.sin(value);
  70976. this._minYawCos = Math.cos(value);
  70977. if (this._maxYaw != null) {
  70978. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70979. this._yawRange = this._maxYaw - this._minYaw;
  70980. }
  70981. },
  70982. enumerable: true,
  70983. configurable: true
  70984. });
  70985. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  70986. /**
  70987. * Get/set the maximum yaw angle that the bone can look to.
  70988. */
  70989. get: function () {
  70990. return this._maxYaw;
  70991. },
  70992. set: function (value) {
  70993. this._maxYaw = value;
  70994. this._maxYawSin = Math.sin(value);
  70995. this._maxYawCos = Math.cos(value);
  70996. if (this._minYaw != null) {
  70997. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70998. this._yawRange = this._maxYaw - this._minYaw;
  70999. }
  71000. },
  71001. enumerable: true,
  71002. configurable: true
  71003. });
  71004. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  71005. /**
  71006. * Get/set the minimum pitch angle that the bone can look to.
  71007. */
  71008. get: function () {
  71009. return this._minPitch;
  71010. },
  71011. set: function (value) {
  71012. this._minPitch = value;
  71013. this._minPitchTan = Math.tan(value);
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71019. /**
  71020. * Get/set the maximum pitch angle that the bone can look to.
  71021. */
  71022. get: function () {
  71023. return this._maxPitch;
  71024. },
  71025. set: function (value) {
  71026. this._maxPitch = value;
  71027. this._maxPitchTan = Math.tan(value);
  71028. },
  71029. enumerable: true,
  71030. configurable: true
  71031. });
  71032. /**
  71033. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71034. */
  71035. BoneLookController.prototype.update = function () {
  71036. //skip the first frame when slerping so that the mesh rotation is correct
  71037. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71038. this._firstFrameSkipped = true;
  71039. return;
  71040. }
  71041. var bone = this.bone;
  71042. var bonePos = BoneLookController._tmpVecs[0];
  71043. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71044. var target = this.target;
  71045. var _tmpMat1 = BoneLookController._tmpMats[0];
  71046. var _tmpMat2 = BoneLookController._tmpMats[1];
  71047. var mesh = this.mesh;
  71048. var parentBone = bone.getParent();
  71049. var upAxis = BoneLookController._tmpVecs[1];
  71050. upAxis.copyFrom(this.upAxis);
  71051. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71052. if (this._transformYawPitch) {
  71053. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71054. }
  71055. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71056. }
  71057. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71058. mesh.getDirectionToRef(upAxis, upAxis);
  71059. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71060. upAxis.normalize();
  71061. }
  71062. }
  71063. var checkYaw = false;
  71064. var checkPitch = false;
  71065. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71066. checkYaw = true;
  71067. }
  71068. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71069. checkPitch = true;
  71070. }
  71071. if (checkYaw || checkPitch) {
  71072. var spaceMat = BoneLookController._tmpMats[2];
  71073. var spaceMatInv = BoneLookController._tmpMats[3];
  71074. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71075. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71076. }
  71077. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71078. spaceMat.copyFrom(mesh.getWorldMatrix());
  71079. }
  71080. else {
  71081. var forwardAxis = BoneLookController._tmpVecs[2];
  71082. forwardAxis.copyFrom(this._fowardAxis);
  71083. if (this._transformYawPitch) {
  71084. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71085. }
  71086. if (parentBone) {
  71087. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71088. }
  71089. else {
  71090. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71091. }
  71092. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71093. rightAxis.normalize();
  71094. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71095. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71096. }
  71097. spaceMat.invertToRef(spaceMatInv);
  71098. var xzlen = null;
  71099. if (checkPitch) {
  71100. var localTarget = BoneLookController._tmpVecs[3];
  71101. target.subtractToRef(bonePos, localTarget);
  71102. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71103. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71104. var pitch = Math.atan2(localTarget.y, xzlen);
  71105. var newPitch = pitch;
  71106. if (pitch > this._maxPitch) {
  71107. localTarget.y = this._maxPitchTan * xzlen;
  71108. newPitch = this._maxPitch;
  71109. }
  71110. else if (pitch < this._minPitch) {
  71111. localTarget.y = this._minPitchTan * xzlen;
  71112. newPitch = this._minPitch;
  71113. }
  71114. if (pitch != newPitch) {
  71115. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71116. localTarget.addInPlace(bonePos);
  71117. target = localTarget;
  71118. }
  71119. }
  71120. if (checkYaw) {
  71121. var localTarget = BoneLookController._tmpVecs[4];
  71122. target.subtractToRef(bonePos, localTarget);
  71123. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71124. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71125. var newYaw = yaw;
  71126. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71127. if (xzlen == null) {
  71128. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71129. }
  71130. if (this._yawRange > Math.PI) {
  71131. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71132. localTarget.z = this._maxYawCos * xzlen;
  71133. localTarget.x = this._maxYawSin * xzlen;
  71134. newYaw = this._maxYaw;
  71135. }
  71136. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71137. localTarget.z = this._minYawCos * xzlen;
  71138. localTarget.x = this._minYawSin * xzlen;
  71139. newYaw = this._minYaw;
  71140. }
  71141. }
  71142. else {
  71143. if (yaw > this._maxYaw) {
  71144. localTarget.z = this._maxYawCos * xzlen;
  71145. localTarget.x = this._maxYawSin * xzlen;
  71146. newYaw = this._maxYaw;
  71147. }
  71148. else if (yaw < this._minYaw) {
  71149. localTarget.z = this._minYawCos * xzlen;
  71150. localTarget.x = this._minYawSin * xzlen;
  71151. newYaw = this._minYaw;
  71152. }
  71153. }
  71154. }
  71155. if (this._slerping && this._yawRange > Math.PI) {
  71156. //are we going to be crossing into the min/max region?
  71157. var boneFwd = BoneLookController._tmpVecs[8];
  71158. boneFwd.copyFrom(BABYLON.Axis.Z);
  71159. if (this._transformYawPitch) {
  71160. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71161. }
  71162. var boneRotMat = BoneLookController._tmpMats[4];
  71163. this._boneQuat.toRotationMatrix(boneRotMat);
  71164. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71165. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71166. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71167. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71168. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71169. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71170. if (angBtwTar > angBtwMidYaw) {
  71171. if (xzlen == null) {
  71172. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71173. }
  71174. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71175. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71176. if (angBtwMin < angBtwMax) {
  71177. newYaw = boneYaw + Math.PI * .75;
  71178. localTarget.z = Math.cos(newYaw) * xzlen;
  71179. localTarget.x = Math.sin(newYaw) * xzlen;
  71180. }
  71181. else {
  71182. newYaw = boneYaw - Math.PI * .75;
  71183. localTarget.z = Math.cos(newYaw) * xzlen;
  71184. localTarget.x = Math.sin(newYaw) * xzlen;
  71185. }
  71186. }
  71187. }
  71188. if (yaw != newYaw) {
  71189. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71190. localTarget.addInPlace(bonePos);
  71191. target = localTarget;
  71192. }
  71193. }
  71194. }
  71195. var zaxis = BoneLookController._tmpVecs[5];
  71196. var xaxis = BoneLookController._tmpVecs[6];
  71197. var yaxis = BoneLookController._tmpVecs[7];
  71198. var _tmpQuat = BoneLookController._tmpQuat;
  71199. target.subtractToRef(bonePos, zaxis);
  71200. zaxis.normalize();
  71201. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71202. xaxis.normalize();
  71203. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71204. yaxis.normalize();
  71205. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71206. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71207. return;
  71208. }
  71209. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71210. return;
  71211. }
  71212. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71213. return;
  71214. }
  71215. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71216. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71217. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71218. }
  71219. if (this.slerpAmount < 1) {
  71220. if (!this._slerping) {
  71221. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71222. }
  71223. if (this._transformYawPitch) {
  71224. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71225. }
  71226. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71227. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71228. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71229. this._slerping = true;
  71230. }
  71231. else {
  71232. if (this._transformYawPitch) {
  71233. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71234. }
  71235. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71236. this._slerping = false;
  71237. }
  71238. };
  71239. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71240. var angDiff = ang2 - ang1;
  71241. angDiff %= Math.PI * 2;
  71242. if (angDiff > Math.PI) {
  71243. angDiff -= Math.PI * 2;
  71244. }
  71245. else if (angDiff < -Math.PI) {
  71246. angDiff += Math.PI * 2;
  71247. }
  71248. return angDiff;
  71249. };
  71250. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71251. ang1 %= (2 * Math.PI);
  71252. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71253. ang2 %= (2 * Math.PI);
  71254. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71255. var ab = 0;
  71256. if (ang1 < ang2) {
  71257. ab = ang2 - ang1;
  71258. }
  71259. else {
  71260. ab = ang1 - ang2;
  71261. }
  71262. if (ab > Math.PI) {
  71263. ab = Math.PI * 2 - ab;
  71264. }
  71265. return ab;
  71266. };
  71267. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71268. ang %= (2 * Math.PI);
  71269. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71270. ang1 %= (2 * Math.PI);
  71271. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71272. ang2 %= (2 * Math.PI);
  71273. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71274. if (ang1 < ang2) {
  71275. if (ang > ang1 && ang < ang2) {
  71276. return true;
  71277. }
  71278. }
  71279. else {
  71280. if (ang > ang2 && ang < ang1) {
  71281. return true;
  71282. }
  71283. }
  71284. return false;
  71285. };
  71286. 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()];
  71287. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71288. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71289. return BoneLookController;
  71290. }());
  71291. BABYLON.BoneLookController = BoneLookController;
  71292. })(BABYLON || (BABYLON = {}));
  71293. //# sourceMappingURL=babylon.boneLookController.js.map
  71294. var BABYLON;
  71295. (function (BABYLON) {
  71296. var Skeleton = /** @class */ (function () {
  71297. function Skeleton(name, id, scene) {
  71298. this.name = name;
  71299. this.id = id;
  71300. this.bones = new Array();
  71301. this.needInitialSkinMatrix = false;
  71302. this._isDirty = true;
  71303. this._meshesWithPoseMatrix = new Array();
  71304. this._identity = BABYLON.Matrix.Identity();
  71305. this._ranges = {};
  71306. this._lastAbsoluteTransformsUpdateId = -1;
  71307. /**
  71308. * Specifies if the skeleton should be serialized.
  71309. */
  71310. this.doNotSerialize = false;
  71311. // Events
  71312. /**
  71313. * An event triggered before computing the skeleton's matrices
  71314. * @type {BABYLON.Observable}
  71315. */
  71316. this.onBeforeComputeObservable = new BABYLON.Observable();
  71317. this.bones = [];
  71318. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71319. scene.skeletons.push(this);
  71320. //make sure it will recalculate the matrix next time prepare is called.
  71321. this._isDirty = true;
  71322. }
  71323. // Members
  71324. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71325. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71326. return mesh._bonesTransformMatrices;
  71327. }
  71328. if (!this._transformMatrices) {
  71329. this.prepare();
  71330. }
  71331. return this._transformMatrices;
  71332. };
  71333. Skeleton.prototype.getScene = function () {
  71334. return this._scene;
  71335. };
  71336. // Methods
  71337. /**
  71338. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71339. */
  71340. Skeleton.prototype.toString = function (fullDetails) {
  71341. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71342. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71343. if (fullDetails) {
  71344. ret += ", Ranges: {";
  71345. var first = true;
  71346. for (var name_1 in this._ranges) {
  71347. if (first) {
  71348. ret += ", ";
  71349. first = false;
  71350. }
  71351. ret += name_1;
  71352. }
  71353. ret += "}";
  71354. }
  71355. return ret;
  71356. };
  71357. /**
  71358. * Get bone's index searching by name
  71359. * @param {string} name is bone's name to search for
  71360. * @return {number} Indice of the bone. Returns -1 if not found
  71361. */
  71362. Skeleton.prototype.getBoneIndexByName = function (name) {
  71363. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71364. if (this.bones[boneIndex].name === name) {
  71365. return boneIndex;
  71366. }
  71367. }
  71368. return -1;
  71369. };
  71370. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71371. // check name not already in use
  71372. if (!this._ranges[name]) {
  71373. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71374. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71375. if (this.bones[i].animations[0]) {
  71376. this.bones[i].animations[0].createRange(name, from, to);
  71377. }
  71378. }
  71379. }
  71380. };
  71381. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71382. if (deleteFrames === void 0) { deleteFrames = true; }
  71383. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71384. if (this.bones[i].animations[0]) {
  71385. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71386. }
  71387. }
  71388. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71389. };
  71390. Skeleton.prototype.getAnimationRange = function (name) {
  71391. return this._ranges[name];
  71392. };
  71393. /**
  71394. * Returns as an Array, all AnimationRanges defined on this skeleton
  71395. */
  71396. Skeleton.prototype.getAnimationRanges = function () {
  71397. var animationRanges = [];
  71398. var name;
  71399. var i = 0;
  71400. for (name in this._ranges) {
  71401. animationRanges[i] = this._ranges[name];
  71402. i++;
  71403. }
  71404. return animationRanges;
  71405. };
  71406. /**
  71407. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71408. */
  71409. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71410. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71411. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71412. return false;
  71413. }
  71414. var ret = true;
  71415. var frameOffset = this._getHighestAnimationFrame() + 1;
  71416. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71417. var boneDict = {};
  71418. var sourceBones = source.bones;
  71419. var nBones;
  71420. var i;
  71421. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71422. boneDict[sourceBones[i].name] = sourceBones[i];
  71423. }
  71424. if (this.bones.length !== sourceBones.length) {
  71425. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71426. ret = false;
  71427. }
  71428. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71429. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71430. var boneName = this.bones[i].name;
  71431. var sourceBone = boneDict[boneName];
  71432. if (sourceBone) {
  71433. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71434. }
  71435. else {
  71436. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71437. ret = false;
  71438. }
  71439. }
  71440. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71441. var range = source.getAnimationRange(name);
  71442. if (range) {
  71443. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71444. }
  71445. return ret;
  71446. };
  71447. Skeleton.prototype.returnToRest = function () {
  71448. for (var index = 0; index < this.bones.length; index++) {
  71449. this.bones[index].returnToRest();
  71450. }
  71451. };
  71452. Skeleton.prototype._getHighestAnimationFrame = function () {
  71453. var ret = 0;
  71454. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71455. if (this.bones[i].animations[0]) {
  71456. var highest = this.bones[i].animations[0].getHighestFrame();
  71457. if (ret < highest) {
  71458. ret = highest;
  71459. }
  71460. }
  71461. }
  71462. return ret;
  71463. };
  71464. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71465. var range = this.getAnimationRange(name);
  71466. if (!range) {
  71467. return null;
  71468. }
  71469. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71470. };
  71471. Skeleton.prototype._markAsDirty = function () {
  71472. this._isDirty = true;
  71473. };
  71474. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71475. this._meshesWithPoseMatrix.push(mesh);
  71476. };
  71477. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71478. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71479. if (index > -1) {
  71480. this._meshesWithPoseMatrix.splice(index, 1);
  71481. }
  71482. };
  71483. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71484. this.onBeforeComputeObservable.notifyObservers(this);
  71485. for (var index = 0; index < this.bones.length; index++) {
  71486. var bone = this.bones[index];
  71487. var parentBone = bone.getParent();
  71488. if (parentBone) {
  71489. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71490. }
  71491. else {
  71492. if (initialSkinMatrix) {
  71493. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71494. }
  71495. else {
  71496. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71497. }
  71498. }
  71499. if (bone._index !== -1) {
  71500. var mappedIndex = bone._index === null ? index : bone._index;
  71501. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71502. }
  71503. }
  71504. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71505. };
  71506. Skeleton.prototype.prepare = function () {
  71507. if (!this._isDirty) {
  71508. return;
  71509. }
  71510. if (this.needInitialSkinMatrix) {
  71511. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71512. var mesh = this._meshesWithPoseMatrix[index];
  71513. var poseMatrix = mesh.getPoseMatrix();
  71514. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71515. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71516. }
  71517. if (this._synchronizedWithMesh !== mesh) {
  71518. this._synchronizedWithMesh = mesh;
  71519. // Prepare bones
  71520. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71521. var bone = this.bones[boneIndex];
  71522. if (!bone.getParent()) {
  71523. var matrix = bone.getBaseMatrix();
  71524. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71525. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71526. }
  71527. }
  71528. }
  71529. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71530. }
  71531. }
  71532. else {
  71533. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71534. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71535. }
  71536. this._computeTransformMatrices(this._transformMatrices, null);
  71537. }
  71538. this._isDirty = false;
  71539. this._scene._activeBones.addCount(this.bones.length, false);
  71540. };
  71541. Skeleton.prototype.getAnimatables = function () {
  71542. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71543. this._animatables = [];
  71544. for (var index = 0; index < this.bones.length; index++) {
  71545. this._animatables.push(this.bones[index]);
  71546. }
  71547. }
  71548. return this._animatables;
  71549. };
  71550. Skeleton.prototype.clone = function (name, id) {
  71551. var result = new Skeleton(name, id || name, this._scene);
  71552. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71553. for (var index = 0; index < this.bones.length; index++) {
  71554. var source = this.bones[index];
  71555. var parentBone = null;
  71556. var parent_1 = source.getParent();
  71557. if (parent_1) {
  71558. var parentIndex = this.bones.indexOf(parent_1);
  71559. parentBone = result.bones[parentIndex];
  71560. }
  71561. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71562. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71563. }
  71564. if (this._ranges) {
  71565. result._ranges = {};
  71566. for (var rangeName in this._ranges) {
  71567. var range = this._ranges[rangeName];
  71568. if (range) {
  71569. result._ranges[rangeName] = range.clone();
  71570. }
  71571. }
  71572. }
  71573. this._isDirty = true;
  71574. return result;
  71575. };
  71576. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71577. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71578. this.bones.forEach(function (bone) {
  71579. bone.animations.forEach(function (animation) {
  71580. animation.enableBlending = true;
  71581. animation.blendingSpeed = blendingSpeed;
  71582. });
  71583. });
  71584. };
  71585. Skeleton.prototype.dispose = function () {
  71586. this._meshesWithPoseMatrix = [];
  71587. // Animations
  71588. this.getScene().stopAnimation(this);
  71589. // Remove from scene
  71590. this.getScene().removeSkeleton(this);
  71591. };
  71592. Skeleton.prototype.serialize = function () {
  71593. var serializationObject = {};
  71594. serializationObject.name = this.name;
  71595. serializationObject.id = this.id;
  71596. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71597. serializationObject.bones = [];
  71598. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71599. for (var index = 0; index < this.bones.length; index++) {
  71600. var bone = this.bones[index];
  71601. var parent_2 = bone.getParent();
  71602. var serializedBone = {
  71603. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71604. name: bone.name,
  71605. matrix: bone.getBaseMatrix().toArray(),
  71606. rest: bone.getRestPose().toArray()
  71607. };
  71608. serializationObject.bones.push(serializedBone);
  71609. if (bone.length) {
  71610. serializedBone.length = bone.length;
  71611. }
  71612. if (bone.animations && bone.animations.length > 0) {
  71613. serializedBone.animation = bone.animations[0].serialize();
  71614. }
  71615. serializationObject.ranges = [];
  71616. for (var name in this._ranges) {
  71617. var source = this._ranges[name];
  71618. if (!source) {
  71619. continue;
  71620. }
  71621. var range = {};
  71622. range.name = name;
  71623. range.from = source.from;
  71624. range.to = source.to;
  71625. serializationObject.ranges.push(range);
  71626. }
  71627. }
  71628. return serializationObject;
  71629. };
  71630. Skeleton.Parse = function (parsedSkeleton, scene) {
  71631. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71632. if (parsedSkeleton.dimensionsAtRest) {
  71633. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71634. }
  71635. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71636. var index;
  71637. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71638. var parsedBone = parsedSkeleton.bones[index];
  71639. var parentBone = null;
  71640. if (parsedBone.parentBoneIndex > -1) {
  71641. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71642. }
  71643. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71644. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71645. if (parsedBone.length) {
  71646. bone.length = parsedBone.length;
  71647. }
  71648. if (parsedBone.animation) {
  71649. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71650. }
  71651. }
  71652. // placed after bones, so createAnimationRange can cascade down
  71653. if (parsedSkeleton.ranges) {
  71654. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71655. var data = parsedSkeleton.ranges[index];
  71656. skeleton.createAnimationRange(data.name, data.from, data.to);
  71657. }
  71658. }
  71659. return skeleton;
  71660. };
  71661. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71662. if (forceUpdate === void 0) { forceUpdate = false; }
  71663. var renderId = this._scene.getRenderId();
  71664. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71665. this.bones[0].computeAbsoluteTransforms();
  71666. this._lastAbsoluteTransformsUpdateId = renderId;
  71667. }
  71668. };
  71669. Skeleton.prototype.getPoseMatrix = function () {
  71670. var poseMatrix = null;
  71671. if (this._meshesWithPoseMatrix.length > 0) {
  71672. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71673. }
  71674. return poseMatrix;
  71675. };
  71676. Skeleton.prototype.sortBones = function () {
  71677. var bones = new Array();
  71678. var visited = new Array(this.bones.length);
  71679. for (var index = 0; index < this.bones.length; index++) {
  71680. this._sortBones(index, bones, visited);
  71681. }
  71682. this.bones = bones;
  71683. };
  71684. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71685. if (visited[index]) {
  71686. return;
  71687. }
  71688. visited[index] = true;
  71689. var bone = this.bones[index];
  71690. if (bone._index === undefined) {
  71691. bone._index = index;
  71692. }
  71693. var parentBone = bone.getParent();
  71694. if (parentBone) {
  71695. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71696. }
  71697. bones.push(bone);
  71698. };
  71699. return Skeleton;
  71700. }());
  71701. BABYLON.Skeleton = Skeleton;
  71702. })(BABYLON || (BABYLON = {}));
  71703. //# sourceMappingURL=babylon.skeleton.js.map
  71704. var BABYLON;
  71705. (function (BABYLON) {
  71706. var SphericalPolynomial = /** @class */ (function () {
  71707. function SphericalPolynomial() {
  71708. this.x = BABYLON.Vector3.Zero();
  71709. this.y = BABYLON.Vector3.Zero();
  71710. this.z = BABYLON.Vector3.Zero();
  71711. this.xx = BABYLON.Vector3.Zero();
  71712. this.yy = BABYLON.Vector3.Zero();
  71713. this.zz = BABYLON.Vector3.Zero();
  71714. this.xy = BABYLON.Vector3.Zero();
  71715. this.yz = BABYLON.Vector3.Zero();
  71716. this.zx = BABYLON.Vector3.Zero();
  71717. }
  71718. SphericalPolynomial.prototype.addAmbient = function (color) {
  71719. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71720. this.xx = this.xx.add(colorVector);
  71721. this.yy = this.yy.add(colorVector);
  71722. this.zz = this.zz.add(colorVector);
  71723. };
  71724. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71725. var result = new SphericalPolynomial();
  71726. result.x = harmonics.L11.scale(1.02333);
  71727. result.y = harmonics.L1_1.scale(1.02333);
  71728. result.z = harmonics.L10.scale(1.02333);
  71729. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71730. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71731. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71732. result.yz = harmonics.L2_1.scale(0.858086);
  71733. result.zx = harmonics.L21.scale(0.858086);
  71734. result.xy = harmonics.L2_2.scale(0.858086);
  71735. result.scale(1.0 / Math.PI);
  71736. return result;
  71737. };
  71738. SphericalPolynomial.prototype.scale = function (scale) {
  71739. this.x = this.x.scale(scale);
  71740. this.y = this.y.scale(scale);
  71741. this.z = this.z.scale(scale);
  71742. this.xx = this.xx.scale(scale);
  71743. this.yy = this.yy.scale(scale);
  71744. this.zz = this.zz.scale(scale);
  71745. this.yz = this.yz.scale(scale);
  71746. this.zx = this.zx.scale(scale);
  71747. this.xy = this.xy.scale(scale);
  71748. };
  71749. return SphericalPolynomial;
  71750. }());
  71751. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71752. var SphericalHarmonics = /** @class */ (function () {
  71753. function SphericalHarmonics() {
  71754. this.L00 = BABYLON.Vector3.Zero();
  71755. this.L1_1 = BABYLON.Vector3.Zero();
  71756. this.L10 = BABYLON.Vector3.Zero();
  71757. this.L11 = BABYLON.Vector3.Zero();
  71758. this.L2_2 = BABYLON.Vector3.Zero();
  71759. this.L2_1 = BABYLON.Vector3.Zero();
  71760. this.L20 = BABYLON.Vector3.Zero();
  71761. this.L21 = BABYLON.Vector3.Zero();
  71762. this.L22 = BABYLON.Vector3.Zero();
  71763. }
  71764. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71765. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71766. var c = colorVector.scale(deltaSolidAngle);
  71767. this.L00 = this.L00.add(c.scale(0.282095));
  71768. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71769. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71770. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71771. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71772. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71773. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71774. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71775. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71776. };
  71777. SphericalHarmonics.prototype.scale = function (scale) {
  71778. this.L00 = this.L00.scale(scale);
  71779. this.L1_1 = this.L1_1.scale(scale);
  71780. this.L10 = this.L10.scale(scale);
  71781. this.L11 = this.L11.scale(scale);
  71782. this.L2_2 = this.L2_2.scale(scale);
  71783. this.L2_1 = this.L2_1.scale(scale);
  71784. this.L20 = this.L20.scale(scale);
  71785. this.L21 = this.L21.scale(scale);
  71786. this.L22 = this.L22.scale(scale);
  71787. };
  71788. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71789. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71790. //
  71791. // E_lm = A_l * L_lm
  71792. //
  71793. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71794. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71795. // the scaling factors are given in equation 9.
  71796. // Constant (Band 0)
  71797. this.L00 = this.L00.scale(3.141593);
  71798. // Linear (Band 1)
  71799. this.L1_1 = this.L1_1.scale(2.094395);
  71800. this.L10 = this.L10.scale(2.094395);
  71801. this.L11 = this.L11.scale(2.094395);
  71802. // Quadratic (Band 2)
  71803. this.L2_2 = this.L2_2.scale(0.785398);
  71804. this.L2_1 = this.L2_1.scale(0.785398);
  71805. this.L20 = this.L20.scale(0.785398);
  71806. this.L21 = this.L21.scale(0.785398);
  71807. this.L22 = this.L22.scale(0.785398);
  71808. };
  71809. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71810. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71811. // L = (1/pi) * E * rho
  71812. //
  71813. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71814. this.scale(1.0 / Math.PI);
  71815. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71816. // (The pixel shader must apply albedo after texture fetches, etc).
  71817. };
  71818. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71819. var result = new SphericalHarmonics();
  71820. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71821. result.L1_1 = polynomial.y.scale(0.977204);
  71822. result.L10 = polynomial.z.scale(0.977204);
  71823. result.L11 = polynomial.x.scale(0.977204);
  71824. result.L2_2 = polynomial.xy.scale(1.16538);
  71825. result.L2_1 = polynomial.yz.scale(1.16538);
  71826. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71827. result.L21 = polynomial.zx.scale(1.16538);
  71828. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71829. result.scale(Math.PI);
  71830. return result;
  71831. };
  71832. return SphericalHarmonics;
  71833. }());
  71834. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71835. })(BABYLON || (BABYLON = {}));
  71836. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71837. var BABYLON;
  71838. (function (BABYLON) {
  71839. var FileFaceOrientation = /** @class */ (function () {
  71840. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71841. this.name = name;
  71842. this.worldAxisForNormal = worldAxisForNormal;
  71843. this.worldAxisForFileX = worldAxisForFileX;
  71844. this.worldAxisForFileY = worldAxisForFileY;
  71845. }
  71846. return FileFaceOrientation;
  71847. }());
  71848. ;
  71849. /**
  71850. * Helper class dealing with the extraction of spherical polynomial dataArray
  71851. * from a cube map.
  71852. */
  71853. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71854. function CubeMapToSphericalPolynomialTools() {
  71855. }
  71856. /**
  71857. * Converts a texture to the according Spherical Polynomial data.
  71858. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71859. *
  71860. * @param texture The texture to extract the information from.
  71861. * @return The Spherical Polynomial data.
  71862. */
  71863. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71864. if (!texture.isCube) {
  71865. // Only supports cube Textures currently.
  71866. return null;
  71867. }
  71868. var size = texture.getSize().width;
  71869. var right = texture.readPixels(0);
  71870. var left = texture.readPixels(1);
  71871. var up;
  71872. var down;
  71873. if (texture.isRenderTarget) {
  71874. up = texture.readPixels(3);
  71875. down = texture.readPixels(2);
  71876. }
  71877. else {
  71878. up = texture.readPixels(2);
  71879. down = texture.readPixels(3);
  71880. }
  71881. var front = texture.readPixels(4);
  71882. var back = texture.readPixels(5);
  71883. var gammaSpace = texture.gammaSpace;
  71884. // Always read as RGBA.
  71885. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71886. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71887. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71888. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71889. }
  71890. var cubeInfo = {
  71891. size: size,
  71892. right: right,
  71893. left: left,
  71894. up: up,
  71895. down: down,
  71896. front: front,
  71897. back: back,
  71898. format: format,
  71899. type: type,
  71900. gammaSpace: gammaSpace,
  71901. };
  71902. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71903. };
  71904. /**
  71905. * Converts a cubemap to the according Spherical Polynomial data.
  71906. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71907. *
  71908. * @param cubeInfo The Cube map to extract the information from.
  71909. * @return The Spherical Polynomial data.
  71910. */
  71911. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71912. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71913. var totalSolidAngle = 0.0;
  71914. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71915. var du = 2.0 / cubeInfo.size;
  71916. var dv = du;
  71917. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71918. var minUV = du * 0.5 - 1.0;
  71919. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71920. var fileFace = this.FileFaces[faceIndex];
  71921. var dataArray = cubeInfo[fileFace.name];
  71922. var v = minUV;
  71923. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71924. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71925. // Because SP is still linear, so summation is fine in that basis.
  71926. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71927. for (var y = 0; y < cubeInfo.size; y++) {
  71928. var u = minUV;
  71929. for (var x = 0; x < cubeInfo.size; x++) {
  71930. // World direction (not normalised)
  71931. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71932. worldDirection.normalize();
  71933. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71934. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71935. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71936. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71937. // Handle Integer types.
  71938. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71939. r /= 255;
  71940. g /= 255;
  71941. b /= 255;
  71942. }
  71943. // Handle Gamma space textures.
  71944. if (cubeInfo.gammaSpace) {
  71945. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71946. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71947. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71948. }
  71949. var color = new BABYLON.Color3(r, g, b);
  71950. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71951. totalSolidAngle += deltaSolidAngle;
  71952. u += du;
  71953. }
  71954. v += dv;
  71955. }
  71956. }
  71957. // Solid angle for entire sphere is 4*pi
  71958. var sphereSolidAngle = 4.0 * Math.PI;
  71959. // Adjust the solid angle to allow for how many faces we processed.
  71960. var facesProcessed = 6.0;
  71961. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71962. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71963. // This is needed because the numerical integration over the cube uses a
  71964. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71965. // and also to compensate for accumulative error due to float precision in the summation.
  71966. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71967. sphericalHarmonics.scale(correctionFactor);
  71968. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71969. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71970. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71971. };
  71972. CubeMapToSphericalPolynomialTools.FileFaces = [
  71973. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71974. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  71975. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  71976. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  71977. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  71978. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  71979. ];
  71980. return CubeMapToSphericalPolynomialTools;
  71981. }());
  71982. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  71983. })(BABYLON || (BABYLON = {}));
  71984. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  71985. var BABYLON;
  71986. (function (BABYLON) {
  71987. /**
  71988. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  71989. */
  71990. var PanoramaToCubeMapTools = /** @class */ (function () {
  71991. function PanoramaToCubeMapTools() {
  71992. }
  71993. /**
  71994. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  71995. *
  71996. * @param float32Array The source data.
  71997. * @param inputWidth The width of the input panorama.
  71998. * @param inputhHeight The height of the input panorama.
  71999. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  72000. * @return The cubemap data
  72001. */
  72002. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  72003. if (!float32Array) {
  72004. throw "ConvertPanoramaToCubemap: input cannot be null";
  72005. }
  72006. if (float32Array.length != inputWidth * inputHeight * 3) {
  72007. throw "ConvertPanoramaToCubemap: input size is wrong";
  72008. }
  72009. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  72010. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  72011. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  72012. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  72013. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  72014. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  72015. return {
  72016. front: textureFront,
  72017. back: textureBack,
  72018. left: textureLeft,
  72019. right: textureRight,
  72020. up: textureUp,
  72021. down: textureDown,
  72022. size: size,
  72023. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72024. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72025. gammaSpace: false,
  72026. };
  72027. };
  72028. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72029. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72030. var textureArray = new Float32Array(buffer);
  72031. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72032. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72033. var dy = 1 / texSize;
  72034. var fy = 0;
  72035. for (var y = 0; y < texSize; y++) {
  72036. var xv1 = faceData[0];
  72037. var xv2 = faceData[2];
  72038. for (var x = 0; x < texSize; x++) {
  72039. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72040. v.normalize();
  72041. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72042. // 3 channels per pixels
  72043. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72044. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72045. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72046. xv1 = xv1.add(rotDX1);
  72047. xv2 = xv2.add(rotDX2);
  72048. }
  72049. fy += dy;
  72050. }
  72051. return textureArray;
  72052. };
  72053. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72054. var theta = Math.atan2(vDir.z, vDir.x);
  72055. var phi = Math.acos(vDir.y);
  72056. while (theta < -Math.PI)
  72057. theta += 2 * Math.PI;
  72058. while (theta > Math.PI)
  72059. theta -= 2 * Math.PI;
  72060. var dx = theta / Math.PI;
  72061. var dy = phi / Math.PI;
  72062. // recenter.
  72063. dx = dx * 0.5 + 0.5;
  72064. var px = Math.round(dx * inputWidth);
  72065. if (px < 0)
  72066. px = 0;
  72067. else if (px >= inputWidth)
  72068. px = inputWidth - 1;
  72069. var py = Math.round(dy * inputHeight);
  72070. if (py < 0)
  72071. py = 0;
  72072. else if (py >= inputHeight)
  72073. py = inputHeight - 1;
  72074. var inputY = (inputHeight - py - 1);
  72075. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72076. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72077. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72078. return {
  72079. r: r,
  72080. g: g,
  72081. b: b
  72082. };
  72083. };
  72084. PanoramaToCubeMapTools.FACE_FRONT = [
  72085. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72086. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72087. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72088. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72089. ];
  72090. PanoramaToCubeMapTools.FACE_BACK = [
  72091. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72092. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72093. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72094. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72095. ];
  72096. PanoramaToCubeMapTools.FACE_RIGHT = [
  72097. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72098. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72099. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72100. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72101. ];
  72102. PanoramaToCubeMapTools.FACE_LEFT = [
  72103. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72104. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72105. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72106. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72107. ];
  72108. PanoramaToCubeMapTools.FACE_DOWN = [
  72109. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72110. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72111. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72112. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72113. ];
  72114. PanoramaToCubeMapTools.FACE_UP = [
  72115. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72116. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72117. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72118. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72119. ];
  72120. return PanoramaToCubeMapTools;
  72121. }());
  72122. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72123. })(BABYLON || (BABYLON = {}));
  72124. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72125. var BABYLON;
  72126. (function (BABYLON) {
  72127. ;
  72128. /**
  72129. * This groups tools to convert HDR texture to native colors array.
  72130. */
  72131. var HDRTools = /** @class */ (function () {
  72132. function HDRTools() {
  72133. }
  72134. HDRTools.Ldexp = function (mantissa, exponent) {
  72135. if (exponent > 1023) {
  72136. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72137. }
  72138. if (exponent < -1074) {
  72139. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72140. }
  72141. return mantissa * Math.pow(2, exponent);
  72142. };
  72143. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72144. if (exponent > 0) {
  72145. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72146. float32array[index + 0] = red * exponent;
  72147. float32array[index + 1] = green * exponent;
  72148. float32array[index + 2] = blue * exponent;
  72149. }
  72150. else {
  72151. float32array[index + 0] = 0;
  72152. float32array[index + 1] = 0;
  72153. float32array[index + 2] = 0;
  72154. }
  72155. };
  72156. HDRTools.readStringLine = function (uint8array, startIndex) {
  72157. var line = "";
  72158. var character = "";
  72159. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72160. character = String.fromCharCode(uint8array[i]);
  72161. if (character == "\n") {
  72162. break;
  72163. }
  72164. line += character;
  72165. }
  72166. return line;
  72167. };
  72168. /**
  72169. * Reads header information from an RGBE texture stored in a native array.
  72170. * More information on this format are available here:
  72171. * https://en.wikipedia.org/wiki/RGBE_image_format
  72172. *
  72173. * @param uint8array The binary file stored in native array.
  72174. * @return The header information.
  72175. */
  72176. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72177. var height = 0;
  72178. var width = 0;
  72179. var line = this.readStringLine(uint8array, 0);
  72180. if (line[0] != '#' || line[1] != '?') {
  72181. throw "Bad HDR Format.";
  72182. }
  72183. var endOfHeader = false;
  72184. var findFormat = false;
  72185. var lineIndex = 0;
  72186. do {
  72187. lineIndex += (line.length + 1);
  72188. line = this.readStringLine(uint8array, lineIndex);
  72189. if (line == "FORMAT=32-bit_rle_rgbe") {
  72190. findFormat = true;
  72191. }
  72192. else if (line.length == 0) {
  72193. endOfHeader = true;
  72194. }
  72195. } while (!endOfHeader);
  72196. if (!findFormat) {
  72197. throw "HDR Bad header format, unsupported FORMAT";
  72198. }
  72199. lineIndex += (line.length + 1);
  72200. line = this.readStringLine(uint8array, lineIndex);
  72201. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72202. var match = sizeRegexp.exec(line);
  72203. // TODO. Support +Y and -X if needed.
  72204. if (!match || match.length < 3) {
  72205. throw "HDR Bad header format, no size";
  72206. }
  72207. width = parseInt(match[2]);
  72208. height = parseInt(match[1]);
  72209. if (width < 8 || width > 0x7fff) {
  72210. throw "HDR Bad header format, unsupported size";
  72211. }
  72212. lineIndex += (line.length + 1);
  72213. return {
  72214. height: height,
  72215. width: width,
  72216. dataPosition: lineIndex
  72217. };
  72218. };
  72219. /**
  72220. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72221. * This RGBE texture needs to store the information as a panorama.
  72222. *
  72223. * More information on this format are available here:
  72224. * https://en.wikipedia.org/wiki/RGBE_image_format
  72225. *
  72226. * @param buffer The binary file stored in an array buffer.
  72227. * @param size The expected size of the extracted cubemap.
  72228. * @return The Cube Map information.
  72229. */
  72230. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72231. var uint8array = new Uint8Array(buffer);
  72232. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72233. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72234. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72235. return cubeMapData;
  72236. };
  72237. /**
  72238. * Returns the pixels data extracted from an RGBE texture.
  72239. * This pixels will be stored left to right up to down in the R G B order in one array.
  72240. *
  72241. * More information on this format are available here:
  72242. * https://en.wikipedia.org/wiki/RGBE_image_format
  72243. *
  72244. * @param uint8array The binary file stored in an array buffer.
  72245. * @param hdrInfo The header information of the file.
  72246. * @return The pixels data in RGB right to left up to down order.
  72247. */
  72248. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72249. // Keep for multi format supports.
  72250. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72251. };
  72252. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72253. var num_scanlines = hdrInfo.height;
  72254. var scanline_width = hdrInfo.width;
  72255. var a, b, c, d, count;
  72256. var dataIndex = hdrInfo.dataPosition;
  72257. var index = 0, endIndex = 0, i = 0;
  72258. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72259. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72260. // 3 channels of 4 bytes per pixel in float.
  72261. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72262. var resultArray = new Float32Array(resultBuffer);
  72263. // read in each successive scanline
  72264. while (num_scanlines > 0) {
  72265. a = uint8array[dataIndex++];
  72266. b = uint8array[dataIndex++];
  72267. c = uint8array[dataIndex++];
  72268. d = uint8array[dataIndex++];
  72269. if (a != 2 || b != 2 || (c & 0x80)) {
  72270. // this file is not run length encoded
  72271. throw "HDR Bad header format, not RLE";
  72272. }
  72273. if (((c << 8) | d) != scanline_width) {
  72274. throw "HDR Bad header format, wrong scan line width";
  72275. }
  72276. index = 0;
  72277. // read each of the four channels for the scanline into the buffer
  72278. for (i = 0; i < 4; i++) {
  72279. endIndex = (i + 1) * scanline_width;
  72280. while (index < endIndex) {
  72281. a = uint8array[dataIndex++];
  72282. b = uint8array[dataIndex++];
  72283. if (a > 128) {
  72284. // a run of the same value
  72285. count = a - 128;
  72286. if ((count == 0) || (count > endIndex - index)) {
  72287. throw "HDR Bad Format, bad scanline data (run)";
  72288. }
  72289. while (count-- > 0) {
  72290. scanLineArray[index++] = b;
  72291. }
  72292. }
  72293. else {
  72294. // a non-run
  72295. count = a;
  72296. if ((count == 0) || (count > endIndex - index)) {
  72297. throw "HDR Bad Format, bad scanline data (non-run)";
  72298. }
  72299. scanLineArray[index++] = b;
  72300. if (--count > 0) {
  72301. for (var j = 0; j < count; j++) {
  72302. scanLineArray[index++] = uint8array[dataIndex++];
  72303. }
  72304. }
  72305. }
  72306. }
  72307. }
  72308. // now convert data from buffer into floats
  72309. for (i = 0; i < scanline_width; i++) {
  72310. a = scanLineArray[i];
  72311. b = scanLineArray[i + scanline_width];
  72312. c = scanLineArray[i + 2 * scanline_width];
  72313. d = scanLineArray[i + 3 * scanline_width];
  72314. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72315. }
  72316. num_scanlines--;
  72317. }
  72318. return resultArray;
  72319. };
  72320. return HDRTools;
  72321. }());
  72322. BABYLON.HDRTools = HDRTools;
  72323. })(BABYLON || (BABYLON = {}));
  72324. //# sourceMappingURL=babylon.hdr.js.map
  72325. var BABYLON;
  72326. (function (BABYLON) {
  72327. /**
  72328. * This represents a texture coming from an HDR input.
  72329. *
  72330. * The only supported format is currently panorama picture stored in RGBE format.
  72331. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72332. */
  72333. var HDRCubeTexture = /** @class */ (function (_super) {
  72334. __extends(HDRCubeTexture, _super);
  72335. /**
  72336. * Instantiates an HDRTexture from the following parameters.
  72337. *
  72338. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72339. * @param scene The scene the texture will be used in
  72340. * @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.
  72341. * @param noMipmap Forces to not generate the mipmap if true
  72342. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72343. * @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)
  72344. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72345. */
  72346. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72347. if (noMipmap === void 0) { noMipmap = false; }
  72348. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72349. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72350. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72351. if (onLoad === void 0) { onLoad = null; }
  72352. if (onError === void 0) { onError = null; }
  72353. var _this = _super.call(this, scene) || this;
  72354. _this._useInGammaSpace = false;
  72355. _this._generateHarmonics = true;
  72356. _this._isBABYLONPreprocessed = false;
  72357. _this._onLoad = null;
  72358. _this._onError = null;
  72359. /**
  72360. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72361. */
  72362. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72363. /**
  72364. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72365. * This is usefull at run time to apply the good shader.
  72366. */
  72367. _this.isPMREM = false;
  72368. _this._isBlocking = true;
  72369. /**
  72370. * Gets or sets the center of the bounding box associated with the cube texture
  72371. * It must define where the camera used to render the texture was set
  72372. */
  72373. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  72374. if (!url) {
  72375. return _this;
  72376. }
  72377. _this.name = url;
  72378. _this.url = url;
  72379. _this.hasAlpha = false;
  72380. _this.isCube = true;
  72381. _this._textureMatrix = BABYLON.Matrix.Identity();
  72382. _this._onLoad = onLoad;
  72383. _this._onError = onError;
  72384. _this.gammaSpace = false;
  72385. var caps = scene.getEngine().getCaps();
  72386. if (size) {
  72387. _this._isBABYLONPreprocessed = false;
  72388. _this._noMipmap = noMipmap;
  72389. _this._size = size;
  72390. _this._useInGammaSpace = useInGammaSpace;
  72391. _this._usePMREMGenerator = usePMREMGenerator &&
  72392. caps.textureLOD &&
  72393. caps.textureFloat &&
  72394. !_this._useInGammaSpace;
  72395. }
  72396. else {
  72397. _this._isBABYLONPreprocessed = true;
  72398. _this._noMipmap = false;
  72399. _this._useInGammaSpace = false;
  72400. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72401. !_this._useInGammaSpace;
  72402. }
  72403. _this.isPMREM = _this._usePMREMGenerator;
  72404. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72405. if (!_this._texture) {
  72406. if (!scene.useDelayedTextureLoading) {
  72407. _this.loadTexture();
  72408. }
  72409. else {
  72410. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72411. }
  72412. }
  72413. return _this;
  72414. }
  72415. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72416. /**
  72417. * Gets wether or not the texture is blocking during loading.
  72418. */
  72419. get: function () {
  72420. return this._isBlocking;
  72421. },
  72422. /**
  72423. * Sets wether or not the texture is blocking during loading.
  72424. */
  72425. set: function (value) {
  72426. this._isBlocking = value;
  72427. },
  72428. enumerable: true,
  72429. configurable: true
  72430. });
  72431. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  72432. get: function () {
  72433. return this._boundingBoxSize;
  72434. },
  72435. /**
  72436. * Gets or sets the size of the bounding box associated with the cube texture
  72437. * When defined, the cubemap will switch to local mode
  72438. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  72439. * @example https://www.babylonjs-playground.com/#RNASML
  72440. */
  72441. set: function (value) {
  72442. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  72443. return;
  72444. }
  72445. this._boundingBoxSize = value;
  72446. var scene = this.getScene();
  72447. if (scene) {
  72448. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  72449. }
  72450. },
  72451. enumerable: true,
  72452. configurable: true
  72453. });
  72454. /**
  72455. * Occurs when the file is a preprocessed .babylon.hdr file.
  72456. */
  72457. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72458. var _this = this;
  72459. var mipLevels = 0;
  72460. var floatArrayView = null;
  72461. var scene = this.getScene();
  72462. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72463. var mips = new Array();
  72464. if (!floatArrayView) {
  72465. return mips;
  72466. }
  72467. var startIndex = 30;
  72468. for (var level = 0; level < mipLevels; level++) {
  72469. mips.push([]);
  72470. // Fill each pixel of the mip level.
  72471. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72472. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72473. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72474. mips[level].push(faceData);
  72475. startIndex += faceSize;
  72476. }
  72477. }
  72478. return mips;
  72479. } : null;
  72480. var callback = function (buffer) {
  72481. var scene = _this.getScene();
  72482. if (!scene) {
  72483. return null;
  72484. }
  72485. // Create Native Array Views
  72486. var intArrayView = new Int32Array(buffer);
  72487. floatArrayView = new Float32Array(buffer);
  72488. // Fill header.
  72489. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72490. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72491. // Update Texture Information.
  72492. if (!_this._texture) {
  72493. return null;
  72494. }
  72495. _this._texture.updateSize(_this._size, _this._size);
  72496. // Fill polynomial information.
  72497. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72498. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72499. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72500. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72501. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72502. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72503. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72504. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72505. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72506. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72507. _this.sphericalPolynomial = sphericalPolynomial;
  72508. // Fill pixel data.
  72509. mipLevels = intArrayView[29]; // Number of mip levels.
  72510. var startIndex = 30;
  72511. var data = [];
  72512. var faceSize = Math.pow(_this._size, 2) * 3;
  72513. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72514. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72515. startIndex += faceSize;
  72516. }
  72517. var results = [];
  72518. var byteArray = null;
  72519. // Push each faces.
  72520. for (var k = 0; k < 6; k++) {
  72521. var dataFace = null;
  72522. // To be deprecated.
  72523. if (version === 1) {
  72524. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72525. dataFace = data[j];
  72526. }
  72527. // If special cases.
  72528. if (!mipmapGenerator && dataFace) {
  72529. if (!scene.getEngine().getCaps().textureFloat) {
  72530. // 3 channels of 1 bytes per pixel in bytes.
  72531. var byteBuffer = new ArrayBuffer(faceSize);
  72532. byteArray = new Uint8Array(byteBuffer);
  72533. }
  72534. for (var i = 0; i < _this._size * _this._size; i++) {
  72535. // Put in gamma space if requested.
  72536. if (_this._useInGammaSpace) {
  72537. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72538. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72539. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72540. }
  72541. // Convert to int texture for fallback.
  72542. if (byteArray) {
  72543. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72544. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72545. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72546. // May use luminance instead if the result is not accurate.
  72547. var max = Math.max(Math.max(r, g), b);
  72548. if (max > 255) {
  72549. var scale = 255 / max;
  72550. r *= scale;
  72551. g *= scale;
  72552. b *= scale;
  72553. }
  72554. byteArray[(i * 3) + 0] = r;
  72555. byteArray[(i * 3) + 1] = g;
  72556. byteArray[(i * 3) + 2] = b;
  72557. }
  72558. }
  72559. }
  72560. // Fill the array accordingly.
  72561. if (byteArray) {
  72562. results.push(byteArray);
  72563. }
  72564. else {
  72565. results.push(dataFace);
  72566. }
  72567. }
  72568. return results;
  72569. };
  72570. if (scene) {
  72571. 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);
  72572. }
  72573. };
  72574. /**
  72575. * Occurs when the file is raw .hdr file.
  72576. */
  72577. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72578. var _this = this;
  72579. var callback = function (buffer) {
  72580. var scene = _this.getScene();
  72581. if (!scene) {
  72582. return null;
  72583. }
  72584. // Extract the raw linear data.
  72585. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72586. // Generate harmonics if needed.
  72587. if (_this._generateHarmonics) {
  72588. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72589. _this.sphericalPolynomial = sphericalPolynomial;
  72590. }
  72591. var results = [];
  72592. var byteArray = null;
  72593. // Push each faces.
  72594. for (var j = 0; j < 6; j++) {
  72595. // Create uintarray fallback.
  72596. if (!scene.getEngine().getCaps().textureFloat) {
  72597. // 3 channels of 1 bytes per pixel in bytes.
  72598. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72599. byteArray = new Uint8Array(byteBuffer);
  72600. }
  72601. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72602. // If special cases.
  72603. if (_this._useInGammaSpace || byteArray) {
  72604. for (var i = 0; i < _this._size * _this._size; i++) {
  72605. // Put in gamma space if requested.
  72606. if (_this._useInGammaSpace) {
  72607. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72608. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72609. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72610. }
  72611. // Convert to int texture for fallback.
  72612. if (byteArray) {
  72613. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72614. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72615. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72616. // May use luminance instead if the result is not accurate.
  72617. var max = Math.max(Math.max(r, g), b);
  72618. if (max > 255) {
  72619. var scale = 255 / max;
  72620. r *= scale;
  72621. g *= scale;
  72622. b *= scale;
  72623. }
  72624. byteArray[(i * 3) + 0] = r;
  72625. byteArray[(i * 3) + 1] = g;
  72626. byteArray[(i * 3) + 2] = b;
  72627. }
  72628. }
  72629. }
  72630. if (byteArray) {
  72631. results.push(byteArray);
  72632. }
  72633. else {
  72634. results.push(dataFace);
  72635. }
  72636. }
  72637. return results;
  72638. };
  72639. var mipmapGenerator = null;
  72640. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72641. // if (!this._noMipmap &&
  72642. // this._usePMREMGenerator) {
  72643. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72644. // // Custom setup of the generator matching with the PBR shader values.
  72645. // var generator = new BABYLON.PMREMGenerator(data,
  72646. // this._size,
  72647. // this._size,
  72648. // 0,
  72649. // 3,
  72650. // this.getScene().getEngine().getCaps().textureFloat,
  72651. // 2048,
  72652. // 0.25,
  72653. // false,
  72654. // true);
  72655. // return generator.filterCubeMap();
  72656. // };
  72657. // }
  72658. var scene = this.getScene();
  72659. if (scene) {
  72660. 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);
  72661. }
  72662. };
  72663. /**
  72664. * Starts the loading process of the texture.
  72665. */
  72666. HDRCubeTexture.prototype.loadTexture = function () {
  72667. if (this._isBABYLONPreprocessed) {
  72668. this.loadBabylonTexture();
  72669. }
  72670. else {
  72671. this.loadHDRTexture();
  72672. }
  72673. };
  72674. HDRCubeTexture.prototype.clone = function () {
  72675. var scene = this.getScene();
  72676. if (!scene) {
  72677. return this;
  72678. }
  72679. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72680. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72681. // Base texture
  72682. newTexture.level = this.level;
  72683. newTexture.wrapU = this.wrapU;
  72684. newTexture.wrapV = this.wrapV;
  72685. newTexture.coordinatesIndex = this.coordinatesIndex;
  72686. newTexture.coordinatesMode = this.coordinatesMode;
  72687. return newTexture;
  72688. };
  72689. // Methods
  72690. HDRCubeTexture.prototype.delayLoad = function () {
  72691. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72692. return;
  72693. }
  72694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72695. this._texture = this._getFromCache(this.url, this._noMipmap);
  72696. if (!this._texture) {
  72697. this.loadTexture();
  72698. }
  72699. };
  72700. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72701. return this._textureMatrix;
  72702. };
  72703. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72704. this._textureMatrix = value;
  72705. };
  72706. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72707. var texture = null;
  72708. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72709. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72710. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72711. texture.name = parsedTexture.name;
  72712. texture.hasAlpha = parsedTexture.hasAlpha;
  72713. texture.level = parsedTexture.level;
  72714. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72715. texture.isBlocking = parsedTexture.isBlocking;
  72716. }
  72717. if (texture) {
  72718. if (parsedTexture.boundingBoxPosition) {
  72719. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  72720. }
  72721. if (parsedTexture.boundingBoxSize) {
  72722. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  72723. }
  72724. }
  72725. return texture;
  72726. };
  72727. HDRCubeTexture.prototype.serialize = function () {
  72728. if (!this.name) {
  72729. return null;
  72730. }
  72731. var serializationObject = {};
  72732. serializationObject.name = this.name;
  72733. serializationObject.hasAlpha = this.hasAlpha;
  72734. serializationObject.isCube = true;
  72735. serializationObject.level = this.level;
  72736. serializationObject.size = this._size;
  72737. serializationObject.coordinatesMode = this.coordinatesMode;
  72738. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72739. serializationObject.generateHarmonics = this._generateHarmonics;
  72740. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72741. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72742. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72743. serializationObject.noMipmap = this._noMipmap;
  72744. serializationObject.isBlocking = this._isBlocking;
  72745. return serializationObject;
  72746. };
  72747. /**
  72748. * Saves as a file the data contained in the texture in a binary format.
  72749. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72750. * as the spherical used in the lighting.
  72751. * @param url The HDR file url.
  72752. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72753. * @param onError Method called if any error happens during download.
  72754. * @return The packed binary data.
  72755. */
  72756. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72757. if (onError === void 0) { onError = null; }
  72758. var callback = function (buffer) {
  72759. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72760. // Returns a URL you can use as a href.
  72761. var objUrl = window.URL.createObjectURL(data);
  72762. // Simulates a link to it and click to dowload.
  72763. var a = document.createElement("a");
  72764. document.body.appendChild(a);
  72765. a.style.display = "none";
  72766. a.href = objUrl;
  72767. a.download = "envmap.babylon.hdr";
  72768. a.click();
  72769. };
  72770. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72771. };
  72772. /**
  72773. * Serializes the data contained in the texture in a binary format.
  72774. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72775. * as the spherical used in the lighting.
  72776. * @param url The HDR file url.
  72777. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72778. * @param onError Method called if any error happens during download.
  72779. * @return The packed binary data.
  72780. */
  72781. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72782. if (onError === void 0) { onError = null; }
  72783. // Needs the url tho create the texture.
  72784. if (!url) {
  72785. return;
  72786. }
  72787. // Check Power of two size.
  72788. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72789. return;
  72790. }
  72791. // Coming Back in 3.x.
  72792. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72793. };
  72794. HDRCubeTexture._facesMapping = [
  72795. "right",
  72796. "left",
  72797. "up",
  72798. "down",
  72799. "front",
  72800. "back"
  72801. ];
  72802. return HDRCubeTexture;
  72803. }(BABYLON.BaseTexture));
  72804. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72805. })(BABYLON || (BABYLON = {}));
  72806. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72807. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72808. // Huge respect for a such great lib.
  72809. // Earcut license:
  72810. // Copyright (c) 2016, Mapbox
  72811. //
  72812. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72813. // with or without fee is hereby granted, provided that the above copyright notice
  72814. // and this permission notice appear in all copies.
  72815. //
  72816. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72817. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72818. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72819. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72820. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72821. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72822. // THIS SOFTWARE.
  72823. var Earcut;
  72824. (function (Earcut) {
  72825. /**
  72826. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72827. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72828. * @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).
  72829. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72830. */
  72831. function earcut(data, holeIndices, dim) {
  72832. dim = dim || 2;
  72833. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72834. if (!outerNode)
  72835. return triangles;
  72836. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72837. if (hasHoles)
  72838. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72839. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72840. if (data.length > 80 * dim) {
  72841. minX = maxX = data[0];
  72842. minY = maxY = data[1];
  72843. for (var i = dim; i < outerLen; i += dim) {
  72844. x = data[i];
  72845. y = data[i + 1];
  72846. if (x < minX)
  72847. minX = x;
  72848. if (y < minY)
  72849. minY = y;
  72850. if (x > maxX)
  72851. maxX = x;
  72852. if (y > maxY)
  72853. maxY = y;
  72854. }
  72855. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72856. size = Math.max(maxX - minX, maxY - minY);
  72857. }
  72858. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72859. return triangles;
  72860. }
  72861. Earcut.earcut = earcut;
  72862. var Node = /** @class */ (function () {
  72863. function Node(i, x, y) {
  72864. this.i = i;
  72865. this.x = x;
  72866. this.y = y;
  72867. this.prev = null;
  72868. this.next = null;
  72869. this.z = null;
  72870. this.prevZ = null;
  72871. this.nextZ = null;
  72872. this.steiner = false;
  72873. }
  72874. return Node;
  72875. }());
  72876. // create a circular doubly linked list from polygon points in the specified winding order
  72877. function linkedList(data, start, end, dim, clockwise) {
  72878. var i, last = null;
  72879. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72880. for (i = start; i < end; i += dim)
  72881. last = insertNode(i, data[i], data[i + 1], last);
  72882. }
  72883. else {
  72884. for (i = end - dim; i >= start; i -= dim)
  72885. last = insertNode(i, data[i], data[i + 1], last);
  72886. }
  72887. if (last && equals(last, last.next)) {
  72888. removeNode(last);
  72889. last = last.next;
  72890. }
  72891. return last;
  72892. }
  72893. // eliminate colinear or duplicate points
  72894. function filterPoints(start, end) {
  72895. if (!start)
  72896. return start;
  72897. if (!end)
  72898. end = start;
  72899. var p = start, again;
  72900. do {
  72901. again = false;
  72902. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72903. removeNode(p);
  72904. p = end = p.prev;
  72905. if (p === p.next)
  72906. return undefined;
  72907. again = true;
  72908. }
  72909. else {
  72910. p = p.next;
  72911. }
  72912. } while (again || p !== end);
  72913. return end;
  72914. }
  72915. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72916. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72917. if (!ear)
  72918. return;
  72919. // interlink polygon nodes in z-order
  72920. if (!pass && size)
  72921. indexCurve(ear, minX, minY, size);
  72922. var stop = ear, prev, next;
  72923. // iterate through ears, slicing them one by one
  72924. while (ear.prev !== ear.next) {
  72925. prev = ear.prev;
  72926. next = ear.next;
  72927. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72928. // cut off the triangle
  72929. triangles.push(prev.i / dim);
  72930. triangles.push(ear.i / dim);
  72931. triangles.push(next.i / dim);
  72932. removeNode(ear);
  72933. // skipping the next vertice leads to less sliver triangles
  72934. ear = next.next;
  72935. stop = next.next;
  72936. continue;
  72937. }
  72938. ear = next;
  72939. // if we looped through the whole remaining polygon and can't find any more ears
  72940. if (ear === stop) {
  72941. // try filtering points and slicing again
  72942. if (!pass) {
  72943. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72944. // if this didn't work, try curing all small self-intersections locally
  72945. }
  72946. else if (pass === 1) {
  72947. ear = cureLocalIntersections(ear, triangles, dim);
  72948. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72949. // as a last resort, try splitting the remaining polygon into two
  72950. }
  72951. else if (pass === 2) {
  72952. splitEarcut(ear, triangles, dim, minX, minY, size);
  72953. }
  72954. break;
  72955. }
  72956. }
  72957. }
  72958. // check whether a polygon node forms a valid ear with adjacent nodes
  72959. function isEar(ear) {
  72960. var a = ear.prev, b = ear, c = ear.next;
  72961. if (area(a, b, c) >= 0)
  72962. return false; // reflex, can't be an ear
  72963. // now make sure we don't have other points inside the potential ear
  72964. var p = ear.next.next;
  72965. while (p !== ear.prev) {
  72966. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72967. area(p.prev, p, p.next) >= 0)
  72968. return false;
  72969. p = p.next;
  72970. }
  72971. return true;
  72972. }
  72973. function isEarHashed(ear, minX, minY, size) {
  72974. var a = ear.prev, b = ear, c = ear.next;
  72975. if (area(a, b, c) >= 0)
  72976. return false; // reflex, can't be an ear
  72977. // triangle bbox; min & max are calculated like this for speed
  72978. 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);
  72979. // z-order range for the current triangle bbox;
  72980. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  72981. // first look for points inside the triangle in increasing z-order
  72982. var p = ear.nextZ;
  72983. while (p && p.z <= maxZ) {
  72984. if (p !== ear.prev &&
  72985. p !== ear.next &&
  72986. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72987. area(p.prev, p, p.next) >= 0)
  72988. return false;
  72989. p = p.nextZ;
  72990. }
  72991. // then look for points in decreasing z-order
  72992. p = ear.prevZ;
  72993. while (p && p.z >= minZ) {
  72994. if (p !== ear.prev &&
  72995. p !== ear.next &&
  72996. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72997. area(p.prev, p, p.next) >= 0)
  72998. return false;
  72999. p = p.prevZ;
  73000. }
  73001. return true;
  73002. }
  73003. // go through all polygon nodes and cure small local self-intersections
  73004. function cureLocalIntersections(start, triangles, dim) {
  73005. var p = start;
  73006. do {
  73007. var a = p.prev, b = p.next.next;
  73008. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  73009. triangles.push(a.i / dim);
  73010. triangles.push(p.i / dim);
  73011. triangles.push(b.i / dim);
  73012. // remove two nodes involved
  73013. removeNode(p);
  73014. removeNode(p.next);
  73015. p = start = b;
  73016. }
  73017. p = p.next;
  73018. } while (p !== start);
  73019. return p;
  73020. }
  73021. // try splitting polygon into two and triangulate them independently
  73022. function splitEarcut(start, triangles, dim, minX, minY, size) {
  73023. // look for a valid diagonal that divides the polygon into two
  73024. var a = start;
  73025. do {
  73026. var b = a.next.next;
  73027. while (b !== a.prev) {
  73028. if (a.i !== b.i && isValidDiagonal(a, b)) {
  73029. // split the polygon in two by the diagonal
  73030. var c = splitPolygon(a, b);
  73031. // filter colinear points around the cuts
  73032. a = filterPoints(a, a.next);
  73033. c = filterPoints(c, c.next);
  73034. // run earcut on each half
  73035. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  73036. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  73037. return;
  73038. }
  73039. b = b.next;
  73040. }
  73041. a = a.next;
  73042. } while (a !== start);
  73043. }
  73044. // link every hole into the outer loop, producing a single-ring polygon without holes
  73045. function eliminateHoles(data, holeIndices, outerNode, dim) {
  73046. var queue = [], i, len, start, end, list;
  73047. for (i = 0, len = holeIndices.length; i < len; i++) {
  73048. start = holeIndices[i] * dim;
  73049. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73050. list = linkedList(data, start, end, dim, false);
  73051. if (list === list.next)
  73052. list.steiner = true;
  73053. queue.push(getLeftmost(list));
  73054. }
  73055. queue.sort(compareX);
  73056. // process holes from left to right
  73057. for (i = 0; i < queue.length; i++) {
  73058. eliminateHole(queue[i], outerNode);
  73059. outerNode = filterPoints(outerNode, outerNode.next);
  73060. }
  73061. return outerNode;
  73062. }
  73063. function compareX(a, b) {
  73064. return a.x - b.x;
  73065. }
  73066. // find a bridge between vertices that connects hole with an outer ring and and link it
  73067. function eliminateHole(hole, outerNode) {
  73068. outerNode = findHoleBridge(hole, outerNode);
  73069. if (outerNode) {
  73070. var b = splitPolygon(outerNode, hole);
  73071. filterPoints(b, b.next);
  73072. }
  73073. }
  73074. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73075. function findHoleBridge(hole, outerNode) {
  73076. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73077. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73078. // segment's endpoint with lesser x will be potential connection point
  73079. do {
  73080. if (hy <= p.y && hy >= p.next.y) {
  73081. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73082. if (x <= hx && x > qx) {
  73083. qx = x;
  73084. if (x === hx) {
  73085. if (hy === p.y)
  73086. return p;
  73087. if (hy === p.next.y)
  73088. return p.next;
  73089. }
  73090. m = p.x < p.next.x ? p : p.next;
  73091. }
  73092. }
  73093. p = p.next;
  73094. } while (p !== outerNode);
  73095. if (!m)
  73096. return null;
  73097. if (hx === qx)
  73098. return m.prev; // hole touches outer segment; pick lower endpoint
  73099. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73100. // if there are no points found, we have a valid connection;
  73101. // otherwise choose the point of the minimum angle with the ray as connection point
  73102. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73103. p = m.next;
  73104. while (p !== stop) {
  73105. if (hx >= p.x &&
  73106. p.x >= mx &&
  73107. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73108. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73109. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73110. m = p;
  73111. tanMin = tan;
  73112. }
  73113. }
  73114. p = p.next;
  73115. }
  73116. return m;
  73117. }
  73118. // interlink polygon nodes in z-order
  73119. function indexCurve(start, minX, minY, size) {
  73120. var p = start;
  73121. do {
  73122. if (p.z === null)
  73123. p.z = zOrder(p.x, p.y, minX, minY, size);
  73124. p.prevZ = p.prev;
  73125. p.nextZ = p.next;
  73126. p = p.next;
  73127. } while (p !== start);
  73128. p.prevZ.nextZ = null;
  73129. p.prevZ = null;
  73130. sortLinked(p);
  73131. }
  73132. // Simon Tatham's linked list merge sort algorithm
  73133. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73134. function sortLinked(list) {
  73135. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73136. do {
  73137. p = list;
  73138. list = null;
  73139. tail = null;
  73140. numMerges = 0;
  73141. while (p) {
  73142. numMerges++;
  73143. q = p;
  73144. pSize = 0;
  73145. for (i = 0; i < inSize; i++) {
  73146. pSize++;
  73147. q = q.nextZ;
  73148. if (!q)
  73149. break;
  73150. }
  73151. qSize = inSize;
  73152. while (pSize > 0 || (qSize > 0 && q)) {
  73153. if (pSize === 0) {
  73154. e = q;
  73155. q = q.nextZ;
  73156. qSize--;
  73157. }
  73158. else if (qSize === 0 || !q) {
  73159. e = p;
  73160. p = p.nextZ;
  73161. pSize--;
  73162. }
  73163. else if (p.z <= q.z) {
  73164. e = p;
  73165. p = p.nextZ;
  73166. pSize--;
  73167. }
  73168. else {
  73169. e = q;
  73170. q = q.nextZ;
  73171. qSize--;
  73172. }
  73173. if (tail)
  73174. tail.nextZ = e;
  73175. else
  73176. list = e;
  73177. e.prevZ = tail;
  73178. tail = e;
  73179. }
  73180. p = q;
  73181. }
  73182. tail.nextZ = null;
  73183. inSize *= 2;
  73184. } while (numMerges > 1);
  73185. return list;
  73186. }
  73187. // z-order of a point given coords and size of the data bounding box
  73188. function zOrder(x, y, minX, minY, size) {
  73189. // coords are transformed into non-negative 15-bit integer range
  73190. x = 32767 * (x - minX) / size;
  73191. y = 32767 * (y - minY) / size;
  73192. x = (x | (x << 8)) & 0x00FF00FF;
  73193. x = (x | (x << 4)) & 0x0F0F0F0F;
  73194. x = (x | (x << 2)) & 0x33333333;
  73195. x = (x | (x << 1)) & 0x55555555;
  73196. y = (y | (y << 8)) & 0x00FF00FF;
  73197. y = (y | (y << 4)) & 0x0F0F0F0F;
  73198. y = (y | (y << 2)) & 0x33333333;
  73199. y = (y | (y << 1)) & 0x55555555;
  73200. return x | (y << 1);
  73201. }
  73202. // find the leftmost node of a polygon ring
  73203. function getLeftmost(start) {
  73204. var p = start, leftmost = start;
  73205. do {
  73206. if (p.x < leftmost.x)
  73207. leftmost = p;
  73208. p = p.next;
  73209. } while (p !== start);
  73210. return leftmost;
  73211. }
  73212. // check if a point lies within a convex triangle
  73213. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73214. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73215. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73216. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73217. }
  73218. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73219. function isValidDiagonal(a, b) {
  73220. return a.next.i !== b.i &&
  73221. a.prev.i !== b.i &&
  73222. !intersectsPolygon(a, b) &&
  73223. locallyInside(a, b) &&
  73224. locallyInside(b, a) &&
  73225. middleInside(a, b);
  73226. }
  73227. // signed area of a triangle
  73228. function area(p, q, r) {
  73229. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73230. }
  73231. // check if two points are equal
  73232. function equals(p1, p2) {
  73233. return p1.x === p2.x && p1.y === p2.y;
  73234. }
  73235. // check if two segments intersect
  73236. function intersects(p1, q1, p2, q2) {
  73237. if ((equals(p1, q1) && equals(p2, q2)) ||
  73238. (equals(p1, q2) && equals(p2, q1)))
  73239. return true;
  73240. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73241. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73242. }
  73243. // check if a polygon diagonal intersects any polygon segments
  73244. function intersectsPolygon(a, b) {
  73245. var p = a;
  73246. do {
  73247. if (p.i !== a.i &&
  73248. p.next.i !== a.i &&
  73249. p.i !== b.i &&
  73250. p.next.i !== b.i &&
  73251. intersects(p, p.next, a, b))
  73252. return true;
  73253. p = p.next;
  73254. } while (p !== a);
  73255. return false;
  73256. }
  73257. // check if a polygon diagonal is locally inside the polygon
  73258. function locallyInside(a, b) {
  73259. return area(a.prev, a, a.next) < 0
  73260. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73261. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73262. }
  73263. // check if the middle point of a polygon diagonal is inside the polygon
  73264. function middleInside(a, b) {
  73265. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73266. do {
  73267. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73268. inside = !inside;
  73269. p = p.next;
  73270. } while (p !== a);
  73271. return inside;
  73272. }
  73273. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73274. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73275. function splitPolygon(a, b) {
  73276. 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;
  73277. a.next = b;
  73278. b.prev = a;
  73279. a2.next = an;
  73280. an.prev = a2;
  73281. b2.next = a2;
  73282. a2.prev = b2;
  73283. bp.next = b2;
  73284. b2.prev = bp;
  73285. return b2;
  73286. }
  73287. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73288. function insertNode(i, x, y, last) {
  73289. var p = new Node(i, x, y);
  73290. if (!last) {
  73291. p.prev = p;
  73292. p.next = p;
  73293. }
  73294. else {
  73295. p.next = last.next;
  73296. p.prev = last;
  73297. last.next.prev = p;
  73298. last.next = p;
  73299. }
  73300. return p;
  73301. }
  73302. function removeNode(p) {
  73303. p.next.prev = p.prev;
  73304. p.prev.next = p.next;
  73305. if (p.prevZ)
  73306. p.prevZ.nextZ = p.nextZ;
  73307. if (p.nextZ)
  73308. p.nextZ.prevZ = p.prevZ;
  73309. }
  73310. /**
  73311. * return a percentage difference between the polygon area and its triangulation area;
  73312. * used to verify correctness of triangulation
  73313. */
  73314. function deviation(data, holeIndices, dim, triangles) {
  73315. var hasHoles = holeIndices && holeIndices.length;
  73316. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73317. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73318. if (hasHoles) {
  73319. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73320. var start = holeIndices[i] * dim;
  73321. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73322. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73323. }
  73324. }
  73325. var trianglesArea = 0;
  73326. for (i = 0; i < triangles.length; i += 3) {
  73327. var a = triangles[i] * dim;
  73328. var b = triangles[i + 1] * dim;
  73329. var c = triangles[i + 2] * dim;
  73330. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73331. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73332. }
  73333. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73334. }
  73335. Earcut.deviation = deviation;
  73336. ;
  73337. function signedArea(data, start, end, dim) {
  73338. var sum = 0;
  73339. for (var i = start, j = end - dim; i < end; i += dim) {
  73340. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73341. j = i;
  73342. }
  73343. return sum;
  73344. }
  73345. /**
  73346. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73347. */
  73348. function flatten(data) {
  73349. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73350. for (var i = 0; i < data.length; i++) {
  73351. for (var j = 0; j < data[i].length; j++) {
  73352. for (var d = 0; d < dim; d++)
  73353. result.vertices.push(data[i][j][d]);
  73354. }
  73355. if (i > 0) {
  73356. holeIndex += data[i - 1].length;
  73357. result.holes.push(holeIndex);
  73358. }
  73359. }
  73360. return result;
  73361. }
  73362. Earcut.flatten = flatten;
  73363. ;
  73364. })(Earcut || (Earcut = {}));
  73365. //# sourceMappingURL=babylon.earcut.js.map
  73366. var BABYLON;
  73367. (function (BABYLON) {
  73368. var IndexedVector2 = /** @class */ (function (_super) {
  73369. __extends(IndexedVector2, _super);
  73370. function IndexedVector2(original, index) {
  73371. var _this = _super.call(this, original.x, original.y) || this;
  73372. _this.index = index;
  73373. return _this;
  73374. }
  73375. return IndexedVector2;
  73376. }(BABYLON.Vector2));
  73377. var PolygonPoints = /** @class */ (function () {
  73378. function PolygonPoints() {
  73379. this.elements = new Array();
  73380. }
  73381. PolygonPoints.prototype.add = function (originalPoints) {
  73382. var _this = this;
  73383. var result = new Array();
  73384. originalPoints.forEach(function (point) {
  73385. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73386. var newPoint = new IndexedVector2(point, _this.elements.length);
  73387. result.push(newPoint);
  73388. _this.elements.push(newPoint);
  73389. }
  73390. });
  73391. return result;
  73392. };
  73393. PolygonPoints.prototype.computeBounds = function () {
  73394. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73395. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73396. this.elements.forEach(function (point) {
  73397. // x
  73398. if (point.x < lmin.x) {
  73399. lmin.x = point.x;
  73400. }
  73401. else if (point.x > lmax.x) {
  73402. lmax.x = point.x;
  73403. }
  73404. // y
  73405. if (point.y < lmin.y) {
  73406. lmin.y = point.y;
  73407. }
  73408. else if (point.y > lmax.y) {
  73409. lmax.y = point.y;
  73410. }
  73411. });
  73412. return {
  73413. min: lmin,
  73414. max: lmax,
  73415. width: lmax.x - lmin.x,
  73416. height: lmax.y - lmin.y
  73417. };
  73418. };
  73419. return PolygonPoints;
  73420. }());
  73421. var Polygon = /** @class */ (function () {
  73422. function Polygon() {
  73423. }
  73424. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73425. return [
  73426. new BABYLON.Vector2(xmin, ymin),
  73427. new BABYLON.Vector2(xmax, ymin),
  73428. new BABYLON.Vector2(xmax, ymax),
  73429. new BABYLON.Vector2(xmin, ymax)
  73430. ];
  73431. };
  73432. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73433. if (cx === void 0) { cx = 0; }
  73434. if (cy === void 0) { cy = 0; }
  73435. if (numberOfSides === void 0) { numberOfSides = 32; }
  73436. var result = new Array();
  73437. var angle = 0;
  73438. var increment = (Math.PI * 2) / numberOfSides;
  73439. for (var i = 0; i < numberOfSides; i++) {
  73440. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73441. angle -= increment;
  73442. }
  73443. return result;
  73444. };
  73445. Polygon.Parse = function (input) {
  73446. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73447. var i, result = [];
  73448. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73449. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73450. }
  73451. return result;
  73452. };
  73453. Polygon.StartingAt = function (x, y) {
  73454. return BABYLON.Path2.StartingAt(x, y);
  73455. };
  73456. return Polygon;
  73457. }());
  73458. BABYLON.Polygon = Polygon;
  73459. var PolygonMeshBuilder = /** @class */ (function () {
  73460. function PolygonMeshBuilder(name, contours, scene) {
  73461. this._points = new PolygonPoints();
  73462. this._outlinepoints = new PolygonPoints();
  73463. this._holes = new Array();
  73464. this._epoints = new Array();
  73465. this._eholes = new Array();
  73466. this._name = name;
  73467. this._scene = scene;
  73468. var points;
  73469. if (contours instanceof BABYLON.Path2) {
  73470. points = contours.getPoints();
  73471. }
  73472. else {
  73473. points = contours;
  73474. }
  73475. this._addToepoint(points);
  73476. this._points.add(points);
  73477. this._outlinepoints.add(points);
  73478. }
  73479. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73480. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73481. var p = points_1[_i];
  73482. this._epoints.push(p.x, p.y);
  73483. }
  73484. };
  73485. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73486. this._points.add(hole);
  73487. var holepoints = new PolygonPoints();
  73488. holepoints.add(hole);
  73489. this._holes.push(holepoints);
  73490. this._eholes.push(this._epoints.length / 2);
  73491. this._addToepoint(hole);
  73492. return this;
  73493. };
  73494. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73495. var _this = this;
  73496. if (updatable === void 0) { updatable = false; }
  73497. if (depth === void 0) { depth = 0; }
  73498. var result = new BABYLON.Mesh(this._name, this._scene);
  73499. var normals = new Array();
  73500. var positions = new Array();
  73501. var uvs = new Array();
  73502. var bounds = this._points.computeBounds();
  73503. this._points.elements.forEach(function (p) {
  73504. normals.push(0, 1.0, 0);
  73505. positions.push(p.x, 0, p.y);
  73506. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73507. });
  73508. var indices = new Array();
  73509. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73510. for (var i = 0; i < res.length; i++) {
  73511. indices.push(res[i]);
  73512. }
  73513. if (depth > 0) {
  73514. var positionscount = (positions.length / 3); //get the current pointcount
  73515. this._points.elements.forEach(function (p) {
  73516. normals.push(0, -1.0, 0);
  73517. positions.push(p.x, -depth, p.y);
  73518. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73519. });
  73520. var totalCount = indices.length;
  73521. for (var i = 0; i < totalCount; i += 3) {
  73522. var i0 = indices[i + 0];
  73523. var i1 = indices[i + 1];
  73524. var i2 = indices[i + 2];
  73525. indices.push(i2 + positionscount);
  73526. indices.push(i1 + positionscount);
  73527. indices.push(i0 + positionscount);
  73528. }
  73529. //Add the sides
  73530. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73531. this._holes.forEach(function (hole) {
  73532. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73533. });
  73534. }
  73535. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73536. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73537. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73538. result.setIndices(indices);
  73539. return result;
  73540. };
  73541. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73542. var StartIndex = positions.length / 3;
  73543. var ulength = 0;
  73544. for (var i = 0; i < points.elements.length; i++) {
  73545. var p = points.elements[i];
  73546. var p1;
  73547. if ((i + 1) > points.elements.length - 1) {
  73548. p1 = points.elements[0];
  73549. }
  73550. else {
  73551. p1 = points.elements[i + 1];
  73552. }
  73553. positions.push(p.x, 0, p.y);
  73554. positions.push(p.x, -depth, p.y);
  73555. positions.push(p1.x, 0, p1.y);
  73556. positions.push(p1.x, -depth, p1.y);
  73557. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73558. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73559. var v3 = v2.subtract(v1);
  73560. var v4 = new BABYLON.Vector3(0, 1, 0);
  73561. var vn = BABYLON.Vector3.Cross(v3, v4);
  73562. vn = vn.normalize();
  73563. uvs.push(ulength / bounds.width, 0);
  73564. uvs.push(ulength / bounds.width, 1);
  73565. ulength += v3.length();
  73566. uvs.push((ulength / bounds.width), 0);
  73567. uvs.push((ulength / bounds.width), 1);
  73568. if (!flip) {
  73569. normals.push(-vn.x, -vn.y, -vn.z);
  73570. normals.push(-vn.x, -vn.y, -vn.z);
  73571. normals.push(-vn.x, -vn.y, -vn.z);
  73572. normals.push(-vn.x, -vn.y, -vn.z);
  73573. indices.push(StartIndex);
  73574. indices.push(StartIndex + 1);
  73575. indices.push(StartIndex + 2);
  73576. indices.push(StartIndex + 1);
  73577. indices.push(StartIndex + 3);
  73578. indices.push(StartIndex + 2);
  73579. }
  73580. else {
  73581. normals.push(vn.x, vn.y, vn.z);
  73582. normals.push(vn.x, vn.y, vn.z);
  73583. normals.push(vn.x, vn.y, vn.z);
  73584. normals.push(vn.x, vn.y, vn.z);
  73585. indices.push(StartIndex);
  73586. indices.push(StartIndex + 2);
  73587. indices.push(StartIndex + 1);
  73588. indices.push(StartIndex + 1);
  73589. indices.push(StartIndex + 2);
  73590. indices.push(StartIndex + 3);
  73591. }
  73592. StartIndex += 4;
  73593. }
  73594. ;
  73595. };
  73596. return PolygonMeshBuilder;
  73597. }());
  73598. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73599. })(BABYLON || (BABYLON = {}));
  73600. //# sourceMappingURL=babylon.polygonMesh.js.map
  73601. var BABYLON;
  73602. (function (BABYLON) {
  73603. // Unique ID when we import meshes from Babylon to CSG
  73604. var currentCSGMeshId = 0;
  73605. // # class Vertex
  73606. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73607. // one to provide additional features like texture coordinates and vertex
  73608. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73609. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73610. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73611. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73612. // is not used anywhere else.
  73613. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73614. var Vertex = /** @class */ (function () {
  73615. function Vertex(pos, normal, uv) {
  73616. this.pos = pos;
  73617. this.normal = normal;
  73618. this.uv = uv;
  73619. }
  73620. Vertex.prototype.clone = function () {
  73621. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73622. };
  73623. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73624. // orientation of a polygon is flipped.
  73625. Vertex.prototype.flip = function () {
  73626. this.normal = this.normal.scale(-1);
  73627. };
  73628. // Create a new vertex between this vertex and `other` by linearly
  73629. // interpolating all properties using a parameter of `t`. Subclasses should
  73630. // override this to interpolate additional properties.
  73631. Vertex.prototype.interpolate = function (other, t) {
  73632. 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));
  73633. };
  73634. return Vertex;
  73635. }());
  73636. // # class Plane
  73637. // Represents a plane in 3D space.
  73638. var Plane = /** @class */ (function () {
  73639. function Plane(normal, w) {
  73640. this.normal = normal;
  73641. this.w = w;
  73642. }
  73643. Plane.FromPoints = function (a, b, c) {
  73644. var v0 = c.subtract(a);
  73645. var v1 = b.subtract(a);
  73646. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73647. return null;
  73648. }
  73649. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73650. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73651. };
  73652. Plane.prototype.clone = function () {
  73653. return new Plane(this.normal.clone(), this.w);
  73654. };
  73655. Plane.prototype.flip = function () {
  73656. this.normal.scaleInPlace(-1);
  73657. this.w = -this.w;
  73658. };
  73659. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73660. // fragments in the appropriate lists. Coplanar polygons go into either
  73661. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73662. // respect to this plane. Polygons in front or in back of this plane go into
  73663. // either `front` or `back`.
  73664. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73665. var COPLANAR = 0;
  73666. var FRONT = 1;
  73667. var BACK = 2;
  73668. var SPANNING = 3;
  73669. // Classify each point as well as the entire polygon into one of the above
  73670. // four classes.
  73671. var polygonType = 0;
  73672. var types = [];
  73673. var i;
  73674. var t;
  73675. for (i = 0; i < polygon.vertices.length; i++) {
  73676. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73677. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73678. polygonType |= type;
  73679. types.push(type);
  73680. }
  73681. // Put the polygon in the correct list, splitting it when necessary.
  73682. switch (polygonType) {
  73683. case COPLANAR:
  73684. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73685. break;
  73686. case FRONT:
  73687. front.push(polygon);
  73688. break;
  73689. case BACK:
  73690. back.push(polygon);
  73691. break;
  73692. case SPANNING:
  73693. var f = [], b = [];
  73694. for (i = 0; i < polygon.vertices.length; i++) {
  73695. var j = (i + 1) % polygon.vertices.length;
  73696. var ti = types[i], tj = types[j];
  73697. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73698. if (ti !== BACK)
  73699. f.push(vi);
  73700. if (ti !== FRONT)
  73701. b.push(ti !== BACK ? vi.clone() : vi);
  73702. if ((ti | tj) === SPANNING) {
  73703. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73704. var v = vi.interpolate(vj, t);
  73705. f.push(v);
  73706. b.push(v.clone());
  73707. }
  73708. }
  73709. var poly;
  73710. if (f.length >= 3) {
  73711. poly = new Polygon(f, polygon.shared);
  73712. if (poly.plane)
  73713. front.push(poly);
  73714. }
  73715. if (b.length >= 3) {
  73716. poly = new Polygon(b, polygon.shared);
  73717. if (poly.plane)
  73718. back.push(poly);
  73719. }
  73720. break;
  73721. }
  73722. };
  73723. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73724. // point is on the plane.
  73725. Plane.EPSILON = 1e-5;
  73726. return Plane;
  73727. }());
  73728. // # class Polygon
  73729. // Represents a convex polygon. The vertices used to initialize a polygon must
  73730. // be coplanar and form a convex loop.
  73731. //
  73732. // Each convex polygon has a `shared` property, which is shared between all
  73733. // polygons that are clones of each other or were split from the same polygon.
  73734. // This can be used to define per-polygon properties (such as surface color).
  73735. var Polygon = /** @class */ (function () {
  73736. function Polygon(vertices, shared) {
  73737. this.vertices = vertices;
  73738. this.shared = shared;
  73739. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73740. }
  73741. Polygon.prototype.clone = function () {
  73742. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73743. return new Polygon(vertices, this.shared);
  73744. };
  73745. Polygon.prototype.flip = function () {
  73746. this.vertices.reverse().map(function (v) { v.flip(); });
  73747. this.plane.flip();
  73748. };
  73749. return Polygon;
  73750. }());
  73751. // # class Node
  73752. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73753. // by picking a polygon to split along. That polygon (and all other coplanar
  73754. // polygons) are added directly to that node and the other polygons are added to
  73755. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73756. // no distinction between internal and leaf nodes.
  73757. var Node = /** @class */ (function () {
  73758. function Node(polygons) {
  73759. this.plane = null;
  73760. this.front = null;
  73761. this.back = null;
  73762. this.polygons = new Array();
  73763. if (polygons) {
  73764. this.build(polygons);
  73765. }
  73766. }
  73767. Node.prototype.clone = function () {
  73768. var node = new Node();
  73769. node.plane = this.plane && this.plane.clone();
  73770. node.front = this.front && this.front.clone();
  73771. node.back = this.back && this.back.clone();
  73772. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73773. return node;
  73774. };
  73775. // Convert solid space to empty space and empty space to solid space.
  73776. Node.prototype.invert = function () {
  73777. for (var i = 0; i < this.polygons.length; i++) {
  73778. this.polygons[i].flip();
  73779. }
  73780. if (this.plane) {
  73781. this.plane.flip();
  73782. }
  73783. if (this.front) {
  73784. this.front.invert();
  73785. }
  73786. if (this.back) {
  73787. this.back.invert();
  73788. }
  73789. var temp = this.front;
  73790. this.front = this.back;
  73791. this.back = temp;
  73792. };
  73793. // Recursively remove all polygons in `polygons` that are inside this BSP
  73794. // tree.
  73795. Node.prototype.clipPolygons = function (polygons) {
  73796. if (!this.plane)
  73797. return polygons.slice();
  73798. var front = new Array(), back = new Array();
  73799. for (var i = 0; i < polygons.length; i++) {
  73800. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73801. }
  73802. if (this.front) {
  73803. front = this.front.clipPolygons(front);
  73804. }
  73805. if (this.back) {
  73806. back = this.back.clipPolygons(back);
  73807. }
  73808. else {
  73809. back = [];
  73810. }
  73811. return front.concat(back);
  73812. };
  73813. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73814. // `bsp`.
  73815. Node.prototype.clipTo = function (bsp) {
  73816. this.polygons = bsp.clipPolygons(this.polygons);
  73817. if (this.front)
  73818. this.front.clipTo(bsp);
  73819. if (this.back)
  73820. this.back.clipTo(bsp);
  73821. };
  73822. // Return a list of all polygons in this BSP tree.
  73823. Node.prototype.allPolygons = function () {
  73824. var polygons = this.polygons.slice();
  73825. if (this.front)
  73826. polygons = polygons.concat(this.front.allPolygons());
  73827. if (this.back)
  73828. polygons = polygons.concat(this.back.allPolygons());
  73829. return polygons;
  73830. };
  73831. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73832. // new polygons are filtered down to the bottom of the tree and become new
  73833. // nodes there. Each set of polygons is partitioned using the first polygon
  73834. // (no heuristic is used to pick a good split).
  73835. Node.prototype.build = function (polygons) {
  73836. if (!polygons.length)
  73837. return;
  73838. if (!this.plane)
  73839. this.plane = polygons[0].plane.clone();
  73840. var front = new Array(), back = new Array();
  73841. for (var i = 0; i < polygons.length; i++) {
  73842. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73843. }
  73844. if (front.length) {
  73845. if (!this.front)
  73846. this.front = new Node();
  73847. this.front.build(front);
  73848. }
  73849. if (back.length) {
  73850. if (!this.back)
  73851. this.back = new Node();
  73852. this.back.build(back);
  73853. }
  73854. };
  73855. return Node;
  73856. }());
  73857. var CSG = /** @class */ (function () {
  73858. function CSG() {
  73859. this.polygons = new Array();
  73860. }
  73861. // Convert BABYLON.Mesh to BABYLON.CSG
  73862. CSG.FromMesh = function (mesh) {
  73863. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73864. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73865. if (mesh instanceof BABYLON.Mesh) {
  73866. mesh.computeWorldMatrix(true);
  73867. matrix = mesh.getWorldMatrix();
  73868. meshPosition = mesh.position.clone();
  73869. meshRotation = mesh.rotation.clone();
  73870. if (mesh.rotationQuaternion) {
  73871. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73872. }
  73873. meshScaling = mesh.scaling.clone();
  73874. }
  73875. else {
  73876. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73877. }
  73878. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73879. var subMeshes = mesh.subMeshes;
  73880. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73881. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73882. vertices = [];
  73883. for (var j = 0; j < 3; j++) {
  73884. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73885. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73886. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73887. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73888. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73889. vertex = new Vertex(position, normal, uv);
  73890. vertices.push(vertex);
  73891. }
  73892. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73893. // To handle the case of degenerated triangle
  73894. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73895. if (polygon.plane)
  73896. polygons.push(polygon);
  73897. }
  73898. }
  73899. var csg = CSG.FromPolygons(polygons);
  73900. csg.matrix = matrix;
  73901. csg.position = meshPosition;
  73902. csg.rotation = meshRotation;
  73903. csg.scaling = meshScaling;
  73904. csg.rotationQuaternion = meshRotationQuaternion;
  73905. currentCSGMeshId++;
  73906. return csg;
  73907. };
  73908. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73909. CSG.FromPolygons = function (polygons) {
  73910. var csg = new CSG();
  73911. csg.polygons = polygons;
  73912. return csg;
  73913. };
  73914. CSG.prototype.clone = function () {
  73915. var csg = new CSG();
  73916. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73917. csg.copyTransformAttributes(this);
  73918. return csg;
  73919. };
  73920. CSG.prototype.union = function (csg) {
  73921. var a = new Node(this.clone().polygons);
  73922. var b = new Node(csg.clone().polygons);
  73923. a.clipTo(b);
  73924. b.clipTo(a);
  73925. b.invert();
  73926. b.clipTo(a);
  73927. b.invert();
  73928. a.build(b.allPolygons());
  73929. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73930. };
  73931. CSG.prototype.unionInPlace = function (csg) {
  73932. var a = new Node(this.polygons);
  73933. var b = new Node(csg.polygons);
  73934. a.clipTo(b);
  73935. b.clipTo(a);
  73936. b.invert();
  73937. b.clipTo(a);
  73938. b.invert();
  73939. a.build(b.allPolygons());
  73940. this.polygons = a.allPolygons();
  73941. };
  73942. CSG.prototype.subtract = function (csg) {
  73943. var a = new Node(this.clone().polygons);
  73944. var b = new Node(csg.clone().polygons);
  73945. a.invert();
  73946. a.clipTo(b);
  73947. b.clipTo(a);
  73948. b.invert();
  73949. b.clipTo(a);
  73950. b.invert();
  73951. a.build(b.allPolygons());
  73952. a.invert();
  73953. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73954. };
  73955. CSG.prototype.subtractInPlace = function (csg) {
  73956. var a = new Node(this.polygons);
  73957. var b = new Node(csg.polygons);
  73958. a.invert();
  73959. a.clipTo(b);
  73960. b.clipTo(a);
  73961. b.invert();
  73962. b.clipTo(a);
  73963. b.invert();
  73964. a.build(b.allPolygons());
  73965. a.invert();
  73966. this.polygons = a.allPolygons();
  73967. };
  73968. CSG.prototype.intersect = function (csg) {
  73969. var a = new Node(this.clone().polygons);
  73970. var b = new Node(csg.clone().polygons);
  73971. a.invert();
  73972. b.clipTo(a);
  73973. b.invert();
  73974. a.clipTo(b);
  73975. b.clipTo(a);
  73976. a.build(b.allPolygons());
  73977. a.invert();
  73978. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73979. };
  73980. CSG.prototype.intersectInPlace = function (csg) {
  73981. var a = new Node(this.polygons);
  73982. var b = new Node(csg.polygons);
  73983. a.invert();
  73984. b.clipTo(a);
  73985. b.invert();
  73986. a.clipTo(b);
  73987. b.clipTo(a);
  73988. a.build(b.allPolygons());
  73989. a.invert();
  73990. this.polygons = a.allPolygons();
  73991. };
  73992. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  73993. // not modified.
  73994. CSG.prototype.inverse = function () {
  73995. var csg = this.clone();
  73996. csg.inverseInPlace();
  73997. return csg;
  73998. };
  73999. CSG.prototype.inverseInPlace = function () {
  74000. this.polygons.map(function (p) { p.flip(); });
  74001. };
  74002. // This is used to keep meshes transformations so they can be restored
  74003. // when we build back a Babylon Mesh
  74004. // NB : All CSG operations are performed in world coordinates
  74005. CSG.prototype.copyTransformAttributes = function (csg) {
  74006. this.matrix = csg.matrix;
  74007. this.position = csg.position;
  74008. this.rotation = csg.rotation;
  74009. this.scaling = csg.scaling;
  74010. this.rotationQuaternion = csg.rotationQuaternion;
  74011. return this;
  74012. };
  74013. // Build Raw mesh from CSG
  74014. // Coordinates here are in world space
  74015. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  74016. var matrix = this.matrix.clone();
  74017. matrix.invert();
  74018. 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;
  74019. if (keepSubMeshes) {
  74020. // Sort Polygons, since subMeshes are indices range
  74021. polygons.sort(function (a, b) {
  74022. if (a.shared.meshId === b.shared.meshId) {
  74023. return a.shared.subMeshId - b.shared.subMeshId;
  74024. }
  74025. else {
  74026. return a.shared.meshId - b.shared.meshId;
  74027. }
  74028. });
  74029. }
  74030. for (var i = 0, il = polygons.length; i < il; i++) {
  74031. polygon = polygons[i];
  74032. // Building SubMeshes
  74033. if (!subMesh_dict[polygon.shared.meshId]) {
  74034. subMesh_dict[polygon.shared.meshId] = {};
  74035. }
  74036. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  74037. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  74038. indexStart: +Infinity,
  74039. indexEnd: -Infinity,
  74040. materialIndex: polygon.shared.materialIndex
  74041. };
  74042. }
  74043. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  74044. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  74045. polygonIndices[0] = 0;
  74046. polygonIndices[1] = j - 1;
  74047. polygonIndices[2] = j;
  74048. for (var k = 0; k < 3; k++) {
  74049. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  74050. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  74051. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  74052. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  74053. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74054. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74055. // Check if 2 points can be merged
  74056. if (!(typeof vertex_idx !== 'undefined' &&
  74057. normals[vertex_idx * 3] === localNormal.x &&
  74058. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74059. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74060. uvs[vertex_idx * 2] === uv.x &&
  74061. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74062. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74063. uvs.push(uv.x, uv.y);
  74064. normals.push(normal.x, normal.y, normal.z);
  74065. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74066. }
  74067. indices.push(vertex_idx);
  74068. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74069. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74070. currentIndex++;
  74071. }
  74072. }
  74073. }
  74074. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74075. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74076. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74077. mesh.setIndices(indices, null);
  74078. if (keepSubMeshes) {
  74079. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74080. var materialIndexOffset = 0, materialMaxIndex;
  74081. mesh.subMeshes = new Array();
  74082. for (var m in subMesh_dict) {
  74083. materialMaxIndex = -1;
  74084. for (var sm in subMesh_dict[m]) {
  74085. subMesh_obj = subMesh_dict[m][sm];
  74086. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74087. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74088. }
  74089. materialIndexOffset += ++materialMaxIndex;
  74090. }
  74091. }
  74092. return mesh;
  74093. };
  74094. // Build Mesh from CSG taking material and transforms into account
  74095. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74096. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74097. mesh.material = material;
  74098. mesh.position.copyFrom(this.position);
  74099. mesh.rotation.copyFrom(this.rotation);
  74100. if (this.rotationQuaternion) {
  74101. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74102. }
  74103. mesh.scaling.copyFrom(this.scaling);
  74104. mesh.computeWorldMatrix(true);
  74105. return mesh;
  74106. };
  74107. return CSG;
  74108. }());
  74109. BABYLON.CSG = CSG;
  74110. })(BABYLON || (BABYLON = {}));
  74111. //# sourceMappingURL=babylon.csg.js.map
  74112. var BABYLON;
  74113. (function (BABYLON) {
  74114. var LensFlare = /** @class */ (function () {
  74115. function LensFlare(size, position, color, imgUrl, system) {
  74116. this.size = size;
  74117. this.position = position;
  74118. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74119. this.color = color || new BABYLON.Color3(1, 1, 1);
  74120. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74121. this._system = system;
  74122. system.lensFlares.push(this);
  74123. }
  74124. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74125. return new LensFlare(size, position, color, imgUrl, system);
  74126. };
  74127. LensFlare.prototype.dispose = function () {
  74128. if (this.texture) {
  74129. this.texture.dispose();
  74130. }
  74131. // Remove from scene
  74132. var index = this._system.lensFlares.indexOf(this);
  74133. this._system.lensFlares.splice(index, 1);
  74134. };
  74135. ;
  74136. return LensFlare;
  74137. }());
  74138. BABYLON.LensFlare = LensFlare;
  74139. })(BABYLON || (BABYLON = {}));
  74140. //# sourceMappingURL=babylon.lensFlare.js.map
  74141. var BABYLON;
  74142. (function (BABYLON) {
  74143. var LensFlareSystem = /** @class */ (function () {
  74144. function LensFlareSystem(name, emitter, scene) {
  74145. this.name = name;
  74146. this.lensFlares = new Array();
  74147. this.borderLimit = 300;
  74148. this.viewportBorder = 0;
  74149. this.layerMask = 0x0FFFFFFF;
  74150. this._vertexBuffers = {};
  74151. this._isEnabled = true;
  74152. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74153. this._emitter = emitter;
  74154. this.id = name;
  74155. scene.lensFlareSystems.push(this);
  74156. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74157. var engine = scene.getEngine();
  74158. // VBO
  74159. var vertices = [];
  74160. vertices.push(1, 1);
  74161. vertices.push(-1, 1);
  74162. vertices.push(-1, -1);
  74163. vertices.push(1, -1);
  74164. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74165. // Indices
  74166. var indices = [];
  74167. indices.push(0);
  74168. indices.push(1);
  74169. indices.push(2);
  74170. indices.push(0);
  74171. indices.push(2);
  74172. indices.push(3);
  74173. this._indexBuffer = engine.createIndexBuffer(indices);
  74174. // Effects
  74175. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74176. }
  74177. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74178. get: function () {
  74179. return this._isEnabled;
  74180. },
  74181. set: function (value) {
  74182. this._isEnabled = value;
  74183. },
  74184. enumerable: true,
  74185. configurable: true
  74186. });
  74187. LensFlareSystem.prototype.getScene = function () {
  74188. return this._scene;
  74189. };
  74190. LensFlareSystem.prototype.getEmitter = function () {
  74191. return this._emitter;
  74192. };
  74193. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74194. this._emitter = newEmitter;
  74195. };
  74196. LensFlareSystem.prototype.getEmitterPosition = function () {
  74197. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74198. };
  74199. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74200. var position = this.getEmitterPosition();
  74201. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74202. this._positionX = position.x;
  74203. this._positionY = position.y;
  74204. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74205. if (this.viewportBorder > 0) {
  74206. globalViewport.x -= this.viewportBorder;
  74207. globalViewport.y -= this.viewportBorder;
  74208. globalViewport.width += this.viewportBorder * 2;
  74209. globalViewport.height += this.viewportBorder * 2;
  74210. position.x += this.viewportBorder;
  74211. position.y += this.viewportBorder;
  74212. this._positionX += this.viewportBorder;
  74213. this._positionY += this.viewportBorder;
  74214. }
  74215. if (position.z > 0) {
  74216. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74217. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74218. return true;
  74219. }
  74220. return true;
  74221. }
  74222. return false;
  74223. };
  74224. LensFlareSystem.prototype._isVisible = function () {
  74225. if (!this._isEnabled || !this._scene.activeCamera) {
  74226. return false;
  74227. }
  74228. var emitterPosition = this.getEmitterPosition();
  74229. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74230. var distance = direction.length();
  74231. direction.normalize();
  74232. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74233. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74234. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74235. };
  74236. LensFlareSystem.prototype.render = function () {
  74237. if (!this._effect.isReady() || !this._scene.activeCamera)
  74238. return false;
  74239. var engine = this._scene.getEngine();
  74240. var viewport = this._scene.activeCamera.viewport;
  74241. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74242. // Position
  74243. if (!this.computeEffectivePosition(globalViewport)) {
  74244. return false;
  74245. }
  74246. // Visibility
  74247. if (!this._isVisible()) {
  74248. return false;
  74249. }
  74250. // Intensity
  74251. var awayX;
  74252. var awayY;
  74253. if (this._positionX < this.borderLimit + globalViewport.x) {
  74254. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74255. }
  74256. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74257. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74258. }
  74259. else {
  74260. awayX = 0;
  74261. }
  74262. if (this._positionY < this.borderLimit + globalViewport.y) {
  74263. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74264. }
  74265. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74266. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74267. }
  74268. else {
  74269. awayY = 0;
  74270. }
  74271. var away = (awayX > awayY) ? awayX : awayY;
  74272. away -= this.viewportBorder;
  74273. if (away > this.borderLimit) {
  74274. away = this.borderLimit;
  74275. }
  74276. var intensity = 1.0 - (away / this.borderLimit);
  74277. if (intensity < 0) {
  74278. return false;
  74279. }
  74280. if (intensity > 1.0) {
  74281. intensity = 1.0;
  74282. }
  74283. if (this.viewportBorder > 0) {
  74284. globalViewport.x += this.viewportBorder;
  74285. globalViewport.y += this.viewportBorder;
  74286. globalViewport.width -= this.viewportBorder * 2;
  74287. globalViewport.height -= this.viewportBorder * 2;
  74288. this._positionX -= this.viewportBorder;
  74289. this._positionY -= this.viewportBorder;
  74290. }
  74291. // Position
  74292. var centerX = globalViewport.x + globalViewport.width / 2;
  74293. var centerY = globalViewport.y + globalViewport.height / 2;
  74294. var distX = centerX - this._positionX;
  74295. var distY = centerY - this._positionY;
  74296. // Effects
  74297. engine.enableEffect(this._effect);
  74298. engine.setState(false);
  74299. engine.setDepthBuffer(false);
  74300. // VBOs
  74301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74302. // Flares
  74303. for (var index = 0; index < this.lensFlares.length; index++) {
  74304. var flare = this.lensFlares[index];
  74305. engine.setAlphaMode(flare.alphaMode);
  74306. var x = centerX - (distX * flare.position);
  74307. var y = centerY - (distY * flare.position);
  74308. var cw = flare.size;
  74309. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74310. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74311. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74312. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74313. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74314. // Texture
  74315. this._effect.setTexture("textureSampler", flare.texture);
  74316. // Color
  74317. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74318. // Draw order
  74319. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74320. }
  74321. engine.setDepthBuffer(true);
  74322. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74323. return true;
  74324. };
  74325. LensFlareSystem.prototype.dispose = function () {
  74326. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74327. if (vertexBuffer) {
  74328. vertexBuffer.dispose();
  74329. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74330. }
  74331. if (this._indexBuffer) {
  74332. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74333. this._indexBuffer = null;
  74334. }
  74335. while (this.lensFlares.length) {
  74336. this.lensFlares[0].dispose();
  74337. }
  74338. // Remove from scene
  74339. var index = this._scene.lensFlareSystems.indexOf(this);
  74340. this._scene.lensFlareSystems.splice(index, 1);
  74341. };
  74342. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74343. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74344. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74345. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74346. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74347. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74348. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74349. var parsedFlare = parsedLensFlareSystem.flares[index];
  74350. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74351. }
  74352. return lensFlareSystem;
  74353. };
  74354. LensFlareSystem.prototype.serialize = function () {
  74355. var serializationObject = {};
  74356. serializationObject.id = this.id;
  74357. serializationObject.name = this.name;
  74358. serializationObject.emitterId = this.getEmitter().id;
  74359. serializationObject.borderLimit = this.borderLimit;
  74360. serializationObject.flares = [];
  74361. for (var index = 0; index < this.lensFlares.length; index++) {
  74362. var flare = this.lensFlares[index];
  74363. serializationObject.flares.push({
  74364. size: flare.size,
  74365. position: flare.position,
  74366. color: flare.color.asArray(),
  74367. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74368. });
  74369. }
  74370. return serializationObject;
  74371. };
  74372. return LensFlareSystem;
  74373. }());
  74374. BABYLON.LensFlareSystem = LensFlareSystem;
  74375. })(BABYLON || (BABYLON = {}));
  74376. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74377. var BABYLON;
  74378. (function (BABYLON) {
  74379. /**
  74380. * This is a holder class for the physics joint created by the physics plugin.
  74381. * It holds a set of functions to control the underlying joint.
  74382. */
  74383. var PhysicsJoint = /** @class */ (function () {
  74384. function PhysicsJoint(type, jointData) {
  74385. this.type = type;
  74386. this.jointData = jointData;
  74387. jointData.nativeParams = jointData.nativeParams || {};
  74388. }
  74389. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74390. get: function () {
  74391. return this._physicsJoint;
  74392. },
  74393. set: function (newJoint) {
  74394. if (this._physicsJoint) {
  74395. //remove from the wolrd
  74396. }
  74397. this._physicsJoint = newJoint;
  74398. },
  74399. enumerable: true,
  74400. configurable: true
  74401. });
  74402. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74403. set: function (physicsPlugin) {
  74404. this._physicsPlugin = physicsPlugin;
  74405. },
  74406. enumerable: true,
  74407. configurable: true
  74408. });
  74409. /**
  74410. * Execute a function that is physics-plugin specific.
  74411. * @param {Function} func the function that will be executed.
  74412. * It accepts two parameters: the physics world and the physics joint.
  74413. */
  74414. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74415. func(this._physicsPlugin.world, this._physicsJoint);
  74416. };
  74417. //TODO check if the native joints are the same
  74418. //Joint Types
  74419. PhysicsJoint.DistanceJoint = 0;
  74420. PhysicsJoint.HingeJoint = 1;
  74421. PhysicsJoint.BallAndSocketJoint = 2;
  74422. PhysicsJoint.WheelJoint = 3;
  74423. PhysicsJoint.SliderJoint = 4;
  74424. //OIMO
  74425. PhysicsJoint.PrismaticJoint = 5;
  74426. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74427. PhysicsJoint.UniversalJoint = 6;
  74428. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74429. //Cannon
  74430. //Similar to a Ball-Joint. Different in params
  74431. PhysicsJoint.PointToPointJoint = 8;
  74432. //Cannon only at the moment
  74433. PhysicsJoint.SpringJoint = 9;
  74434. PhysicsJoint.LockJoint = 10;
  74435. return PhysicsJoint;
  74436. }());
  74437. BABYLON.PhysicsJoint = PhysicsJoint;
  74438. /**
  74439. * A class representing a physics distance joint.
  74440. */
  74441. var DistanceJoint = /** @class */ (function (_super) {
  74442. __extends(DistanceJoint, _super);
  74443. function DistanceJoint(jointData) {
  74444. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74445. }
  74446. /**
  74447. * Update the predefined distance.
  74448. */
  74449. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74450. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74451. };
  74452. return DistanceJoint;
  74453. }(PhysicsJoint));
  74454. BABYLON.DistanceJoint = DistanceJoint;
  74455. var MotorEnabledJoint = /** @class */ (function (_super) {
  74456. __extends(MotorEnabledJoint, _super);
  74457. function MotorEnabledJoint(type, jointData) {
  74458. return _super.call(this, type, jointData) || this;
  74459. }
  74460. /**
  74461. * Set the motor values.
  74462. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74463. * @param {number} force the force to apply
  74464. * @param {number} maxForce max force for this motor.
  74465. */
  74466. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74467. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74468. };
  74469. /**
  74470. * Set the motor's limits.
  74471. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74472. */
  74473. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74474. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74475. };
  74476. return MotorEnabledJoint;
  74477. }(PhysicsJoint));
  74478. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74479. /**
  74480. * This class represents a single hinge physics joint
  74481. */
  74482. var HingeJoint = /** @class */ (function (_super) {
  74483. __extends(HingeJoint, _super);
  74484. function HingeJoint(jointData) {
  74485. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74486. }
  74487. /**
  74488. * Set the motor values.
  74489. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74490. * @param {number} force the force to apply
  74491. * @param {number} maxForce max force for this motor.
  74492. */
  74493. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74494. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74495. };
  74496. /**
  74497. * Set the motor's limits.
  74498. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74499. */
  74500. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74501. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74502. };
  74503. return HingeJoint;
  74504. }(MotorEnabledJoint));
  74505. BABYLON.HingeJoint = HingeJoint;
  74506. /**
  74507. * This class represents a dual hinge physics joint (same as wheel joint)
  74508. */
  74509. var Hinge2Joint = /** @class */ (function (_super) {
  74510. __extends(Hinge2Joint, _super);
  74511. function Hinge2Joint(jointData) {
  74512. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74513. }
  74514. /**
  74515. * Set the motor values.
  74516. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74517. * @param {number} force the force to apply
  74518. * @param {number} maxForce max force for this motor.
  74519. * @param {motorIndex} the motor's index, 0 or 1.
  74520. */
  74521. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74522. if (motorIndex === void 0) { motorIndex = 0; }
  74523. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74524. };
  74525. /**
  74526. * Set the motor limits.
  74527. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74528. * @param {number} upperLimit the upper limit
  74529. * @param {number} lowerLimit lower limit
  74530. * @param {motorIndex} the motor's index, 0 or 1.
  74531. */
  74532. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74533. if (motorIndex === void 0) { motorIndex = 0; }
  74534. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74535. };
  74536. return Hinge2Joint;
  74537. }(MotorEnabledJoint));
  74538. BABYLON.Hinge2Joint = Hinge2Joint;
  74539. })(BABYLON || (BABYLON = {}));
  74540. //# sourceMappingURL=babylon.physicsJoint.js.map
  74541. var BABYLON;
  74542. (function (BABYLON) {
  74543. var PhysicsImpostor = /** @class */ (function () {
  74544. function PhysicsImpostor(object, type, _options, _scene) {
  74545. if (_options === void 0) { _options = { mass: 0 }; }
  74546. var _this = this;
  74547. this.object = object;
  74548. this.type = type;
  74549. this._options = _options;
  74550. this._scene = _scene;
  74551. this._bodyUpdateRequired = false;
  74552. this._onBeforePhysicsStepCallbacks = new Array();
  74553. this._onAfterPhysicsStepCallbacks = new Array();
  74554. this._onPhysicsCollideCallbacks = [];
  74555. this._deltaPosition = BABYLON.Vector3.Zero();
  74556. this._isDisposed = false;
  74557. //temp variables for parent rotation calculations
  74558. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74559. this._tmpQuat = new BABYLON.Quaternion();
  74560. this._tmpQuat2 = new BABYLON.Quaternion();
  74561. /**
  74562. * this function is executed by the physics engine.
  74563. */
  74564. this.beforeStep = function () {
  74565. if (!_this._physicsEngine) {
  74566. return;
  74567. }
  74568. _this.object.translate(_this._deltaPosition, -1);
  74569. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74570. _this.object.computeWorldMatrix(false);
  74571. if (_this.object.parent && _this.object.rotationQuaternion) {
  74572. _this.getParentsRotation();
  74573. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74574. }
  74575. else {
  74576. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74577. }
  74578. if (!_this._options.disableBidirectionalTransformation) {
  74579. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74580. }
  74581. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74582. func(_this);
  74583. });
  74584. };
  74585. /**
  74586. * this function is executed by the physics engine.
  74587. */
  74588. this.afterStep = function () {
  74589. if (!_this._physicsEngine) {
  74590. return;
  74591. }
  74592. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74593. func(_this);
  74594. });
  74595. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74596. // object has now its world rotation. needs to be converted to local.
  74597. if (_this.object.parent && _this.object.rotationQuaternion) {
  74598. _this.getParentsRotation();
  74599. _this._tmpQuat.conjugateInPlace();
  74600. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74601. }
  74602. // take the position set and make it the absolute position of this object.
  74603. _this.object.setAbsolutePosition(_this.object.position);
  74604. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74605. _this.object.translate(_this._deltaPosition, 1);
  74606. };
  74607. /**
  74608. * Legacy collision detection event support
  74609. */
  74610. this.onCollideEvent = null;
  74611. //event and body object due to cannon's event-based architecture.
  74612. this.onCollide = function (e) {
  74613. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74614. return;
  74615. }
  74616. if (!_this._physicsEngine) {
  74617. return;
  74618. }
  74619. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74620. if (otherImpostor) {
  74621. // Legacy collision detection event support
  74622. if (_this.onCollideEvent) {
  74623. _this.onCollideEvent(_this, otherImpostor);
  74624. }
  74625. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74626. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74627. }).forEach(function (obj) {
  74628. obj.callback(_this, otherImpostor);
  74629. });
  74630. }
  74631. };
  74632. //sanity check!
  74633. if (!this.object) {
  74634. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74635. return;
  74636. }
  74637. //legacy support for old syntax.
  74638. if (!this._scene && object.getScene) {
  74639. this._scene = object.getScene();
  74640. }
  74641. if (!this._scene) {
  74642. return;
  74643. }
  74644. this._physicsEngine = this._scene.getPhysicsEngine();
  74645. if (!this._physicsEngine) {
  74646. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74647. }
  74648. else {
  74649. //set the object's quaternion, if not set
  74650. if (!this.object.rotationQuaternion) {
  74651. if (this.object.rotation) {
  74652. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74653. }
  74654. else {
  74655. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74656. }
  74657. }
  74658. //default options params
  74659. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74660. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74661. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74662. this._joints = [];
  74663. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74664. if (!this.object.parent || this._options.ignoreParent) {
  74665. this._init();
  74666. }
  74667. else if (this.object.parent.physicsImpostor) {
  74668. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74669. }
  74670. }
  74671. }
  74672. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74673. get: function () {
  74674. return this._isDisposed;
  74675. },
  74676. enumerable: true,
  74677. configurable: true
  74678. });
  74679. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74680. get: function () {
  74681. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74682. },
  74683. set: function (value) {
  74684. this.setMass(value);
  74685. },
  74686. enumerable: true,
  74687. configurable: true
  74688. });
  74689. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74690. get: function () {
  74691. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74692. },
  74693. set: function (value) {
  74694. if (!this._physicsEngine) {
  74695. return;
  74696. }
  74697. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74698. },
  74699. enumerable: true,
  74700. configurable: true
  74701. });
  74702. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74703. get: function () {
  74704. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74705. },
  74706. set: function (value) {
  74707. if (!this._physicsEngine) {
  74708. return;
  74709. }
  74710. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74711. },
  74712. enumerable: true,
  74713. configurable: true
  74714. });
  74715. /**
  74716. * This function will completly initialize this impostor.
  74717. * It will create a new body - but only if this mesh has no parent.
  74718. * If it has, this impostor will not be used other than to define the impostor
  74719. * of the child mesh.
  74720. */
  74721. PhysicsImpostor.prototype._init = function () {
  74722. if (!this._physicsEngine) {
  74723. return;
  74724. }
  74725. this._physicsEngine.removeImpostor(this);
  74726. this.physicsBody = null;
  74727. this._parent = this._parent || this._getPhysicsParent();
  74728. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74729. this._physicsEngine.addImpostor(this);
  74730. }
  74731. };
  74732. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74733. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74734. var parentMesh = this.object.parent;
  74735. return parentMesh.physicsImpostor;
  74736. }
  74737. return null;
  74738. };
  74739. /**
  74740. * Should a new body be generated.
  74741. */
  74742. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74743. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74744. };
  74745. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74746. this.forceUpdate();
  74747. };
  74748. /**
  74749. * Force a regeneration of this or the parent's impostor's body.
  74750. * Use under cautious - This will remove all joints already implemented.
  74751. */
  74752. PhysicsImpostor.prototype.forceUpdate = function () {
  74753. this._init();
  74754. if (this.parent && !this._options.ignoreParent) {
  74755. this.parent.forceUpdate();
  74756. }
  74757. };
  74758. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74759. /*public get mesh(): AbstractMesh {
  74760. return this._mesh;
  74761. }*/
  74762. /**
  74763. * Gets the body that holds this impostor. Either its own, or its parent.
  74764. */
  74765. get: function () {
  74766. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74767. },
  74768. /**
  74769. * Set the physics body. Used mainly by the physics engine/plugin
  74770. */
  74771. set: function (physicsBody) {
  74772. if (this._physicsBody && this._physicsEngine) {
  74773. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74774. }
  74775. this._physicsBody = physicsBody;
  74776. this.resetUpdateFlags();
  74777. },
  74778. enumerable: true,
  74779. configurable: true
  74780. });
  74781. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74782. get: function () {
  74783. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74784. },
  74785. set: function (value) {
  74786. this._parent = value;
  74787. },
  74788. enumerable: true,
  74789. configurable: true
  74790. });
  74791. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74792. this._bodyUpdateRequired = false;
  74793. };
  74794. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74795. if (this.object.getBoundingInfo) {
  74796. var q = this.object.rotationQuaternion;
  74797. //reset rotation
  74798. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74799. //calculate the world matrix with no rotation
  74800. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74801. var boundingInfo = this.object.getBoundingInfo();
  74802. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74803. //bring back the rotation
  74804. this.object.rotationQuaternion = q;
  74805. //calculate the world matrix with the new rotation
  74806. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74807. return size;
  74808. }
  74809. else {
  74810. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74811. }
  74812. };
  74813. PhysicsImpostor.prototype.getObjectCenter = function () {
  74814. if (this.object.getBoundingInfo) {
  74815. var boundingInfo = this.object.getBoundingInfo();
  74816. return boundingInfo.boundingBox.centerWorld;
  74817. }
  74818. else {
  74819. return this.object.position;
  74820. }
  74821. };
  74822. /**
  74823. * Get a specific parametes from the options parameter.
  74824. */
  74825. PhysicsImpostor.prototype.getParam = function (paramName) {
  74826. return this._options[paramName];
  74827. };
  74828. /**
  74829. * Sets a specific parameter in the options given to the physics plugin
  74830. */
  74831. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74832. this._options[paramName] = value;
  74833. this._bodyUpdateRequired = true;
  74834. };
  74835. /**
  74836. * Specifically change the body's mass option. Won't recreate the physics body object
  74837. */
  74838. PhysicsImpostor.prototype.setMass = function (mass) {
  74839. if (this.getParam("mass") !== mass) {
  74840. this.setParam("mass", mass);
  74841. }
  74842. if (this._physicsEngine) {
  74843. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74844. }
  74845. };
  74846. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74847. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74848. };
  74849. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74850. if (this._physicsEngine) {
  74851. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74852. }
  74853. };
  74854. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74855. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74856. };
  74857. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74858. if (this._physicsEngine) {
  74859. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74860. }
  74861. };
  74862. /**
  74863. * Execute a function with the physics plugin native code.
  74864. * Provide a function the will have two variables - the world object and the physics body object.
  74865. */
  74866. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74867. if (this._physicsEngine) {
  74868. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74869. }
  74870. };
  74871. /**
  74872. * Register a function that will be executed before the physics world is stepping forward.
  74873. */
  74874. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74875. this._onBeforePhysicsStepCallbacks.push(func);
  74876. };
  74877. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74878. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74879. if (index > -1) {
  74880. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74881. }
  74882. else {
  74883. BABYLON.Tools.Warn("Function to remove was not found");
  74884. }
  74885. };
  74886. /**
  74887. * Register a function that will be executed after the physics step
  74888. */
  74889. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74890. this._onAfterPhysicsStepCallbacks.push(func);
  74891. };
  74892. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74893. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74894. if (index > -1) {
  74895. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74896. }
  74897. else {
  74898. BABYLON.Tools.Warn("Function to remove was not found");
  74899. }
  74900. };
  74901. /**
  74902. * register a function that will be executed when this impostor collides against a different body.
  74903. */
  74904. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74905. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74906. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74907. };
  74908. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74909. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74910. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74911. if (index > -1) {
  74912. this._onPhysicsCollideCallbacks.splice(index, 1);
  74913. }
  74914. else {
  74915. BABYLON.Tools.Warn("Function to remove was not found");
  74916. }
  74917. };
  74918. PhysicsImpostor.prototype.getParentsRotation = function () {
  74919. var parent = this.object.parent;
  74920. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74921. while (parent) {
  74922. if (parent.rotationQuaternion) {
  74923. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74924. }
  74925. else {
  74926. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74927. }
  74928. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74929. parent = parent.parent;
  74930. }
  74931. return this._tmpQuat;
  74932. };
  74933. /**
  74934. * Apply a force
  74935. */
  74936. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74937. if (this._physicsEngine) {
  74938. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74939. }
  74940. return this;
  74941. };
  74942. /**
  74943. * Apply an impulse
  74944. */
  74945. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74946. if (this._physicsEngine) {
  74947. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74948. }
  74949. return this;
  74950. };
  74951. /**
  74952. * A help function to create a joint.
  74953. */
  74954. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74955. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74956. this.addJoint(otherImpostor, joint);
  74957. return this;
  74958. };
  74959. /**
  74960. * Add a joint to this impostor with a different impostor.
  74961. */
  74962. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74963. this._joints.push({
  74964. otherImpostor: otherImpostor,
  74965. joint: joint
  74966. });
  74967. if (this._physicsEngine) {
  74968. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74969. }
  74970. return this;
  74971. };
  74972. /**
  74973. * Will keep this body still, in a sleep mode.
  74974. */
  74975. PhysicsImpostor.prototype.sleep = function () {
  74976. if (this._physicsEngine) {
  74977. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  74978. }
  74979. return this;
  74980. };
  74981. /**
  74982. * Wake the body up.
  74983. */
  74984. PhysicsImpostor.prototype.wakeUp = function () {
  74985. if (this._physicsEngine) {
  74986. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  74987. }
  74988. return this;
  74989. };
  74990. PhysicsImpostor.prototype.clone = function (newObject) {
  74991. if (!newObject)
  74992. return null;
  74993. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  74994. };
  74995. PhysicsImpostor.prototype.dispose = function () {
  74996. var _this = this;
  74997. //no dispose if no physics engine is available.
  74998. if (!this._physicsEngine) {
  74999. return;
  75000. }
  75001. this._joints.forEach(function (j) {
  75002. if (_this._physicsEngine) {
  75003. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  75004. }
  75005. });
  75006. //dispose the physics body
  75007. this._physicsEngine.removeImpostor(this);
  75008. if (this.parent) {
  75009. this.parent.forceUpdate();
  75010. }
  75011. else {
  75012. /*this._object.getChildMeshes().forEach(function(mesh) {
  75013. if (mesh.physicsImpostor) {
  75014. if (disposeChildren) {
  75015. mesh.physicsImpostor.dispose();
  75016. mesh.physicsImpostor = null;
  75017. }
  75018. }
  75019. })*/
  75020. }
  75021. this._isDisposed = true;
  75022. };
  75023. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  75024. this._deltaPosition.copyFrom(position);
  75025. };
  75026. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  75027. if (!this._deltaRotation) {
  75028. this._deltaRotation = new BABYLON.Quaternion();
  75029. }
  75030. this._deltaRotation.copyFrom(rotation);
  75031. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  75032. };
  75033. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  75034. if (this._physicsEngine) {
  75035. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  75036. }
  75037. return this;
  75038. };
  75039. PhysicsImpostor.prototype.getRadius = function () {
  75040. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  75041. };
  75042. /**
  75043. * Sync a bone with this impostor
  75044. * @param bone The bone to sync to the impostor.
  75045. * @param boneMesh The mesh that the bone is influencing.
  75046. * @param jointPivot The pivot of the joint / bone in local space.
  75047. * @param distToJoint Optional distance from the impostor to the joint.
  75048. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75049. */
  75050. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  75051. var tempVec = PhysicsImpostor._tmpVecs[0];
  75052. var mesh = this.object;
  75053. if (mesh.rotationQuaternion) {
  75054. if (adjustRotation) {
  75055. var tempQuat = PhysicsImpostor._tmpQuat;
  75056. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75057. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75058. }
  75059. else {
  75060. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75061. }
  75062. }
  75063. tempVec.x = 0;
  75064. tempVec.y = 0;
  75065. tempVec.z = 0;
  75066. if (jointPivot) {
  75067. tempVec.x = jointPivot.x;
  75068. tempVec.y = jointPivot.y;
  75069. tempVec.z = jointPivot.z;
  75070. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75071. if (distToJoint === undefined || distToJoint === null) {
  75072. distToJoint = jointPivot.length();
  75073. }
  75074. tempVec.x *= distToJoint;
  75075. tempVec.y *= distToJoint;
  75076. tempVec.z *= distToJoint;
  75077. }
  75078. if (bone.getParent()) {
  75079. tempVec.addInPlace(mesh.getAbsolutePosition());
  75080. bone.setAbsolutePosition(tempVec, boneMesh);
  75081. }
  75082. else {
  75083. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75084. boneMesh.position.x -= tempVec.x;
  75085. boneMesh.position.y -= tempVec.y;
  75086. boneMesh.position.z -= tempVec.z;
  75087. }
  75088. };
  75089. /**
  75090. * Sync impostor to a bone
  75091. * @param bone The bone that the impostor will be synced to.
  75092. * @param boneMesh The mesh that the bone is influencing.
  75093. * @param jointPivot The pivot of the joint / bone in local space.
  75094. * @param distToJoint Optional distance from the impostor to the joint.
  75095. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75096. * @param boneAxis Optional vector3 axis the bone is aligned with
  75097. */
  75098. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75099. var mesh = this.object;
  75100. if (mesh.rotationQuaternion) {
  75101. if (adjustRotation) {
  75102. var tempQuat = PhysicsImpostor._tmpQuat;
  75103. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75104. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75105. }
  75106. else {
  75107. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75108. }
  75109. }
  75110. var pos = PhysicsImpostor._tmpVecs[0];
  75111. var boneDir = PhysicsImpostor._tmpVecs[1];
  75112. if (!boneAxis) {
  75113. boneAxis = PhysicsImpostor._tmpVecs[2];
  75114. boneAxis.x = 0;
  75115. boneAxis.y = 1;
  75116. boneAxis.z = 0;
  75117. }
  75118. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75119. bone.getAbsolutePositionToRef(boneMesh, pos);
  75120. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75121. distToJoint = jointPivot.length();
  75122. }
  75123. if (distToJoint !== undefined && distToJoint !== null) {
  75124. pos.x += boneDir.x * distToJoint;
  75125. pos.y += boneDir.y * distToJoint;
  75126. pos.z += boneDir.z * distToJoint;
  75127. }
  75128. mesh.setAbsolutePosition(pos);
  75129. };
  75130. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75131. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75132. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75133. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75134. //Impostor types
  75135. PhysicsImpostor.NoImpostor = 0;
  75136. PhysicsImpostor.SphereImpostor = 1;
  75137. PhysicsImpostor.BoxImpostor = 2;
  75138. PhysicsImpostor.PlaneImpostor = 3;
  75139. PhysicsImpostor.MeshImpostor = 4;
  75140. PhysicsImpostor.CylinderImpostor = 7;
  75141. PhysicsImpostor.ParticleImpostor = 8;
  75142. PhysicsImpostor.HeightmapImpostor = 9;
  75143. return PhysicsImpostor;
  75144. }());
  75145. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75146. })(BABYLON || (BABYLON = {}));
  75147. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75148. var BABYLON;
  75149. (function (BABYLON) {
  75150. var PhysicsEngine = /** @class */ (function () {
  75151. function PhysicsEngine(gravity, _physicsPlugin) {
  75152. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75153. this._physicsPlugin = _physicsPlugin;
  75154. //new methods and parameters
  75155. this._impostors = [];
  75156. this._joints = [];
  75157. if (!this._physicsPlugin.isSupported()) {
  75158. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75159. + "Please make sure it is included.");
  75160. }
  75161. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75162. this.setGravity(gravity);
  75163. this.setTimeStep();
  75164. }
  75165. PhysicsEngine.prototype.setGravity = function (gravity) {
  75166. this.gravity = gravity;
  75167. this._physicsPlugin.setGravity(this.gravity);
  75168. };
  75169. /**
  75170. * Set the time step of the physics engine.
  75171. * default is 1/60.
  75172. * To slow it down, enter 1/600 for example.
  75173. * To speed it up, 1/30
  75174. * @param {number} newTimeStep the new timestep to apply to this world.
  75175. */
  75176. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75177. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75178. this._physicsPlugin.setTimeStep(newTimeStep);
  75179. };
  75180. /**
  75181. * Get the time step of the physics engine.
  75182. */
  75183. PhysicsEngine.prototype.getTimeStep = function () {
  75184. return this._physicsPlugin.getTimeStep();
  75185. };
  75186. PhysicsEngine.prototype.dispose = function () {
  75187. this._impostors.forEach(function (impostor) {
  75188. impostor.dispose();
  75189. });
  75190. this._physicsPlugin.dispose();
  75191. };
  75192. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75193. return this._physicsPlugin.name;
  75194. };
  75195. /**
  75196. * Adding a new impostor for the impostor tracking.
  75197. * This will be done by the impostor itself.
  75198. * @param {PhysicsImpostor} impostor the impostor to add
  75199. */
  75200. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75201. impostor.uniqueId = this._impostors.push(impostor);
  75202. //if no parent, generate the body
  75203. if (!impostor.parent) {
  75204. this._physicsPlugin.generatePhysicsBody(impostor);
  75205. }
  75206. };
  75207. /**
  75208. * Remove an impostor from the engine.
  75209. * This impostor and its mesh will not longer be updated by the physics engine.
  75210. * @param {PhysicsImpostor} impostor the impostor to remove
  75211. */
  75212. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75213. var index = this._impostors.indexOf(impostor);
  75214. if (index > -1) {
  75215. var removed = this._impostors.splice(index, 1);
  75216. //Is it needed?
  75217. if (removed.length) {
  75218. //this will also remove it from the world.
  75219. removed[0].physicsBody = null;
  75220. }
  75221. }
  75222. };
  75223. /**
  75224. * Add a joint to the physics engine
  75225. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75226. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75227. * @param {PhysicsJoint} the joint that will connect both impostors.
  75228. */
  75229. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75230. var impostorJoint = {
  75231. mainImpostor: mainImpostor,
  75232. connectedImpostor: connectedImpostor,
  75233. joint: joint
  75234. };
  75235. joint.physicsPlugin = this._physicsPlugin;
  75236. this._joints.push(impostorJoint);
  75237. this._physicsPlugin.generateJoint(impostorJoint);
  75238. };
  75239. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75240. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75241. return (impostorJoint.connectedImpostor === connectedImpostor
  75242. && impostorJoint.joint === joint
  75243. && impostorJoint.mainImpostor === mainImpostor);
  75244. });
  75245. if (matchingJoints.length) {
  75246. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75247. //TODO remove it from the list as well
  75248. }
  75249. };
  75250. /**
  75251. * Called by the scene. no need to call it.
  75252. */
  75253. PhysicsEngine.prototype._step = function (delta) {
  75254. var _this = this;
  75255. //check if any mesh has no body / requires an update
  75256. this._impostors.forEach(function (impostor) {
  75257. if (impostor.isBodyInitRequired()) {
  75258. _this._physicsPlugin.generatePhysicsBody(impostor);
  75259. }
  75260. });
  75261. if (delta > 0.1) {
  75262. delta = 0.1;
  75263. }
  75264. else if (delta <= 0) {
  75265. delta = 1.0 / 60.0;
  75266. }
  75267. this._physicsPlugin.executeStep(delta, this._impostors);
  75268. };
  75269. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75270. return this._physicsPlugin;
  75271. };
  75272. PhysicsEngine.prototype.getImpostors = function () {
  75273. return this._impostors;
  75274. };
  75275. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75276. for (var i = 0; i < this._impostors.length; ++i) {
  75277. if (this._impostors[i].object === object) {
  75278. return this._impostors[i];
  75279. }
  75280. }
  75281. return null;
  75282. };
  75283. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75284. for (var i = 0; i < this._impostors.length; ++i) {
  75285. if (this._impostors[i].physicsBody === body) {
  75286. return this._impostors[i];
  75287. }
  75288. }
  75289. return null;
  75290. };
  75291. // Statics
  75292. PhysicsEngine.Epsilon = 0.001;
  75293. return PhysicsEngine;
  75294. }());
  75295. BABYLON.PhysicsEngine = PhysicsEngine;
  75296. })(BABYLON || (BABYLON = {}));
  75297. //# sourceMappingURL=babylon.physicsEngine.js.map
  75298. var BABYLON;
  75299. (function (BABYLON) {
  75300. var PhysicsHelper = /** @class */ (function () {
  75301. function PhysicsHelper(scene) {
  75302. this._scene = scene;
  75303. this._physicsEngine = this._scene.getPhysicsEngine();
  75304. if (!this._physicsEngine) {
  75305. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75306. }
  75307. }
  75308. /**
  75309. * @param {Vector3} origin the origin of the explosion
  75310. * @param {number} radius the explosion radius
  75311. * @param {number} strength the explosion strength
  75312. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75313. */
  75314. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75315. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75316. if (!this._physicsEngine) {
  75317. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75318. return null;
  75319. }
  75320. var impostors = this._physicsEngine.getImpostors();
  75321. if (impostors.length === 0) {
  75322. return null;
  75323. }
  75324. var event = new PhysicsRadialExplosionEvent(this._scene);
  75325. impostors.forEach(function (impostor) {
  75326. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75327. if (!impostorForceAndContactPoint) {
  75328. return;
  75329. }
  75330. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75331. });
  75332. event.dispose(false);
  75333. return event;
  75334. };
  75335. /**
  75336. * @param {Vector3} origin the origin of the explosion
  75337. * @param {number} radius the explosion radius
  75338. * @param {number} strength the explosion strength
  75339. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75340. */
  75341. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75342. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75343. if (!this._physicsEngine) {
  75344. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75345. return null;
  75346. }
  75347. var impostors = this._physicsEngine.getImpostors();
  75348. if (impostors.length === 0) {
  75349. return null;
  75350. }
  75351. var event = new PhysicsRadialExplosionEvent(this._scene);
  75352. impostors.forEach(function (impostor) {
  75353. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75354. if (!impostorForceAndContactPoint) {
  75355. return;
  75356. }
  75357. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75358. });
  75359. event.dispose(false);
  75360. return event;
  75361. };
  75362. /**
  75363. * @param {Vector3} origin the origin of the explosion
  75364. * @param {number} radius the explosion radius
  75365. * @param {number} strength the explosion strength
  75366. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75367. */
  75368. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75369. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75370. if (!this._physicsEngine) {
  75371. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75372. return null;
  75373. }
  75374. var impostors = this._physicsEngine.getImpostors();
  75375. if (impostors.length === 0) {
  75376. return null;
  75377. }
  75378. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75379. event.dispose(false);
  75380. return event;
  75381. };
  75382. /**
  75383. * @param {Vector3} origin the origin of the updraft
  75384. * @param {number} radius the radius of the updraft
  75385. * @param {number} strength the strength of the updraft
  75386. * @param {number} height the height of the updraft
  75387. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75388. */
  75389. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75390. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75391. if (!this._physicsEngine) {
  75392. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75393. return null;
  75394. }
  75395. if (this._physicsEngine.getImpostors().length === 0) {
  75396. return null;
  75397. }
  75398. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75399. event.dispose(false);
  75400. return event;
  75401. };
  75402. /**
  75403. * @param {Vector3} origin the of the vortex
  75404. * @param {number} radius the radius of the vortex
  75405. * @param {number} strength the strength of the vortex
  75406. * @param {number} height the height of the vortex
  75407. */
  75408. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75409. if (!this._physicsEngine) {
  75410. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75411. return null;
  75412. }
  75413. if (this._physicsEngine.getImpostors().length === 0) {
  75414. return null;
  75415. }
  75416. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75417. event.dispose(false);
  75418. return event;
  75419. };
  75420. return PhysicsHelper;
  75421. }());
  75422. BABYLON.PhysicsHelper = PhysicsHelper;
  75423. /***** Radial explosion *****/
  75424. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75425. function PhysicsRadialExplosionEvent(scene) {
  75426. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75427. this._rays = [];
  75428. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75429. this._scene = scene;
  75430. }
  75431. /**
  75432. * Returns the data related to the radial explosion event (sphere & rays).
  75433. * @returns {PhysicsRadialExplosionEventData}
  75434. */
  75435. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75436. this._dataFetched = true;
  75437. return {
  75438. sphere: this._sphere,
  75439. rays: this._rays,
  75440. };
  75441. };
  75442. /**
  75443. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75444. * @param impostor
  75445. * @param {Vector3} origin the origin of the explosion
  75446. * @param {number} radius the explosion radius
  75447. * @param {number} strength the explosion strength
  75448. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75449. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75450. */
  75451. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75452. if (impostor.mass === 0) {
  75453. return null;
  75454. }
  75455. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75456. return null;
  75457. }
  75458. if (impostor.object.getClassName() !== 'Mesh') {
  75459. return null;
  75460. }
  75461. var impostorObject = impostor.object;
  75462. var impostorObjectCenter = impostor.getObjectCenter();
  75463. var direction = impostorObjectCenter.subtract(origin);
  75464. var ray = new BABYLON.Ray(origin, direction, radius);
  75465. this._rays.push(ray);
  75466. var hit = ray.intersectsMesh(impostorObject);
  75467. var contactPoint = hit.pickedPoint;
  75468. if (!contactPoint) {
  75469. return null;
  75470. }
  75471. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75472. if (distanceFromOrigin > radius) {
  75473. return null;
  75474. }
  75475. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75476. ? strength
  75477. : strength * (1 - (distanceFromOrigin / radius));
  75478. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75479. return { force: force, contactPoint: contactPoint };
  75480. };
  75481. /**
  75482. * Disposes the sphere.
  75483. * @param {bolean} force
  75484. */
  75485. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75486. var _this = this;
  75487. if (force === void 0) { force = true; }
  75488. if (force) {
  75489. this._sphere.dispose();
  75490. }
  75491. else {
  75492. setTimeout(function () {
  75493. if (!_this._dataFetched) {
  75494. _this._sphere.dispose();
  75495. }
  75496. }, 0);
  75497. }
  75498. };
  75499. /*** Helpers ***/
  75500. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75501. if (!this._sphere) {
  75502. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75503. this._sphere.isVisible = false;
  75504. }
  75505. };
  75506. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75507. var impostorObject = impostor.object;
  75508. this._prepareSphere();
  75509. this._sphere.position = origin;
  75510. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75511. this._sphere._updateBoundingInfo();
  75512. this._sphere.computeWorldMatrix(true);
  75513. return this._sphere.intersectsMesh(impostorObject, true);
  75514. };
  75515. return PhysicsRadialExplosionEvent;
  75516. }());
  75517. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75518. /***** Gravitational Field *****/
  75519. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75520. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75521. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75522. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75523. this._physicsHelper = physicsHelper;
  75524. this._scene = scene;
  75525. this._origin = origin;
  75526. this._radius = radius;
  75527. this._strength = strength;
  75528. this._falloff = falloff;
  75529. this._tickCallback = this._tick.bind(this);
  75530. }
  75531. /**
  75532. * Returns the data related to the gravitational field event (sphere).
  75533. * @returns {PhysicsGravitationalFieldEventData}
  75534. */
  75535. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75536. this._dataFetched = true;
  75537. return {
  75538. sphere: this._sphere,
  75539. };
  75540. };
  75541. /**
  75542. * Enables the gravitational field.
  75543. */
  75544. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75545. this._tickCallback.call(this);
  75546. this._scene.registerBeforeRender(this._tickCallback);
  75547. };
  75548. /**
  75549. * Disables the gravitational field.
  75550. */
  75551. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75552. this._scene.unregisterBeforeRender(this._tickCallback);
  75553. };
  75554. /**
  75555. * Disposes the sphere.
  75556. * @param {bolean} force
  75557. */
  75558. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75559. var _this = this;
  75560. if (force === void 0) { force = true; }
  75561. if (force) {
  75562. this._sphere.dispose();
  75563. }
  75564. else {
  75565. setTimeout(function () {
  75566. if (!_this._dataFetched) {
  75567. _this._sphere.dispose();
  75568. }
  75569. }, 0);
  75570. }
  75571. };
  75572. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75573. // Since the params won't change, we fetch the event only once
  75574. if (this._sphere) {
  75575. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75576. }
  75577. else {
  75578. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75579. if (radialExplosionEvent) {
  75580. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75581. }
  75582. }
  75583. };
  75584. return PhysicsGravitationalFieldEvent;
  75585. }());
  75586. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75587. /***** Updraft *****/
  75588. var PhysicsUpdraftEvent = /** @class */ (function () {
  75589. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75590. this._scene = _scene;
  75591. this._origin = _origin;
  75592. this._radius = _radius;
  75593. this._strength = _strength;
  75594. this._height = _height;
  75595. this._updraftMode = _updraftMode;
  75596. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75597. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75598. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75599. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75600. this._physicsEngine = this._scene.getPhysicsEngine();
  75601. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75602. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75603. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75604. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75605. }
  75606. this._tickCallback = this._tick.bind(this);
  75607. }
  75608. /**
  75609. * Returns the data related to the updraft event (cylinder).
  75610. * @returns {PhysicsUpdraftEventData}
  75611. */
  75612. PhysicsUpdraftEvent.prototype.getData = function () {
  75613. this._dataFetched = true;
  75614. return {
  75615. cylinder: this._cylinder,
  75616. };
  75617. };
  75618. /**
  75619. * Enables the updraft.
  75620. */
  75621. PhysicsUpdraftEvent.prototype.enable = function () {
  75622. this._tickCallback.call(this);
  75623. this._scene.registerBeforeRender(this._tickCallback);
  75624. };
  75625. /**
  75626. * Disables the cortex.
  75627. */
  75628. PhysicsUpdraftEvent.prototype.disable = function () {
  75629. this._scene.unregisterBeforeRender(this._tickCallback);
  75630. };
  75631. /**
  75632. * Disposes the sphere.
  75633. * @param {bolean} force
  75634. */
  75635. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75636. var _this = this;
  75637. if (force === void 0) { force = true; }
  75638. if (force) {
  75639. this._cylinder.dispose();
  75640. }
  75641. else {
  75642. setTimeout(function () {
  75643. if (!_this._dataFetched) {
  75644. _this._cylinder.dispose();
  75645. }
  75646. }, 0);
  75647. }
  75648. };
  75649. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75650. if (impostor.mass === 0) {
  75651. return null;
  75652. }
  75653. if (!this._intersectsWithCylinder(impostor)) {
  75654. return null;
  75655. }
  75656. var impostorObjectCenter = impostor.getObjectCenter();
  75657. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75658. var direction = this._originDirection;
  75659. }
  75660. else {
  75661. var direction = impostorObjectCenter.subtract(this._originTop);
  75662. }
  75663. var multiplier = this._strength * -1;
  75664. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75665. return { force: force, contactPoint: impostorObjectCenter };
  75666. };
  75667. PhysicsUpdraftEvent.prototype._tick = function () {
  75668. var _this = this;
  75669. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75670. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75671. if (!impostorForceAndContactPoint) {
  75672. return;
  75673. }
  75674. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75675. });
  75676. };
  75677. /*** Helpers ***/
  75678. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75679. if (!this._cylinder) {
  75680. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75681. height: this._height,
  75682. diameter: this._radius * 2,
  75683. }, this._scene);
  75684. this._cylinder.isVisible = false;
  75685. }
  75686. };
  75687. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75688. var impostorObject = impostor.object;
  75689. this._prepareCylinder();
  75690. this._cylinder.position = this._cylinderPosition;
  75691. return this._cylinder.intersectsMesh(impostorObject, true);
  75692. };
  75693. return PhysicsUpdraftEvent;
  75694. }());
  75695. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75696. /***** Vortex *****/
  75697. var PhysicsVortexEvent = /** @class */ (function () {
  75698. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75699. this._scene = _scene;
  75700. this._origin = _origin;
  75701. this._radius = _radius;
  75702. this._strength = _strength;
  75703. this._height = _height;
  75704. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75705. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75706. this._updraftMultiplier = 0.02;
  75707. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75708. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75709. this._physicsEngine = this._scene.getPhysicsEngine();
  75710. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75711. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75712. this._tickCallback = this._tick.bind(this);
  75713. }
  75714. /**
  75715. * Returns the data related to the vortex event (cylinder).
  75716. * @returns {PhysicsVortexEventData}
  75717. */
  75718. PhysicsVortexEvent.prototype.getData = function () {
  75719. this._dataFetched = true;
  75720. return {
  75721. cylinder: this._cylinder,
  75722. };
  75723. };
  75724. /**
  75725. * Enables the vortex.
  75726. */
  75727. PhysicsVortexEvent.prototype.enable = function () {
  75728. this._tickCallback.call(this);
  75729. this._scene.registerBeforeRender(this._tickCallback);
  75730. };
  75731. /**
  75732. * Disables the cortex.
  75733. */
  75734. PhysicsVortexEvent.prototype.disable = function () {
  75735. this._scene.unregisterBeforeRender(this._tickCallback);
  75736. };
  75737. /**
  75738. * Disposes the sphere.
  75739. * @param {bolean} force
  75740. */
  75741. PhysicsVortexEvent.prototype.dispose = function (force) {
  75742. var _this = this;
  75743. if (force === void 0) { force = true; }
  75744. if (force) {
  75745. this._cylinder.dispose();
  75746. }
  75747. else {
  75748. setTimeout(function () {
  75749. if (!_this._dataFetched) {
  75750. _this._cylinder.dispose();
  75751. }
  75752. }, 0);
  75753. }
  75754. };
  75755. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75756. if (impostor.mass === 0) {
  75757. return null;
  75758. }
  75759. if (!this._intersectsWithCylinder(impostor)) {
  75760. return null;
  75761. }
  75762. if (impostor.object.getClassName() !== 'Mesh') {
  75763. return null;
  75764. }
  75765. var impostorObject = impostor.object;
  75766. var impostorObjectCenter = impostor.getObjectCenter();
  75767. 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)
  75768. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75769. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75770. var hit = ray.intersectsMesh(impostorObject);
  75771. var contactPoint = hit.pickedPoint;
  75772. if (!contactPoint) {
  75773. return null;
  75774. }
  75775. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75776. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75777. var directionToOrigin = contactPoint.normalize();
  75778. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75779. directionToOrigin = directionToOrigin.negate();
  75780. }
  75781. // TODO: find a more physically based solution
  75782. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75783. var forceX = directionToOrigin.x * this._strength / 8;
  75784. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75785. var forceZ = directionToOrigin.z * this._strength / 8;
  75786. }
  75787. else {
  75788. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75789. var forceY = this._originTop.y * this._updraftMultiplier;
  75790. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75791. }
  75792. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75793. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75794. return { force: force, contactPoint: impostorObjectCenter };
  75795. };
  75796. PhysicsVortexEvent.prototype._tick = function () {
  75797. var _this = this;
  75798. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75799. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75800. if (!impostorForceAndContactPoint) {
  75801. return;
  75802. }
  75803. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75804. });
  75805. };
  75806. /*** Helpers ***/
  75807. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75808. if (!this._cylinder) {
  75809. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75810. height: this._height,
  75811. diameter: this._radius * 2,
  75812. }, this._scene);
  75813. this._cylinder.isVisible = false;
  75814. }
  75815. };
  75816. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75817. var impostorObject = impostor.object;
  75818. this._prepareCylinder();
  75819. this._cylinder.position = this._cylinderPosition;
  75820. return this._cylinder.intersectsMesh(impostorObject, true);
  75821. };
  75822. return PhysicsVortexEvent;
  75823. }());
  75824. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75825. /***** Enums *****/
  75826. /**
  75827. * The strenght of the force in correspondence to the distance of the affected object
  75828. */
  75829. var PhysicsRadialImpulseFalloff;
  75830. (function (PhysicsRadialImpulseFalloff) {
  75831. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75832. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75833. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75834. /**
  75835. * The strenght of the force in correspondence to the distance of the affected object
  75836. */
  75837. var PhysicsUpdraftMode;
  75838. (function (PhysicsUpdraftMode) {
  75839. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75840. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75841. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75842. })(BABYLON || (BABYLON = {}));
  75843. //# sourceMappingURL=babylon.physicsHelper.js.map
  75844. var BABYLON;
  75845. (function (BABYLON) {
  75846. var CannonJSPlugin = /** @class */ (function () {
  75847. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75848. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75849. if (iterations === void 0) { iterations = 10; }
  75850. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75851. this.name = "CannonJSPlugin";
  75852. this._physicsMaterials = new Array();
  75853. this._fixedTimeStep = 1 / 60;
  75854. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75855. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  75856. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75857. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75858. this._tmpPosition = BABYLON.Vector3.Zero();
  75859. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75860. this._tmpUnityRotation = new BABYLON.Quaternion();
  75861. if (!this.isSupported()) {
  75862. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75863. return;
  75864. }
  75865. this._extendNamespace();
  75866. this.world = new this.BJSCANNON.World();
  75867. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75868. this.world.solver.iterations = iterations;
  75869. }
  75870. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75871. this.world.gravity.copy(gravity);
  75872. };
  75873. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75874. this._fixedTimeStep = timeStep;
  75875. };
  75876. CannonJSPlugin.prototype.getTimeStep = function () {
  75877. return this._fixedTimeStep;
  75878. };
  75879. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75880. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75881. };
  75882. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75883. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75884. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75885. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75886. };
  75887. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75888. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75889. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75890. impostor.physicsBody.applyForce(impulse, worldPoint);
  75891. };
  75892. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75893. //parent-child relationship. Does this impostor has a parent impostor?
  75894. if (impostor.parent) {
  75895. if (impostor.physicsBody) {
  75896. this.removePhysicsBody(impostor);
  75897. //TODO is that needed?
  75898. impostor.forceUpdate();
  75899. }
  75900. return;
  75901. }
  75902. //should a new body be created for this impostor?
  75903. if (impostor.isBodyInitRequired()) {
  75904. var shape = this._createShape(impostor);
  75905. //unregister events, if body is being changed
  75906. var oldBody = impostor.physicsBody;
  75907. if (oldBody) {
  75908. this.removePhysicsBody(impostor);
  75909. }
  75910. //create the body and material
  75911. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75912. var bodyCreationObject = {
  75913. mass: impostor.getParam("mass"),
  75914. material: material
  75915. };
  75916. // A simple extend, in case native options were used.
  75917. var nativeOptions = impostor.getParam("nativeOptions");
  75918. for (var key in nativeOptions) {
  75919. if (nativeOptions.hasOwnProperty(key)) {
  75920. bodyCreationObject[key] = nativeOptions[key];
  75921. }
  75922. }
  75923. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75924. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75925. this.world.addEventListener("preStep", impostor.beforeStep);
  75926. this.world.addEventListener("postStep", impostor.afterStep);
  75927. impostor.physicsBody.addShape(shape);
  75928. this.world.add(impostor.physicsBody);
  75929. //try to keep the body moving in the right direction by taking old properties.
  75930. //Should be tested!
  75931. if (oldBody) {
  75932. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75933. impostor.physicsBody[param].copy(oldBody[param]);
  75934. });
  75935. }
  75936. this._processChildMeshes(impostor);
  75937. }
  75938. //now update the body's transformation
  75939. this._updatePhysicsBodyTransformation(impostor);
  75940. };
  75941. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75942. var _this = this;
  75943. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75944. var currentRotation = mainImpostor.object.rotationQuaternion;
  75945. if (meshChildren.length) {
  75946. var processMesh = function (localPosition, mesh) {
  75947. if (!currentRotation || !mesh.rotationQuaternion) {
  75948. return;
  75949. }
  75950. var childImpostor = mesh.getPhysicsImpostor();
  75951. if (childImpostor) {
  75952. var parent = childImpostor.parent;
  75953. if (parent !== mainImpostor) {
  75954. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75955. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75956. if (childImpostor.physicsBody) {
  75957. _this.removePhysicsBody(childImpostor);
  75958. childImpostor.physicsBody = null;
  75959. }
  75960. childImpostor.parent = mainImpostor;
  75961. childImpostor.resetUpdateFlags();
  75962. 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));
  75963. //Add the mass of the children.
  75964. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75965. }
  75966. }
  75967. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75968. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75969. };
  75970. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75971. }
  75972. };
  75973. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75974. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  75975. this.world.removeEventListener("preStep", impostor.beforeStep);
  75976. this.world.removeEventListener("postStep", impostor.afterStep);
  75977. this.world.remove(impostor.physicsBody);
  75978. };
  75979. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75980. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75981. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75982. if (!mainBody || !connectedBody) {
  75983. return;
  75984. }
  75985. var constraint;
  75986. var jointData = impostorJoint.joint.jointData;
  75987. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  75988. var constraintData = {
  75989. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  75990. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  75991. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  75992. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  75993. maxForce: jointData.nativeParams.maxForce,
  75994. collideConnected: !!jointData.collision
  75995. };
  75996. switch (impostorJoint.joint.type) {
  75997. case BABYLON.PhysicsJoint.HingeJoint:
  75998. case BABYLON.PhysicsJoint.Hinge2Joint:
  75999. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  76000. break;
  76001. case BABYLON.PhysicsJoint.DistanceJoint:
  76002. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  76003. break;
  76004. case BABYLON.PhysicsJoint.SpringJoint:
  76005. var springData = jointData;
  76006. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  76007. restLength: springData.length,
  76008. stiffness: springData.stiffness,
  76009. damping: springData.damping,
  76010. localAnchorA: constraintData.pivotA,
  76011. localAnchorB: constraintData.pivotB
  76012. });
  76013. break;
  76014. case BABYLON.PhysicsJoint.LockJoint:
  76015. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  76016. break;
  76017. case BABYLON.PhysicsJoint.PointToPointJoint:
  76018. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76019. default:
  76020. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  76021. break;
  76022. }
  76023. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  76024. constraint.collideConnected = !!jointData.collision;
  76025. impostorJoint.joint.physicsJoint = constraint;
  76026. //don't add spring as constraint, as it is not one.
  76027. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  76028. this.world.addConstraint(constraint);
  76029. }
  76030. else {
  76031. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  76032. constraint.applyForce();
  76033. });
  76034. }
  76035. };
  76036. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76037. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  76038. };
  76039. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  76040. var index;
  76041. var mat;
  76042. for (index = 0; index < this._physicsMaterials.length; index++) {
  76043. mat = this._physicsMaterials[index];
  76044. if (mat.friction === friction && mat.restitution === restitution) {
  76045. return mat;
  76046. }
  76047. }
  76048. var currentMat = new this.BJSCANNON.Material(name);
  76049. currentMat.friction = friction;
  76050. currentMat.restitution = restitution;
  76051. this._physicsMaterials.push(currentMat);
  76052. return currentMat;
  76053. };
  76054. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76055. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76056. };
  76057. CannonJSPlugin.prototype._createShape = function (impostor) {
  76058. var object = impostor.object;
  76059. var returnValue;
  76060. var extendSize = impostor.getObjectExtendSize();
  76061. switch (impostor.type) {
  76062. case BABYLON.PhysicsImpostor.SphereImpostor:
  76063. var radiusX = extendSize.x;
  76064. var radiusY = extendSize.y;
  76065. var radiusZ = extendSize.z;
  76066. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76067. break;
  76068. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76069. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76070. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76071. break;
  76072. case BABYLON.PhysicsImpostor.BoxImpostor:
  76073. var box = extendSize.scale(0.5);
  76074. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76075. break;
  76076. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76077. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76078. returnValue = new this.BJSCANNON.Plane();
  76079. break;
  76080. case BABYLON.PhysicsImpostor.MeshImpostor:
  76081. // should transform the vertex data to world coordinates!!
  76082. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76083. var rawFaces = object.getIndices ? object.getIndices() : [];
  76084. if (!rawVerts)
  76085. return;
  76086. // get only scale! so the object could transform correctly.
  76087. var oldPosition = object.position.clone();
  76088. var oldRotation = object.rotation && object.rotation.clone();
  76089. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76090. object.position.copyFromFloats(0, 0, 0);
  76091. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76092. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76093. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76094. var transform = object.computeWorldMatrix(true);
  76095. // convert rawVerts to object space
  76096. var temp = new Array();
  76097. var index;
  76098. for (index = 0; index < rawVerts.length; index += 3) {
  76099. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76100. }
  76101. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76102. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76103. //now set back the transformation!
  76104. object.position.copyFrom(oldPosition);
  76105. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76106. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76107. break;
  76108. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76109. var oldPosition2 = object.position.clone();
  76110. var oldRotation2 = object.rotation && object.rotation.clone();
  76111. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76112. object.position.copyFromFloats(0, 0, 0);
  76113. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76114. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76115. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76116. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76117. returnValue = this._createHeightmap(object);
  76118. object.position.copyFrom(oldPosition2);
  76119. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76120. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76121. object.computeWorldMatrix(true);
  76122. break;
  76123. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76124. returnValue = new this.BJSCANNON.Particle();
  76125. break;
  76126. }
  76127. return returnValue;
  76128. };
  76129. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76130. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76131. var transform = object.computeWorldMatrix(true);
  76132. // convert rawVerts to object space
  76133. var temp = new Array();
  76134. var index;
  76135. for (index = 0; index < pos.length; index += 3) {
  76136. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76137. }
  76138. pos = temp;
  76139. var matrix = new Array();
  76140. //For now pointDepth will not be used and will be automatically calculated.
  76141. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76142. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76143. var boundingInfo = object.getBoundingInfo();
  76144. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76145. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76146. var elementSize = dim * 2 / arraySize;
  76147. for (var i = 0; i < pos.length; i = i + 3) {
  76148. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76149. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76150. var y = -pos[i + 2] + minY;
  76151. if (!matrix[x]) {
  76152. matrix[x] = [];
  76153. }
  76154. if (!matrix[x][z]) {
  76155. matrix[x][z] = y;
  76156. }
  76157. matrix[x][z] = Math.max(y, matrix[x][z]);
  76158. }
  76159. for (var x = 0; x <= arraySize; ++x) {
  76160. if (!matrix[x]) {
  76161. var loc = 1;
  76162. while (!matrix[(x + loc) % arraySize]) {
  76163. loc++;
  76164. }
  76165. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76166. //console.log("missing x", x);
  76167. }
  76168. for (var z = 0; z <= arraySize; ++z) {
  76169. if (!matrix[x][z]) {
  76170. var loc = 1;
  76171. var newValue;
  76172. while (newValue === undefined) {
  76173. newValue = matrix[x][(z + loc++) % arraySize];
  76174. }
  76175. matrix[x][z] = newValue;
  76176. }
  76177. }
  76178. }
  76179. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76180. elementSize: elementSize
  76181. });
  76182. //For future reference, needed for body transformation
  76183. shape.minY = minY;
  76184. return shape;
  76185. };
  76186. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76187. var object = impostor.object;
  76188. //make sure it is updated...
  76189. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76190. // The delta between the mesh position and the mesh bounding box center
  76191. var bInfo = object.getBoundingInfo();
  76192. if (!bInfo)
  76193. return;
  76194. var center = impostor.getObjectCenter();
  76195. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76196. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76197. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76198. this._tmpPosition.copyFrom(center);
  76199. var quaternion = object.rotationQuaternion;
  76200. if (!quaternion) {
  76201. return;
  76202. }
  76203. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76204. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76205. //-90 DEG in X, precalculated
  76206. quaternion = quaternion.multiply(this._minus90X);
  76207. //Invert! (Precalculated, 90 deg in X)
  76208. //No need to clone. this will never change.
  76209. impostor.setDeltaRotation(this._plus90X);
  76210. }
  76211. //If it is a heightfield, if should be centered.
  76212. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76213. var mesh = object;
  76214. var boundingInfo = mesh.getBoundingInfo();
  76215. //calculate the correct body position:
  76216. var rotationQuaternion = mesh.rotationQuaternion;
  76217. mesh.rotationQuaternion = this._tmpUnityRotation;
  76218. mesh.computeWorldMatrix(true);
  76219. //get original center with no rotation
  76220. var c = center.clone();
  76221. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76222. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76223. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76224. mesh.setPreTransformMatrix(p);
  76225. mesh.computeWorldMatrix(true);
  76226. //calculate the translation
  76227. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76228. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76229. //add it inverted to the delta
  76230. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76231. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76232. //rotation is back
  76233. mesh.rotationQuaternion = rotationQuaternion;
  76234. mesh.setPreTransformMatrix(oldPivot);
  76235. mesh.computeWorldMatrix(true);
  76236. }
  76237. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76238. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76239. //this._tmpPosition.copyFrom(object.position);
  76240. }
  76241. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76242. //Now update the impostor object
  76243. impostor.physicsBody.position.copy(this._tmpPosition);
  76244. impostor.physicsBody.quaternion.copy(quaternion);
  76245. };
  76246. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76247. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76248. if (impostor.object.rotationQuaternion) {
  76249. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76250. }
  76251. };
  76252. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76253. impostor.physicsBody.position.copy(newPosition);
  76254. impostor.physicsBody.quaternion.copy(newRotation);
  76255. };
  76256. CannonJSPlugin.prototype.isSupported = function () {
  76257. return this.BJSCANNON !== undefined;
  76258. };
  76259. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76260. impostor.physicsBody.velocity.copy(velocity);
  76261. };
  76262. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76263. impostor.physicsBody.angularVelocity.copy(velocity);
  76264. };
  76265. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76266. var v = impostor.physicsBody.velocity;
  76267. if (!v) {
  76268. return null;
  76269. }
  76270. return new BABYLON.Vector3(v.x, v.y, v.z);
  76271. };
  76272. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76273. var v = impostor.physicsBody.angularVelocity;
  76274. if (!v) {
  76275. return null;
  76276. }
  76277. return new BABYLON.Vector3(v.x, v.y, v.z);
  76278. };
  76279. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76280. impostor.physicsBody.mass = mass;
  76281. impostor.physicsBody.updateMassProperties();
  76282. };
  76283. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76284. return impostor.physicsBody.mass;
  76285. };
  76286. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76287. return impostor.physicsBody.material.friction;
  76288. };
  76289. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76290. impostor.physicsBody.material.friction = friction;
  76291. };
  76292. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76293. return impostor.physicsBody.material.restitution;
  76294. };
  76295. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76296. impostor.physicsBody.material.restitution = restitution;
  76297. };
  76298. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76299. impostor.physicsBody.sleep();
  76300. };
  76301. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76302. impostor.physicsBody.wakeUp();
  76303. };
  76304. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76305. joint.physicsJoint.distance = maxDistance;
  76306. };
  76307. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76308. // if (!motorIndex) {
  76309. // joint.physicsJoint.enableMotor();
  76310. // }
  76311. // }
  76312. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76313. // if (!motorIndex) {
  76314. // joint.physicsJoint.disableMotor();
  76315. // }
  76316. // }
  76317. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76318. if (!motorIndex) {
  76319. joint.physicsJoint.enableMotor();
  76320. joint.physicsJoint.setMotorSpeed(speed);
  76321. if (maxForce) {
  76322. this.setLimit(joint, maxForce);
  76323. }
  76324. }
  76325. };
  76326. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76327. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76328. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76329. };
  76330. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76331. var body = impostor.physicsBody;
  76332. mesh.position.x = body.position.x;
  76333. mesh.position.y = body.position.y;
  76334. mesh.position.z = body.position.z;
  76335. if (mesh.rotationQuaternion) {
  76336. mesh.rotationQuaternion.x = body.quaternion.x;
  76337. mesh.rotationQuaternion.y = body.quaternion.y;
  76338. mesh.rotationQuaternion.z = body.quaternion.z;
  76339. mesh.rotationQuaternion.w = body.quaternion.w;
  76340. }
  76341. };
  76342. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76343. var shape = impostor.physicsBody.shapes[0];
  76344. return shape.boundingSphereRadius;
  76345. };
  76346. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76347. var shape = impostor.physicsBody.shapes[0];
  76348. result.x = shape.halfExtents.x * 2;
  76349. result.y = shape.halfExtents.y * 2;
  76350. result.z = shape.halfExtents.z * 2;
  76351. };
  76352. CannonJSPlugin.prototype.dispose = function () {
  76353. };
  76354. CannonJSPlugin.prototype._extendNamespace = function () {
  76355. //this will force cannon to execute at least one step when using interpolation
  76356. var step_tmp1 = new this.BJSCANNON.Vec3();
  76357. var Engine = this.BJSCANNON;
  76358. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76359. maxSubSteps = maxSubSteps || 10;
  76360. timeSinceLastCalled = timeSinceLastCalled || 0;
  76361. if (timeSinceLastCalled === 0) {
  76362. this.internalStep(dt);
  76363. this.time += dt;
  76364. }
  76365. else {
  76366. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76367. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76368. var t0 = performance.now();
  76369. for (var i = 0; i !== internalSteps; i++) {
  76370. this.internalStep(dt);
  76371. if (performance.now() - t0 > dt * 1000) {
  76372. break;
  76373. }
  76374. }
  76375. this.time += timeSinceLastCalled;
  76376. var h = this.time % dt;
  76377. var h_div_dt = h / dt;
  76378. var interpvelo = step_tmp1;
  76379. var bodies = this.bodies;
  76380. for (var j = 0; j !== bodies.length; j++) {
  76381. var b = bodies[j];
  76382. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76383. b.position.vsub(b.previousPosition, interpvelo);
  76384. interpvelo.scale(h_div_dt, interpvelo);
  76385. b.position.vadd(interpvelo, b.interpolatedPosition);
  76386. }
  76387. else {
  76388. b.interpolatedPosition.copy(b.position);
  76389. b.interpolatedQuaternion.copy(b.quaternion);
  76390. }
  76391. }
  76392. }
  76393. };
  76394. };
  76395. return CannonJSPlugin;
  76396. }());
  76397. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76398. })(BABYLON || (BABYLON = {}));
  76399. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76400. var BABYLON;
  76401. (function (BABYLON) {
  76402. var OimoJSPlugin = /** @class */ (function () {
  76403. function OimoJSPlugin(iterations) {
  76404. this.name = "OimoJSPlugin";
  76405. this._tmpImpostorsArray = [];
  76406. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76407. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76408. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76409. this.world.worldscale(1);
  76410. this.world.clear();
  76411. //making sure no stats are calculated
  76412. this.world.isNoStat = true;
  76413. }
  76414. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76415. this.world.gravity.copy(gravity);
  76416. };
  76417. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76418. this.world.timeStep = timeStep;
  76419. };
  76420. OimoJSPlugin.prototype.getTimeStep = function () {
  76421. return this.world.timeStep;
  76422. };
  76423. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76424. var _this = this;
  76425. impostors.forEach(function (impostor) {
  76426. impostor.beforeStep();
  76427. });
  76428. this.world.step();
  76429. impostors.forEach(function (impostor) {
  76430. impostor.afterStep();
  76431. //update the ordered impostors array
  76432. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76433. });
  76434. //check for collisions
  76435. var contact = this.world.contacts;
  76436. while (contact !== null) {
  76437. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76438. contact = contact.next;
  76439. continue;
  76440. }
  76441. //is this body colliding with any other? get the impostor
  76442. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76443. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76444. if (!mainImpostor || !collidingImpostor) {
  76445. contact = contact.next;
  76446. continue;
  76447. }
  76448. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76449. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76450. contact = contact.next;
  76451. }
  76452. };
  76453. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76454. var mass = impostor.physicsBody.massInfo.mass;
  76455. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76456. };
  76457. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76458. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76459. this.applyImpulse(impostor, force, contactPoint);
  76460. };
  76461. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76462. var _this = this;
  76463. //parent-child relationship. Does this impostor has a parent impostor?
  76464. if (impostor.parent) {
  76465. if (impostor.physicsBody) {
  76466. this.removePhysicsBody(impostor);
  76467. //TODO is that needed?
  76468. impostor.forceUpdate();
  76469. }
  76470. return;
  76471. }
  76472. if (impostor.isBodyInitRequired()) {
  76473. var bodyConfig = {
  76474. name: impostor.uniqueId,
  76475. //Oimo must have mass, also for static objects.
  76476. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76477. size: [],
  76478. type: [],
  76479. pos: [],
  76480. rot: [],
  76481. move: impostor.getParam("mass") !== 0,
  76482. //Supporting older versions of Oimo
  76483. world: this.world
  76484. };
  76485. var impostors = [impostor];
  76486. var addToArray = function (parent) {
  76487. if (!parent.getChildMeshes)
  76488. return;
  76489. parent.getChildMeshes().forEach(function (m) {
  76490. if (m.physicsImpostor) {
  76491. impostors.push(m.physicsImpostor);
  76492. //m.physicsImpostor._init();
  76493. }
  76494. });
  76495. };
  76496. addToArray(impostor.object);
  76497. var checkWithEpsilon_1 = function (value) {
  76498. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76499. };
  76500. impostors.forEach(function (i) {
  76501. if (!impostor.object.rotationQuaternion) {
  76502. return;
  76503. }
  76504. //get the correct bounding box
  76505. var oldQuaternion = i.object.rotationQuaternion;
  76506. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76507. x: impostor.object.rotationQuaternion.x,
  76508. y: impostor.object.rotationQuaternion.y,
  76509. z: impostor.object.rotationQuaternion.z,
  76510. s: impostor.object.rotationQuaternion.w
  76511. });
  76512. var extendSize = i.getObjectExtendSize();
  76513. if (i === impostor) {
  76514. var center = impostor.getObjectCenter();
  76515. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76516. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76517. //Can also use Array.prototype.push.apply
  76518. bodyConfig.pos.push(center.x);
  76519. bodyConfig.pos.push(center.y);
  76520. bodyConfig.pos.push(center.z);
  76521. //tmp solution
  76522. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76523. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76524. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76525. }
  76526. else {
  76527. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76528. bodyConfig.pos.push(localPosition.x);
  76529. bodyConfig.pos.push(localPosition.y);
  76530. bodyConfig.pos.push(localPosition.z);
  76531. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76532. bodyConfig.rot.push(0);
  76533. bodyConfig.rot.push(0);
  76534. bodyConfig.rot.push(0);
  76535. }
  76536. // register mesh
  76537. switch (i.type) {
  76538. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76539. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76540. case BABYLON.PhysicsImpostor.SphereImpostor:
  76541. var radiusX = extendSize.x;
  76542. var radiusY = extendSize.y;
  76543. var radiusZ = extendSize.z;
  76544. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76545. bodyConfig.type.push('sphere');
  76546. //due to the way oimo works with compounds, add 3 times
  76547. bodyConfig.size.push(size);
  76548. bodyConfig.size.push(size);
  76549. bodyConfig.size.push(size);
  76550. break;
  76551. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76552. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76553. var sizeY = checkWithEpsilon_1(extendSize.y);
  76554. bodyConfig.type.push('cylinder');
  76555. bodyConfig.size.push(sizeX);
  76556. bodyConfig.size.push(sizeY);
  76557. //due to the way oimo works with compounds, add one more value.
  76558. bodyConfig.size.push(sizeY);
  76559. break;
  76560. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76561. case BABYLON.PhysicsImpostor.BoxImpostor:
  76562. default:
  76563. var sizeX = checkWithEpsilon_1(extendSize.x);
  76564. var sizeY = checkWithEpsilon_1(extendSize.y);
  76565. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76566. bodyConfig.type.push('box');
  76567. bodyConfig.size.push(sizeX);
  76568. bodyConfig.size.push(sizeY);
  76569. bodyConfig.size.push(sizeZ);
  76570. break;
  76571. }
  76572. //actually not needed, but hey...
  76573. i.object.rotationQuaternion = oldQuaternion;
  76574. });
  76575. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76576. }
  76577. else {
  76578. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76579. }
  76580. impostor.setDeltaPosition(this._tmpPositionVector);
  76581. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76582. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76583. };
  76584. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76585. //impostor.physicsBody.dispose();
  76586. //Same as : (older oimo versions)
  76587. this.world.removeRigidBody(impostor.physicsBody);
  76588. };
  76589. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76590. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76591. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76592. if (!mainBody || !connectedBody) {
  76593. return;
  76594. }
  76595. var jointData = impostorJoint.joint.jointData;
  76596. var options = jointData.nativeParams || {};
  76597. var type;
  76598. var nativeJointData = {
  76599. body1: mainBody,
  76600. body2: connectedBody,
  76601. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76602. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76603. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76604. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76605. min: options.min,
  76606. max: options.max,
  76607. collision: options.collision || jointData.collision,
  76608. spring: options.spring,
  76609. //supporting older version of Oimo
  76610. world: this.world
  76611. };
  76612. switch (impostorJoint.joint.type) {
  76613. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76614. type = "jointBall";
  76615. break;
  76616. case BABYLON.PhysicsJoint.SpringJoint:
  76617. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76618. var springData = jointData;
  76619. nativeJointData.min = springData.length || nativeJointData.min;
  76620. //Max should also be set, just make sure it is at least min
  76621. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76622. case BABYLON.PhysicsJoint.DistanceJoint:
  76623. type = "jointDistance";
  76624. nativeJointData.max = jointData.maxDistance;
  76625. break;
  76626. case BABYLON.PhysicsJoint.PrismaticJoint:
  76627. type = "jointPrisme";
  76628. break;
  76629. case BABYLON.PhysicsJoint.SliderJoint:
  76630. type = "jointSlide";
  76631. break;
  76632. case BABYLON.PhysicsJoint.WheelJoint:
  76633. type = "jointWheel";
  76634. break;
  76635. case BABYLON.PhysicsJoint.HingeJoint:
  76636. default:
  76637. type = "jointHinge";
  76638. break;
  76639. }
  76640. nativeJointData.type = type;
  76641. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76642. };
  76643. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76644. //Bug in Oimo prevents us from disposing a joint in the playground
  76645. //joint.joint.physicsJoint.dispose();
  76646. //So we will bruteforce it!
  76647. try {
  76648. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76649. }
  76650. catch (e) {
  76651. BABYLON.Tools.Warn(e);
  76652. }
  76653. };
  76654. OimoJSPlugin.prototype.isSupported = function () {
  76655. return this.BJSOIMO !== undefined;
  76656. };
  76657. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76658. if (!impostor.physicsBody.sleeping) {
  76659. //TODO check that
  76660. if (impostor.physicsBody.shapes.next) {
  76661. var parentShape = this._getLastShape(impostor.physicsBody);
  76662. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76663. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76664. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76665. }
  76666. else {
  76667. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76668. }
  76669. if (impostor.object.rotationQuaternion) {
  76670. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76671. impostor.object.rotationQuaternion.normalize();
  76672. }
  76673. }
  76674. };
  76675. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76676. var body = impostor.physicsBody;
  76677. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76678. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76679. body.syncShapes();
  76680. body.awake();
  76681. };
  76682. OimoJSPlugin.prototype._getLastShape = function (body) {
  76683. var lastShape = body.shapes;
  76684. while (lastShape.next) {
  76685. lastShape = lastShape.next;
  76686. }
  76687. return lastShape;
  76688. };
  76689. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76690. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76691. };
  76692. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76693. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76694. };
  76695. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76696. var v = impostor.physicsBody.linearVelocity;
  76697. if (!v) {
  76698. return null;
  76699. }
  76700. return new BABYLON.Vector3(v.x, v.y, v.z);
  76701. };
  76702. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76703. var v = impostor.physicsBody.angularVelocity;
  76704. if (!v) {
  76705. return null;
  76706. }
  76707. return new BABYLON.Vector3(v.x, v.y, v.z);
  76708. };
  76709. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76710. var staticBody = mass === 0;
  76711. //this will actually set the body's density and not its mass.
  76712. //But this is how oimo treats the mass variable.
  76713. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76714. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76715. };
  76716. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76717. return impostor.physicsBody.shapes.density;
  76718. };
  76719. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76720. return impostor.physicsBody.shapes.friction;
  76721. };
  76722. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76723. impostor.physicsBody.shapes.friction = friction;
  76724. };
  76725. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76726. return impostor.physicsBody.shapes.restitution;
  76727. };
  76728. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76729. impostor.physicsBody.shapes.restitution = restitution;
  76730. };
  76731. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76732. impostor.physicsBody.sleep();
  76733. };
  76734. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76735. impostor.physicsBody.awake();
  76736. };
  76737. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76738. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76739. if (minDistance !== void 0) {
  76740. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76741. }
  76742. };
  76743. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76744. //TODO separate rotational and transational motors.
  76745. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76746. if (motor) {
  76747. motor.setMotor(speed, maxForce);
  76748. }
  76749. };
  76750. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76751. //TODO separate rotational and transational motors.
  76752. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76753. if (motor) {
  76754. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76755. }
  76756. };
  76757. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76758. var body = impostor.physicsBody;
  76759. mesh.position.x = body.position.x;
  76760. mesh.position.y = body.position.y;
  76761. mesh.position.z = body.position.z;
  76762. if (mesh.rotationQuaternion) {
  76763. mesh.rotationQuaternion.x = body.orientation.x;
  76764. mesh.rotationQuaternion.y = body.orientation.y;
  76765. mesh.rotationQuaternion.z = body.orientation.z;
  76766. mesh.rotationQuaternion.w = body.orientation.s;
  76767. }
  76768. };
  76769. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76770. return impostor.physicsBody.shapes.radius;
  76771. };
  76772. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76773. var shape = impostor.physicsBody.shapes;
  76774. result.x = shape.halfWidth * 2;
  76775. result.y = shape.halfHeight * 2;
  76776. result.z = shape.halfDepth * 2;
  76777. };
  76778. OimoJSPlugin.prototype.dispose = function () {
  76779. this.world.clear();
  76780. };
  76781. return OimoJSPlugin;
  76782. }());
  76783. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76784. })(BABYLON || (BABYLON = {}));
  76785. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76786. var BABYLON;
  76787. (function (BABYLON) {
  76788. /*
  76789. * Based on jsTGALoader - Javascript loader for TGA file
  76790. * By Vincent Thibault
  76791. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76792. */
  76793. var TGATools = /** @class */ (function () {
  76794. function TGATools() {
  76795. }
  76796. TGATools.GetTGAHeader = function (data) {
  76797. var offset = 0;
  76798. var header = {
  76799. id_length: data[offset++],
  76800. colormap_type: data[offset++],
  76801. image_type: data[offset++],
  76802. colormap_index: data[offset++] | data[offset++] << 8,
  76803. colormap_length: data[offset++] | data[offset++] << 8,
  76804. colormap_size: data[offset++],
  76805. origin: [
  76806. data[offset++] | data[offset++] << 8,
  76807. data[offset++] | data[offset++] << 8
  76808. ],
  76809. width: data[offset++] | data[offset++] << 8,
  76810. height: data[offset++] | data[offset++] << 8,
  76811. pixel_size: data[offset++],
  76812. flags: data[offset++]
  76813. };
  76814. return header;
  76815. };
  76816. TGATools.UploadContent = function (gl, data) {
  76817. // Not enough data to contain header ?
  76818. if (data.length < 19) {
  76819. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76820. return;
  76821. }
  76822. // Read Header
  76823. var offset = 18;
  76824. var header = TGATools.GetTGAHeader(data);
  76825. // Assume it's a valid Targa file.
  76826. if (header.id_length + offset > data.length) {
  76827. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76828. return;
  76829. }
  76830. // Skip not needed data
  76831. offset += header.id_length;
  76832. var use_rle = false;
  76833. var use_pal = false;
  76834. var use_grey = false;
  76835. // Get some informations.
  76836. switch (header.image_type) {
  76837. case TGATools._TYPE_RLE_INDEXED:
  76838. use_rle = true;
  76839. case TGATools._TYPE_INDEXED:
  76840. use_pal = true;
  76841. break;
  76842. case TGATools._TYPE_RLE_RGB:
  76843. use_rle = true;
  76844. case TGATools._TYPE_RGB:
  76845. // use_rgb = true;
  76846. break;
  76847. case TGATools._TYPE_RLE_GREY:
  76848. use_rle = true;
  76849. case TGATools._TYPE_GREY:
  76850. use_grey = true;
  76851. break;
  76852. }
  76853. var pixel_data;
  76854. // var numAlphaBits = header.flags & 0xf;
  76855. var pixel_size = header.pixel_size >> 3;
  76856. var pixel_total = header.width * header.height * pixel_size;
  76857. // Read palettes
  76858. var palettes;
  76859. if (use_pal) {
  76860. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76861. }
  76862. // Read LRE
  76863. if (use_rle) {
  76864. pixel_data = new Uint8Array(pixel_total);
  76865. var c, count, i;
  76866. var localOffset = 0;
  76867. var pixels = new Uint8Array(pixel_size);
  76868. while (offset < pixel_total && localOffset < pixel_total) {
  76869. c = data[offset++];
  76870. count = (c & 0x7f) + 1;
  76871. // RLE pixels
  76872. if (c & 0x80) {
  76873. // Bind pixel tmp array
  76874. for (i = 0; i < pixel_size; ++i) {
  76875. pixels[i] = data[offset++];
  76876. }
  76877. // Copy pixel array
  76878. for (i = 0; i < count; ++i) {
  76879. pixel_data.set(pixels, localOffset + i * pixel_size);
  76880. }
  76881. localOffset += pixel_size * count;
  76882. }
  76883. else {
  76884. count *= pixel_size;
  76885. for (i = 0; i < count; ++i) {
  76886. pixel_data[localOffset + i] = data[offset++];
  76887. }
  76888. localOffset += count;
  76889. }
  76890. }
  76891. }
  76892. else {
  76893. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76894. }
  76895. // Load to texture
  76896. var x_start, y_start, x_step, y_step, y_end, x_end;
  76897. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76898. default:
  76899. case TGATools._ORIGIN_UL:
  76900. x_start = 0;
  76901. x_step = 1;
  76902. x_end = header.width;
  76903. y_start = 0;
  76904. y_step = 1;
  76905. y_end = header.height;
  76906. break;
  76907. case TGATools._ORIGIN_BL:
  76908. x_start = 0;
  76909. x_step = 1;
  76910. x_end = header.width;
  76911. y_start = header.height - 1;
  76912. y_step = -1;
  76913. y_end = -1;
  76914. break;
  76915. case TGATools._ORIGIN_UR:
  76916. x_start = header.width - 1;
  76917. x_step = -1;
  76918. x_end = -1;
  76919. y_start = 0;
  76920. y_step = 1;
  76921. y_end = header.height;
  76922. break;
  76923. case TGATools._ORIGIN_BR:
  76924. x_start = header.width - 1;
  76925. x_step = -1;
  76926. x_end = -1;
  76927. y_start = header.height - 1;
  76928. y_step = -1;
  76929. y_end = -1;
  76930. break;
  76931. }
  76932. // Load the specify method
  76933. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76934. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76935. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76936. };
  76937. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76938. var image = pixel_data, colormap = palettes;
  76939. var width = header.width, height = header.height;
  76940. var color, i = 0, x, y;
  76941. var imageData = new Uint8Array(width * height * 4);
  76942. for (y = y_start; y !== y_end; y += y_step) {
  76943. for (x = x_start; x !== x_end; x += x_step, i++) {
  76944. color = image[i];
  76945. imageData[(x + width * y) * 4 + 3] = 255;
  76946. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76947. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76948. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76949. }
  76950. }
  76951. return imageData;
  76952. };
  76953. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76954. var image = pixel_data;
  76955. var width = header.width, height = header.height;
  76956. var color, i = 0, x, y;
  76957. var imageData = new Uint8Array(width * height * 4);
  76958. for (y = y_start; y !== y_end; y += y_step) {
  76959. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76960. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76961. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76962. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76963. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76964. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76965. }
  76966. }
  76967. return imageData;
  76968. };
  76969. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76970. var image = pixel_data;
  76971. var width = header.width, height = header.height;
  76972. var i = 0, x, y;
  76973. var imageData = new Uint8Array(width * height * 4);
  76974. for (y = y_start; y !== y_end; y += y_step) {
  76975. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  76976. imageData[(x + width * y) * 4 + 3] = 255;
  76977. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76978. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76979. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76980. }
  76981. }
  76982. return imageData;
  76983. };
  76984. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76985. var image = pixel_data;
  76986. var width = header.width, height = header.height;
  76987. var i = 0, x, y;
  76988. var imageData = new Uint8Array(width * height * 4);
  76989. for (y = y_start; y !== y_end; y += y_step) {
  76990. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  76991. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76992. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76993. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76994. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  76995. }
  76996. }
  76997. return imageData;
  76998. };
  76999. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77000. var image = pixel_data;
  77001. var width = header.width, height = header.height;
  77002. var color, i = 0, x, y;
  77003. var imageData = new Uint8Array(width * height * 4);
  77004. for (y = y_start; y !== y_end; y += y_step) {
  77005. for (x = x_start; x !== x_end; x += x_step, i++) {
  77006. color = image[i];
  77007. imageData[(x + width * y) * 4 + 0] = color;
  77008. imageData[(x + width * y) * 4 + 1] = color;
  77009. imageData[(x + width * y) * 4 + 2] = color;
  77010. imageData[(x + width * y) * 4 + 3] = 255;
  77011. }
  77012. }
  77013. return imageData;
  77014. };
  77015. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  77016. var image = pixel_data;
  77017. var width = header.width, height = header.height;
  77018. var i = 0, x, y;
  77019. var imageData = new Uint8Array(width * height * 4);
  77020. for (y = y_start; y !== y_end; y += y_step) {
  77021. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  77022. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  77023. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  77024. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  77025. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  77026. }
  77027. }
  77028. return imageData;
  77029. };
  77030. //private static _TYPE_NO_DATA = 0;
  77031. TGATools._TYPE_INDEXED = 1;
  77032. TGATools._TYPE_RGB = 2;
  77033. TGATools._TYPE_GREY = 3;
  77034. TGATools._TYPE_RLE_INDEXED = 9;
  77035. TGATools._TYPE_RLE_RGB = 10;
  77036. TGATools._TYPE_RLE_GREY = 11;
  77037. TGATools._ORIGIN_MASK = 0x30;
  77038. TGATools._ORIGIN_SHIFT = 0x04;
  77039. TGATools._ORIGIN_BL = 0x00;
  77040. TGATools._ORIGIN_BR = 0x01;
  77041. TGATools._ORIGIN_UL = 0x02;
  77042. TGATools._ORIGIN_UR = 0x03;
  77043. return TGATools;
  77044. }());
  77045. BABYLON.TGATools = TGATools;
  77046. })(BABYLON || (BABYLON = {}));
  77047. //# sourceMappingURL=babylon.tga.js.map
  77048. var BABYLON;
  77049. (function (BABYLON) {
  77050. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  77051. // All values and structures referenced from:
  77052. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  77053. var DDS_MAGIC = 0x20534444;
  77054. var
  77055. //DDSD_CAPS = 0x1,
  77056. //DDSD_HEIGHT = 0x2,
  77057. //DDSD_WIDTH = 0x4,
  77058. //DDSD_PITCH = 0x8,
  77059. //DDSD_PIXELFORMAT = 0x1000,
  77060. DDSD_MIPMAPCOUNT = 0x20000;
  77061. //DDSD_LINEARSIZE = 0x80000,
  77062. //DDSD_DEPTH = 0x800000;
  77063. // var DDSCAPS_COMPLEX = 0x8,
  77064. // DDSCAPS_MIPMAP = 0x400000,
  77065. // DDSCAPS_TEXTURE = 0x1000;
  77066. var DDSCAPS2_CUBEMAP = 0x200;
  77067. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77068. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77069. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77070. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77071. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77072. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77073. // DDSCAPS2_VOLUME = 0x200000;
  77074. var
  77075. //DDPF_ALPHAPIXELS = 0x1,
  77076. //DDPF_ALPHA = 0x2,
  77077. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77078. //DDPF_YUV = 0x200,
  77079. DDPF_LUMINANCE = 0x20000;
  77080. function FourCCToInt32(value) {
  77081. return value.charCodeAt(0) +
  77082. (value.charCodeAt(1) << 8) +
  77083. (value.charCodeAt(2) << 16) +
  77084. (value.charCodeAt(3) << 24);
  77085. }
  77086. function Int32ToFourCC(value) {
  77087. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77088. }
  77089. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77090. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77091. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77092. var FOURCC_DX10 = FourCCToInt32("DX10");
  77093. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77094. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77095. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77096. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77097. var headerLengthInt = 31; // The header length in 32 bit ints
  77098. // Offsets into the header array
  77099. var off_magic = 0;
  77100. var off_size = 1;
  77101. var off_flags = 2;
  77102. var off_height = 3;
  77103. var off_width = 4;
  77104. var off_mipmapCount = 7;
  77105. var off_pfFlags = 20;
  77106. var off_pfFourCC = 21;
  77107. var off_RGBbpp = 22;
  77108. var off_RMask = 23;
  77109. var off_GMask = 24;
  77110. var off_BMask = 25;
  77111. var off_AMask = 26;
  77112. // var off_caps1 = 27;
  77113. var off_caps2 = 28;
  77114. // var off_caps3 = 29;
  77115. // var off_caps4 = 30;
  77116. var off_dxgiFormat = 32;
  77117. ;
  77118. var DDSTools = /** @class */ (function () {
  77119. function DDSTools() {
  77120. }
  77121. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77122. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77123. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77124. var mipmapCount = 1;
  77125. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77126. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77127. }
  77128. var fourCC = header[off_pfFourCC];
  77129. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77130. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77131. switch (fourCC) {
  77132. case FOURCC_D3DFMT_R16G16B16A16F:
  77133. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77134. break;
  77135. case FOURCC_D3DFMT_R32G32B32A32F:
  77136. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77137. break;
  77138. case FOURCC_DX10:
  77139. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77140. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77141. break;
  77142. }
  77143. }
  77144. return {
  77145. width: header[off_width],
  77146. height: header[off_height],
  77147. mipmapCount: mipmapCount,
  77148. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77149. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77150. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77151. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77152. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77153. dxgiFormat: dxgiFormat,
  77154. textureType: textureType
  77155. };
  77156. };
  77157. DDSTools._ToHalfFloat = function (value) {
  77158. if (!DDSTools._FloatView) {
  77159. DDSTools._FloatView = new Float32Array(1);
  77160. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77161. }
  77162. DDSTools._FloatView[0] = value;
  77163. var x = DDSTools._Int32View[0];
  77164. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77165. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77166. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77167. /* If zero, or denormal, or exponent underflows too much for a denormal
  77168. * half, return signed zero. */
  77169. if (e < 103) {
  77170. return bits;
  77171. }
  77172. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77173. if (e > 142) {
  77174. bits |= 0x7c00;
  77175. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77176. * not Inf, so make sure we set one mantissa bit too. */
  77177. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77178. return bits;
  77179. }
  77180. /* If exponent underflows but not too much, return a denormal */
  77181. if (e < 113) {
  77182. m |= 0x0800;
  77183. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77184. * to 1, which is OK. */
  77185. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77186. return bits;
  77187. }
  77188. bits |= ((e - 112) << 10) | (m >> 1);
  77189. bits += m & 1;
  77190. return bits;
  77191. };
  77192. DDSTools._FromHalfFloat = function (value) {
  77193. var s = (value & 0x8000) >> 15;
  77194. var e = (value & 0x7C00) >> 10;
  77195. var f = value & 0x03FF;
  77196. if (e === 0) {
  77197. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77198. }
  77199. else if (e == 0x1F) {
  77200. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77201. }
  77202. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77203. };
  77204. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77205. var destArray = new Float32Array(dataLength);
  77206. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77207. var index = 0;
  77208. for (var y = 0; y < height; y++) {
  77209. for (var x = 0; x < width; x++) {
  77210. var srcPos = (x + y * width) * 4;
  77211. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77212. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77213. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77214. if (DDSTools.StoreLODInAlphaChannel) {
  77215. destArray[index + 3] = lod;
  77216. }
  77217. else {
  77218. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77219. }
  77220. index += 4;
  77221. }
  77222. }
  77223. return destArray;
  77224. };
  77225. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77226. if (DDSTools.StoreLODInAlphaChannel) {
  77227. var destArray = new Uint16Array(dataLength);
  77228. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77229. var index = 0;
  77230. for (var y = 0; y < height; y++) {
  77231. for (var x = 0; x < width; x++) {
  77232. var srcPos = (x + y * width) * 4;
  77233. destArray[index] = srcData[srcPos];
  77234. destArray[index + 1] = srcData[srcPos + 1];
  77235. destArray[index + 2] = srcData[srcPos + 2];
  77236. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77237. index += 4;
  77238. }
  77239. }
  77240. return destArray;
  77241. }
  77242. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77243. };
  77244. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77245. if (DDSTools.StoreLODInAlphaChannel) {
  77246. var destArray = new Float32Array(dataLength);
  77247. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77248. var index = 0;
  77249. for (var y = 0; y < height; y++) {
  77250. for (var x = 0; x < width; x++) {
  77251. var srcPos = (x + y * width) * 4;
  77252. destArray[index] = srcData[srcPos];
  77253. destArray[index + 1] = srcData[srcPos + 1];
  77254. destArray[index + 2] = srcData[srcPos + 2];
  77255. destArray[index + 3] = lod;
  77256. index += 4;
  77257. }
  77258. }
  77259. return destArray;
  77260. }
  77261. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77262. };
  77263. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77264. var destArray = new Uint8Array(dataLength);
  77265. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77266. var index = 0;
  77267. for (var y = 0; y < height; y++) {
  77268. for (var x = 0; x < width; x++) {
  77269. var srcPos = (x + y * width) * 4;
  77270. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77271. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77272. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77273. if (DDSTools.StoreLODInAlphaChannel) {
  77274. destArray[index + 3] = lod;
  77275. }
  77276. else {
  77277. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77278. }
  77279. index += 4;
  77280. }
  77281. }
  77282. return destArray;
  77283. };
  77284. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77285. var destArray = new Uint8Array(dataLength);
  77286. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77287. var index = 0;
  77288. for (var y = 0; y < height; y++) {
  77289. for (var x = 0; x < width; x++) {
  77290. var srcPos = (x + y * width) * 4;
  77291. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77292. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77293. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77294. if (DDSTools.StoreLODInAlphaChannel) {
  77295. destArray[index + 3] = lod;
  77296. }
  77297. else {
  77298. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77299. }
  77300. index += 4;
  77301. }
  77302. }
  77303. return destArray;
  77304. };
  77305. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77306. var byteArray = new Uint8Array(dataLength);
  77307. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77308. var index = 0;
  77309. for (var y = 0; y < height; y++) {
  77310. for (var x = 0; x < width; x++) {
  77311. var srcPos = (x + y * width) * 4;
  77312. byteArray[index] = srcData[srcPos + rOffset];
  77313. byteArray[index + 1] = srcData[srcPos + gOffset];
  77314. byteArray[index + 2] = srcData[srcPos + bOffset];
  77315. byteArray[index + 3] = srcData[srcPos + aOffset];
  77316. index += 4;
  77317. }
  77318. }
  77319. return byteArray;
  77320. };
  77321. DDSTools._ExtractLongWordOrder = function (value) {
  77322. if (value === 0 || value === 255 || value === -16777216) {
  77323. return 0;
  77324. }
  77325. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77326. };
  77327. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77328. var byteArray = new Uint8Array(dataLength);
  77329. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77330. var index = 0;
  77331. for (var y = 0; y < height; y++) {
  77332. for (var x = 0; x < width; x++) {
  77333. var srcPos = (x + y * width) * 3;
  77334. byteArray[index] = srcData[srcPos + rOffset];
  77335. byteArray[index + 1] = srcData[srcPos + gOffset];
  77336. byteArray[index + 2] = srcData[srcPos + bOffset];
  77337. index += 3;
  77338. }
  77339. }
  77340. return byteArray;
  77341. };
  77342. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77343. var byteArray = new Uint8Array(dataLength);
  77344. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77345. var index = 0;
  77346. for (var y = 0; y < height; y++) {
  77347. for (var x = 0; x < width; x++) {
  77348. var srcPos = (x + y * width);
  77349. byteArray[index] = srcData[srcPos];
  77350. index++;
  77351. }
  77352. }
  77353. return byteArray;
  77354. };
  77355. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77356. if (lodIndex === void 0) { lodIndex = -1; }
  77357. var ext = engine.getCaps().s3tc;
  77358. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77359. var fourCC, width, height, dataLength = 0, dataOffset;
  77360. var byteArray, mipmapCount, mip;
  77361. var internalFormat = 0;
  77362. var format = 0;
  77363. var blockBytes = 1;
  77364. if (header[off_magic] !== DDS_MAGIC) {
  77365. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77366. return;
  77367. }
  77368. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77369. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77370. return;
  77371. }
  77372. if (info.isCompressed && !ext) {
  77373. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77374. return;
  77375. }
  77376. var bpp = header[off_RGBbpp];
  77377. dataOffset = header[off_size] + 4;
  77378. var computeFormats = false;
  77379. if (info.isFourCC) {
  77380. fourCC = header[off_pfFourCC];
  77381. switch (fourCC) {
  77382. case FOURCC_DXT1:
  77383. blockBytes = 8;
  77384. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77385. break;
  77386. case FOURCC_DXT3:
  77387. blockBytes = 16;
  77388. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77389. break;
  77390. case FOURCC_DXT5:
  77391. blockBytes = 16;
  77392. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77393. break;
  77394. case FOURCC_D3DFMT_R16G16B16A16F:
  77395. computeFormats = true;
  77396. break;
  77397. case FOURCC_D3DFMT_R32G32B32A32F:
  77398. computeFormats = true;
  77399. break;
  77400. case FOURCC_DX10:
  77401. // There is an additionnal header so dataOffset need to be changed
  77402. dataOffset += 5 * 4; // 5 uints
  77403. var supported = false;
  77404. switch (info.dxgiFormat) {
  77405. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77406. computeFormats = true;
  77407. supported = true;
  77408. break;
  77409. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77410. info.isRGB = true;
  77411. info.isFourCC = false;
  77412. bpp = 32;
  77413. supported = true;
  77414. break;
  77415. }
  77416. if (supported) {
  77417. break;
  77418. }
  77419. default:
  77420. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77421. return;
  77422. }
  77423. }
  77424. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77425. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77426. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77427. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77428. if (computeFormats) {
  77429. format = engine._getWebGLTextureType(info.textureType);
  77430. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77431. }
  77432. mipmapCount = 1;
  77433. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77434. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77435. }
  77436. for (var face = 0; face < faces; face++) {
  77437. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77438. width = header[off_width];
  77439. height = header[off_height];
  77440. for (mip = 0; mip < mipmapCount; ++mip) {
  77441. if (lodIndex === -1 || lodIndex === mip) {
  77442. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77443. var i = (lodIndex === -1) ? mip : 0;
  77444. if (!info.isCompressed && info.isFourCC) {
  77445. dataLength = width * height * 4;
  77446. var floatArray = null;
  77447. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77448. if (bpp === 128) {
  77449. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77450. }
  77451. else if (bpp === 64) {
  77452. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77453. }
  77454. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77455. format = engine._getWebGLTextureType(info.textureType);
  77456. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77457. }
  77458. else {
  77459. if (bpp === 128) {
  77460. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77461. }
  77462. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77463. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77464. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77465. format = engine._getWebGLTextureType(info.textureType);
  77466. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77467. }
  77468. else {
  77469. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77470. }
  77471. }
  77472. if (floatArray) {
  77473. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77474. }
  77475. }
  77476. else if (info.isRGB) {
  77477. if (bpp === 24) {
  77478. dataLength = width * height * 3;
  77479. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77480. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77481. }
  77482. else {
  77483. dataLength = width * height * 4;
  77484. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77485. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77486. }
  77487. }
  77488. else if (info.isLuminance) {
  77489. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77490. var unpaddedRowSize = width;
  77491. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77492. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77493. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77494. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77495. }
  77496. else {
  77497. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77498. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77499. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77500. }
  77501. }
  77502. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77503. width *= 0.5;
  77504. height *= 0.5;
  77505. width = Math.max(1.0, width);
  77506. height = Math.max(1.0, height);
  77507. }
  77508. if (currentFace !== undefined) {
  77509. // Loading a single face
  77510. break;
  77511. }
  77512. }
  77513. };
  77514. DDSTools.StoreLODInAlphaChannel = false;
  77515. return DDSTools;
  77516. }());
  77517. BABYLON.DDSTools = DDSTools;
  77518. })(BABYLON || (BABYLON = {}));
  77519. //# sourceMappingURL=babylon.dds.js.map
  77520. var BABYLON;
  77521. (function (BABYLON) {
  77522. /**
  77523. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77524. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77525. */
  77526. var KhronosTextureContainer = /** @class */ (function () {
  77527. /**
  77528. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77529. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77530. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77531. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77532. */
  77533. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77534. this.arrayBuffer = arrayBuffer;
  77535. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77536. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77537. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77538. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77539. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77540. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77541. BABYLON.Tools.Error("texture missing KTX identifier");
  77542. return;
  77543. }
  77544. // load the reset of the header in native 32 bit int
  77545. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77546. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77547. var oppositeEndianess = header[0] === 0x01020304;
  77548. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77549. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77550. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77551. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77552. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77553. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77554. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77555. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77556. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77557. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77558. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77559. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77560. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77561. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77562. if (this.glType !== 0) {
  77563. BABYLON.Tools.Error("only compressed formats currently supported");
  77564. return;
  77565. }
  77566. else {
  77567. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77568. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77569. }
  77570. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77571. BABYLON.Tools.Error("only 2D textures currently supported");
  77572. return;
  77573. }
  77574. if (this.numberOfArrayElements !== 0) {
  77575. BABYLON.Tools.Error("texture arrays not currently supported");
  77576. return;
  77577. }
  77578. if (this.numberOfFaces !== facesExpected) {
  77579. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77580. return;
  77581. }
  77582. // we now have a completely validated file, so could use existence of loadType as success
  77583. // would need to make this more elaborate & adjust checks above to support more than one load type
  77584. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77585. }
  77586. // not as fast hardware based, but will probably never need to use
  77587. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77588. return ((val & 0xFF) << 24)
  77589. | ((val & 0xFF00) << 8)
  77590. | ((val >> 8) & 0xFF00)
  77591. | ((val >> 24) & 0xFF);
  77592. };
  77593. /**
  77594. * It is assumed that the texture has already been created & is currently bound
  77595. */
  77596. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77597. switch (this.loadType) {
  77598. case KhronosTextureContainer.COMPRESSED_2D:
  77599. this._upload2DCompressedLevels(gl, loadMipmaps);
  77600. break;
  77601. case KhronosTextureContainer.TEX_2D:
  77602. case KhronosTextureContainer.COMPRESSED_3D:
  77603. case KhronosTextureContainer.TEX_3D:
  77604. }
  77605. };
  77606. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77607. // initialize width & height for level 1
  77608. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77609. var width = this.pixelWidth;
  77610. var height = this.pixelHeight;
  77611. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77612. for (var level = 0; level < mipmapCount; level++) {
  77613. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77614. for (var face = 0; face < this.numberOfFaces; face++) {
  77615. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77616. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77617. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77618. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77619. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77620. }
  77621. width = Math.max(1.0, width * 0.5);
  77622. height = Math.max(1.0, height * 0.5);
  77623. }
  77624. };
  77625. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77626. // load types
  77627. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77628. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77629. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77630. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77631. return KhronosTextureContainer;
  77632. }());
  77633. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77634. })(BABYLON || (BABYLON = {}));
  77635. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77636. var BABYLON;
  77637. (function (BABYLON) {
  77638. var Debug = /** @class */ (function () {
  77639. function Debug() {
  77640. }
  77641. Debug.AxesViewer = /** @class */ (function () {
  77642. function AxesViewer(scene, scaleLines) {
  77643. if (scaleLines === void 0) { scaleLines = 1; }
  77644. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77645. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77646. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77647. this.scaleLines = 1;
  77648. this.scaleLines = scaleLines;
  77649. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77650. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77651. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77652. this._xmesh.renderingGroupId = 2;
  77653. this._ymesh.renderingGroupId = 2;
  77654. this._zmesh.renderingGroupId = 2;
  77655. this._xmesh.material.checkReadyOnlyOnce = true;
  77656. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77657. this._ymesh.material.checkReadyOnlyOnce = true;
  77658. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77659. this._zmesh.material.checkReadyOnlyOnce = true;
  77660. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77661. this.scene = scene;
  77662. }
  77663. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77664. var scaleLines = this.scaleLines;
  77665. if (this._xmesh) {
  77666. this._xmesh.position.copyFrom(position);
  77667. }
  77668. if (this._ymesh) {
  77669. this._ymesh.position.copyFrom(position);
  77670. }
  77671. if (this._zmesh) {
  77672. this._zmesh.position.copyFrom(position);
  77673. }
  77674. var point2 = this._xline[1];
  77675. point2.x = xaxis.x * scaleLines;
  77676. point2.y = xaxis.y * scaleLines;
  77677. point2.z = xaxis.z * scaleLines;
  77678. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77679. point2 = this._yline[1];
  77680. point2.x = yaxis.x * scaleLines;
  77681. point2.y = yaxis.y * scaleLines;
  77682. point2.z = yaxis.z * scaleLines;
  77683. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77684. point2 = this._zline[1];
  77685. point2.x = zaxis.x * scaleLines;
  77686. point2.y = zaxis.y * scaleLines;
  77687. point2.z = zaxis.z * scaleLines;
  77688. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77689. };
  77690. AxesViewer.prototype.dispose = function () {
  77691. if (this._xmesh) {
  77692. this._xmesh.dispose();
  77693. }
  77694. if (this._ymesh) {
  77695. this._ymesh.dispose();
  77696. }
  77697. if (this._zmesh) {
  77698. this._zmesh.dispose();
  77699. }
  77700. this._xmesh = null;
  77701. this._ymesh = null;
  77702. this._zmesh = null;
  77703. this.scene = null;
  77704. };
  77705. return AxesViewer;
  77706. }());
  77707. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77708. __extends(BoneAxesViewer, _super);
  77709. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77710. if (scaleLines === void 0) { scaleLines = 1; }
  77711. var _this = _super.call(this, scene, scaleLines) || this;
  77712. _this.pos = BABYLON.Vector3.Zero();
  77713. _this.xaxis = BABYLON.Vector3.Zero();
  77714. _this.yaxis = BABYLON.Vector3.Zero();
  77715. _this.zaxis = BABYLON.Vector3.Zero();
  77716. _this.mesh = mesh;
  77717. _this.bone = bone;
  77718. return _this;
  77719. }
  77720. BoneAxesViewer.prototype.update = function () {
  77721. if (!this.mesh || !this.bone) {
  77722. return;
  77723. }
  77724. var bone = this.bone;
  77725. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77726. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77727. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77728. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77729. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77730. };
  77731. BoneAxesViewer.prototype.dispose = function () {
  77732. if (this.mesh) {
  77733. this.mesh = null;
  77734. this.bone = null;
  77735. _super.prototype.dispose.call(this);
  77736. }
  77737. };
  77738. return BoneAxesViewer;
  77739. }(Debug.AxesViewer));
  77740. Debug.PhysicsViewer = /** @class */ (function () {
  77741. function PhysicsViewer(scene) {
  77742. this._impostors = [];
  77743. this._meshes = [];
  77744. this._numMeshes = 0;
  77745. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77746. var physicEngine = this._scene.getPhysicsEngine();
  77747. if (physicEngine) {
  77748. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77749. }
  77750. }
  77751. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77752. var plugin = this._physicsEnginePlugin;
  77753. for (var i = 0; i < this._numMeshes; i++) {
  77754. var impostor = this._impostors[i];
  77755. if (!impostor) {
  77756. continue;
  77757. }
  77758. if (impostor.isDisposed) {
  77759. this.hideImpostor(this._impostors[i--]);
  77760. }
  77761. else {
  77762. var mesh = this._meshes[i];
  77763. if (mesh && plugin) {
  77764. plugin.syncMeshWithImpostor(mesh, impostor);
  77765. }
  77766. }
  77767. }
  77768. };
  77769. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77770. if (!this._scene) {
  77771. return;
  77772. }
  77773. for (var i = 0; i < this._numMeshes; i++) {
  77774. if (this._impostors[i] == impostor) {
  77775. return;
  77776. }
  77777. }
  77778. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77779. if (debugMesh) {
  77780. this._impostors[this._numMeshes] = impostor;
  77781. this._meshes[this._numMeshes] = debugMesh;
  77782. if (this._numMeshes === 0) {
  77783. this._renderFunction = this._updateDebugMeshes.bind(this);
  77784. this._scene.registerBeforeRender(this._renderFunction);
  77785. }
  77786. this._numMeshes++;
  77787. }
  77788. };
  77789. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77790. if (!impostor || !this._scene) {
  77791. return;
  77792. }
  77793. var removed = false;
  77794. for (var i = 0; i < this._numMeshes; i++) {
  77795. if (this._impostors[i] == impostor) {
  77796. var mesh = this._meshes[i];
  77797. if (!mesh) {
  77798. continue;
  77799. }
  77800. this._scene.removeMesh(mesh);
  77801. mesh.dispose();
  77802. this._numMeshes--;
  77803. if (this._numMeshes > 0) {
  77804. this._meshes[i] = this._meshes[this._numMeshes];
  77805. this._impostors[i] = this._impostors[this._numMeshes];
  77806. this._meshes[this._numMeshes] = null;
  77807. this._impostors[this._numMeshes] = null;
  77808. }
  77809. else {
  77810. this._meshes[0] = null;
  77811. this._impostors[0] = null;
  77812. }
  77813. removed = true;
  77814. break;
  77815. }
  77816. }
  77817. if (removed && this._numMeshes === 0) {
  77818. this._scene.unregisterBeforeRender(this._renderFunction);
  77819. }
  77820. };
  77821. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77822. if (!this._debugMaterial) {
  77823. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77824. this._debugMaterial.wireframe = true;
  77825. }
  77826. return this._debugMaterial;
  77827. };
  77828. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77829. if (!this._debugBoxMesh) {
  77830. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77831. this._debugBoxMesh.renderingGroupId = 1;
  77832. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77833. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77834. scene.removeMesh(this._debugBoxMesh);
  77835. }
  77836. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77837. };
  77838. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77839. if (!this._debugSphereMesh) {
  77840. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77841. this._debugSphereMesh.renderingGroupId = 1;
  77842. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77843. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77844. scene.removeMesh(this._debugSphereMesh);
  77845. }
  77846. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77847. };
  77848. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77849. var mesh = null;
  77850. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77851. mesh = this._getDebugBoxMesh(scene);
  77852. impostor.getBoxSizeToRef(mesh.scaling);
  77853. }
  77854. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77855. mesh = this._getDebugSphereMesh(scene);
  77856. var radius = impostor.getRadius();
  77857. mesh.scaling.x = radius * 2;
  77858. mesh.scaling.y = radius * 2;
  77859. mesh.scaling.z = radius * 2;
  77860. }
  77861. return mesh;
  77862. };
  77863. PhysicsViewer.prototype.dispose = function () {
  77864. for (var i = 0; i < this._numMeshes; i++) {
  77865. this.hideImpostor(this._impostors[i]);
  77866. }
  77867. if (this._debugBoxMesh) {
  77868. this._debugBoxMesh.dispose();
  77869. }
  77870. if (this._debugSphereMesh) {
  77871. this._debugSphereMesh.dispose();
  77872. }
  77873. if (this._debugMaterial) {
  77874. this._debugMaterial.dispose();
  77875. }
  77876. this._impostors.length = 0;
  77877. this._scene = null;
  77878. this._physicsEnginePlugin = null;
  77879. };
  77880. return PhysicsViewer;
  77881. }());
  77882. Debug.SkeletonViewer = /** @class */ (function () {
  77883. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77884. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77885. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77886. this.skeleton = skeleton;
  77887. this.mesh = mesh;
  77888. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77889. this.renderingGroupId = renderingGroupId;
  77890. this.color = BABYLON.Color3.White();
  77891. this._debugLines = new Array();
  77892. this._isEnabled = false;
  77893. this._scene = scene;
  77894. this.update();
  77895. this._renderFunction = this.update.bind(this);
  77896. }
  77897. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77898. get: function () {
  77899. return this._isEnabled;
  77900. },
  77901. set: function (value) {
  77902. if (this._isEnabled === value) {
  77903. return;
  77904. }
  77905. this._isEnabled = value;
  77906. if (value) {
  77907. this._scene.registerBeforeRender(this._renderFunction);
  77908. }
  77909. else {
  77910. this._scene.unregisterBeforeRender(this._renderFunction);
  77911. }
  77912. },
  77913. enumerable: true,
  77914. configurable: true
  77915. });
  77916. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77917. if (x === void 0) { x = 0; }
  77918. if (y === void 0) { y = 0; }
  77919. if (z === void 0) { z = 0; }
  77920. var tmat = BABYLON.Tmp.Matrix[0];
  77921. var parentBone = bone.getParent();
  77922. tmat.copyFrom(bone.getLocalMatrix());
  77923. if (x !== 0 || y !== 0 || z !== 0) {
  77924. var tmat2 = BABYLON.Tmp.Matrix[1];
  77925. BABYLON.Matrix.IdentityToRef(tmat2);
  77926. tmat2.m[12] = x;
  77927. tmat2.m[13] = y;
  77928. tmat2.m[14] = z;
  77929. tmat2.multiplyToRef(tmat, tmat);
  77930. }
  77931. if (parentBone) {
  77932. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77933. }
  77934. tmat.multiplyToRef(meshMat, tmat);
  77935. position.x = tmat.m[12];
  77936. position.y = tmat.m[13];
  77937. position.z = tmat.m[14];
  77938. };
  77939. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77940. var len = bones.length;
  77941. var meshPos = this.mesh.position;
  77942. for (var i = 0; i < len; i++) {
  77943. var bone = bones[i];
  77944. var points = this._debugLines[i];
  77945. if (!points) {
  77946. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77947. this._debugLines[i] = points;
  77948. }
  77949. this._getBonePosition(points[0], bone, meshMat);
  77950. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77951. points[0].subtractInPlace(meshPos);
  77952. points[1].subtractInPlace(meshPos);
  77953. }
  77954. };
  77955. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77956. var len = bones.length;
  77957. var boneNum = 0;
  77958. var meshPos = this.mesh.position;
  77959. for (var i = len - 1; i >= 0; i--) {
  77960. var childBone = bones[i];
  77961. var parentBone = childBone.getParent();
  77962. if (!parentBone) {
  77963. continue;
  77964. }
  77965. var points = this._debugLines[boneNum];
  77966. if (!points) {
  77967. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77968. this._debugLines[boneNum] = points;
  77969. }
  77970. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77971. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77972. points[0].subtractInPlace(meshPos);
  77973. points[1].subtractInPlace(meshPos);
  77974. boneNum++;
  77975. }
  77976. };
  77977. SkeletonViewer.prototype.update = function () {
  77978. if (this.autoUpdateBonesMatrices) {
  77979. this.skeleton.computeAbsoluteTransforms();
  77980. }
  77981. if (this.skeleton.bones[0].length === undefined) {
  77982. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77983. }
  77984. else {
  77985. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77986. }
  77987. if (!this._debugMesh) {
  77988. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  77989. this._debugMesh.renderingGroupId = this.renderingGroupId;
  77990. }
  77991. else {
  77992. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  77993. }
  77994. this._debugMesh.position.copyFrom(this.mesh.position);
  77995. this._debugMesh.color = this.color;
  77996. };
  77997. SkeletonViewer.prototype.dispose = function () {
  77998. if (this._debugMesh) {
  77999. this.isEnabled = false;
  78000. this._debugMesh.dispose();
  78001. this._debugMesh = null;
  78002. }
  78003. };
  78004. return SkeletonViewer;
  78005. }());
  78006. return Debug;
  78007. }());
  78008. BABYLON.Debug = Debug;
  78009. })(BABYLON || (BABYLON = {}));
  78010. //# sourceMappingURL=babylon.debugModules.js.map
  78011. var BABYLON;
  78012. (function (BABYLON) {
  78013. var RayHelper = /** @class */ (function () {
  78014. function RayHelper(ray) {
  78015. this.ray = ray;
  78016. }
  78017. RayHelper.CreateAndShow = function (ray, scene, color) {
  78018. var helper = new RayHelper(ray);
  78019. helper.show(scene, color);
  78020. return helper;
  78021. };
  78022. RayHelper.prototype.show = function (scene, color) {
  78023. if (!this._renderFunction && this.ray) {
  78024. var ray = this.ray;
  78025. this._renderFunction = this._render.bind(this);
  78026. this._scene = scene;
  78027. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  78028. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  78029. if (this._renderFunction) {
  78030. this._scene.registerBeforeRender(this._renderFunction);
  78031. }
  78032. }
  78033. if (color && this._renderLine) {
  78034. this._renderLine.color.copyFrom(color);
  78035. }
  78036. };
  78037. RayHelper.prototype.hide = function () {
  78038. if (this._renderFunction && this._scene) {
  78039. this._scene.unregisterBeforeRender(this._renderFunction);
  78040. this._scene = null;
  78041. this._renderFunction = null;
  78042. if (this._renderLine) {
  78043. this._renderLine.dispose();
  78044. this._renderLine = null;
  78045. }
  78046. this._renderPoints = [];
  78047. }
  78048. };
  78049. RayHelper.prototype._render = function () {
  78050. var ray = this.ray;
  78051. if (!ray) {
  78052. return;
  78053. }
  78054. var point = this._renderPoints[1];
  78055. var len = Math.min(ray.length, 1000000);
  78056. point.copyFrom(ray.direction);
  78057. point.scaleInPlace(len);
  78058. point.addInPlace(ray.origin);
  78059. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78060. };
  78061. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78062. this._attachedToMesh = mesh;
  78063. var ray = this.ray;
  78064. if (!ray) {
  78065. return;
  78066. }
  78067. if (!ray.direction) {
  78068. ray.direction = BABYLON.Vector3.Zero();
  78069. }
  78070. if (!ray.origin) {
  78071. ray.origin = BABYLON.Vector3.Zero();
  78072. }
  78073. if (length) {
  78074. ray.length = length;
  78075. }
  78076. if (!meshSpaceOrigin) {
  78077. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78078. }
  78079. if (!meshSpaceDirection) {
  78080. // -1 so that this will work with Mesh.lookAt
  78081. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78082. }
  78083. if (!this._meshSpaceDirection) {
  78084. this._meshSpaceDirection = meshSpaceDirection.clone();
  78085. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78086. }
  78087. else {
  78088. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78089. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78090. }
  78091. if (!this._updateToMeshFunction) {
  78092. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78093. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78094. }
  78095. this._updateToMesh();
  78096. };
  78097. RayHelper.prototype.detachFromMesh = function () {
  78098. if (this._attachedToMesh) {
  78099. if (this._updateToMeshFunction) {
  78100. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78101. }
  78102. this._attachedToMesh = null;
  78103. this._updateToMeshFunction = null;
  78104. }
  78105. };
  78106. RayHelper.prototype._updateToMesh = function () {
  78107. var ray = this.ray;
  78108. if (!this._attachedToMesh || !ray) {
  78109. return;
  78110. }
  78111. if (this._attachedToMesh._isDisposed) {
  78112. this.detachFromMesh();
  78113. return;
  78114. }
  78115. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78116. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78117. };
  78118. RayHelper.prototype.dispose = function () {
  78119. this.hide();
  78120. this.detachFromMesh();
  78121. this.ray = null;
  78122. };
  78123. return RayHelper;
  78124. }());
  78125. BABYLON.RayHelper = RayHelper;
  78126. })(BABYLON || (BABYLON = {}));
  78127. //# sourceMappingURL=babylon.rayHelper.js.map
  78128. var BABYLON;
  78129. (function (BABYLON) {
  78130. // load the inspector using require, if not present in the global namespace.
  78131. var DebugLayer = /** @class */ (function () {
  78132. function DebugLayer(scene) {
  78133. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78134. this._scene = scene;
  78135. // load inspector using require, if it doesn't exist on the global namespace.
  78136. }
  78137. /** Creates the inspector window. */
  78138. DebugLayer.prototype._createInspector = function (config) {
  78139. if (config === void 0) { config = {}; }
  78140. var popup = config.popup || false;
  78141. var initialTab = config.initialTab || 0;
  78142. var parentElement = config.parentElement || null;
  78143. if (!this._inspector) {
  78144. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78145. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78146. } // else nothing to do,; instance is already existing
  78147. };
  78148. DebugLayer.prototype.isVisible = function () {
  78149. if (!this._inspector) {
  78150. return false;
  78151. }
  78152. return true;
  78153. };
  78154. DebugLayer.prototype.hide = function () {
  78155. if (this._inspector) {
  78156. try {
  78157. this._inspector.dispose();
  78158. }
  78159. catch (e) {
  78160. // If the inspector has been removed directly from the inspector tool
  78161. }
  78162. this._inspector = null;
  78163. }
  78164. };
  78165. DebugLayer.prototype.show = function (config) {
  78166. if (config === void 0) { config = {}; }
  78167. if (typeof this.BJSINSPECTOR == 'undefined') {
  78168. // Load inspector and add it to the DOM
  78169. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78170. }
  78171. else {
  78172. // Otherwise creates the inspector
  78173. this._createInspector(config);
  78174. }
  78175. };
  78176. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78177. return DebugLayer;
  78178. }());
  78179. BABYLON.DebugLayer = DebugLayer;
  78180. })(BABYLON || (BABYLON = {}));
  78181. //# sourceMappingURL=babylon.debugLayer.js.map
  78182. var BABYLON;
  78183. (function (BABYLON) {
  78184. var BoundingBoxRenderer = /** @class */ (function () {
  78185. function BoundingBoxRenderer(scene) {
  78186. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78187. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78188. this.showBackLines = true;
  78189. this.renderList = new BABYLON.SmartArray(32);
  78190. this._vertexBuffers = {};
  78191. this._scene = scene;
  78192. }
  78193. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78194. if (this._colorShader) {
  78195. return;
  78196. }
  78197. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78198. attributes: [BABYLON.VertexBuffer.PositionKind],
  78199. uniforms: ["world", "viewProjection", "color"]
  78200. });
  78201. var engine = this._scene.getEngine();
  78202. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78203. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78204. this._createIndexBuffer();
  78205. };
  78206. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78207. var engine = this._scene.getEngine();
  78208. 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]);
  78209. };
  78210. BoundingBoxRenderer.prototype._rebuild = function () {
  78211. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78212. if (vb) {
  78213. vb._rebuild();
  78214. }
  78215. this._createIndexBuffer();
  78216. };
  78217. BoundingBoxRenderer.prototype.reset = function () {
  78218. this.renderList.reset();
  78219. };
  78220. BoundingBoxRenderer.prototype.render = function () {
  78221. if (this.renderList.length === 0) {
  78222. return;
  78223. }
  78224. this._prepareRessources();
  78225. if (!this._colorShader.isReady()) {
  78226. return;
  78227. }
  78228. var engine = this._scene.getEngine();
  78229. engine.setDepthWrite(false);
  78230. this._colorShader._preBind();
  78231. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78232. var boundingBox = this.renderList.data[boundingBoxIndex];
  78233. var min = boundingBox.minimum;
  78234. var max = boundingBox.maximum;
  78235. var diff = max.subtract(min);
  78236. var median = min.add(diff.scale(0.5));
  78237. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78238. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78239. .multiply(boundingBox.getWorldMatrix());
  78240. // VBOs
  78241. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78242. if (this.showBackLines) {
  78243. // Back
  78244. engine.setDepthFunctionToGreaterOrEqual();
  78245. this._scene.resetCachedMaterial();
  78246. this._colorShader.setColor4("color", this.backColor.toColor4());
  78247. this._colorShader.bind(worldMatrix);
  78248. // Draw order
  78249. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78250. }
  78251. // Front
  78252. engine.setDepthFunctionToLess();
  78253. this._scene.resetCachedMaterial();
  78254. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78255. this._colorShader.bind(worldMatrix);
  78256. // Draw order
  78257. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78258. }
  78259. this._colorShader.unbind();
  78260. engine.setDepthFunctionToLessOrEqual();
  78261. engine.setDepthWrite(true);
  78262. };
  78263. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78264. this._prepareRessources();
  78265. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78266. return;
  78267. }
  78268. var engine = this._scene.getEngine();
  78269. engine.setDepthWrite(false);
  78270. engine.setColorWrite(false);
  78271. this._colorShader._preBind();
  78272. var boundingBox = mesh._boundingInfo.boundingBox;
  78273. var min = boundingBox.minimum;
  78274. var max = boundingBox.maximum;
  78275. var diff = max.subtract(min);
  78276. var median = min.add(diff.scale(0.5));
  78277. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78278. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78279. .multiply(boundingBox.getWorldMatrix());
  78280. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78281. engine.setDepthFunctionToLess();
  78282. this._scene.resetCachedMaterial();
  78283. this._colorShader.bind(worldMatrix);
  78284. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78285. this._colorShader.unbind();
  78286. engine.setDepthFunctionToLessOrEqual();
  78287. engine.setDepthWrite(true);
  78288. engine.setColorWrite(true);
  78289. };
  78290. BoundingBoxRenderer.prototype.dispose = function () {
  78291. if (!this._colorShader) {
  78292. return;
  78293. }
  78294. this.renderList.dispose();
  78295. this._colorShader.dispose();
  78296. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78297. if (buffer) {
  78298. buffer.dispose();
  78299. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78300. }
  78301. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78302. };
  78303. return BoundingBoxRenderer;
  78304. }());
  78305. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78306. })(BABYLON || (BABYLON = {}));
  78307. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78308. var BABYLON;
  78309. (function (BABYLON) {
  78310. var MorphTarget = /** @class */ (function () {
  78311. function MorphTarget(name, influence) {
  78312. if (influence === void 0) { influence = 0; }
  78313. this.name = name;
  78314. this.animations = new Array();
  78315. this._positions = null;
  78316. this._normals = null;
  78317. this._tangents = null;
  78318. this.onInfluenceChanged = new BABYLON.Observable();
  78319. this.influence = influence;
  78320. }
  78321. Object.defineProperty(MorphTarget.prototype, "influence", {
  78322. get: function () {
  78323. return this._influence;
  78324. },
  78325. set: function (influence) {
  78326. if (this._influence === influence) {
  78327. return;
  78328. }
  78329. var previous = this._influence;
  78330. this._influence = influence;
  78331. if (this.onInfluenceChanged.hasObservers) {
  78332. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78333. }
  78334. },
  78335. enumerable: true,
  78336. configurable: true
  78337. });
  78338. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78339. get: function () {
  78340. return !!this._positions;
  78341. },
  78342. enumerable: true,
  78343. configurable: true
  78344. });
  78345. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78346. get: function () {
  78347. return !!this._normals;
  78348. },
  78349. enumerable: true,
  78350. configurable: true
  78351. });
  78352. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78353. get: function () {
  78354. return !!this._tangents;
  78355. },
  78356. enumerable: true,
  78357. configurable: true
  78358. });
  78359. MorphTarget.prototype.setPositions = function (data) {
  78360. this._positions = data;
  78361. };
  78362. MorphTarget.prototype.getPositions = function () {
  78363. return this._positions;
  78364. };
  78365. MorphTarget.prototype.setNormals = function (data) {
  78366. this._normals = data;
  78367. };
  78368. MorphTarget.prototype.getNormals = function () {
  78369. return this._normals;
  78370. };
  78371. MorphTarget.prototype.setTangents = function (data) {
  78372. this._tangents = data;
  78373. };
  78374. MorphTarget.prototype.getTangents = function () {
  78375. return this._tangents;
  78376. };
  78377. /**
  78378. * Serializes the current target into a Serialization object.
  78379. * Returns the serialized object.
  78380. */
  78381. MorphTarget.prototype.serialize = function () {
  78382. var serializationObject = {};
  78383. serializationObject.name = this.name;
  78384. serializationObject.influence = this.influence;
  78385. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78386. if (this.hasNormals) {
  78387. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78388. }
  78389. if (this.hasTangents) {
  78390. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78391. }
  78392. // Animations
  78393. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78394. return serializationObject;
  78395. };
  78396. // Statics
  78397. MorphTarget.Parse = function (serializationObject) {
  78398. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78399. result.setPositions(serializationObject.positions);
  78400. if (serializationObject.normals) {
  78401. result.setNormals(serializationObject.normals);
  78402. }
  78403. if (serializationObject.tangents) {
  78404. result.setTangents(serializationObject.tangents);
  78405. }
  78406. // Animations
  78407. if (serializationObject.animations) {
  78408. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78409. var parsedAnimation = serializationObject.animations[animationIndex];
  78410. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78411. }
  78412. }
  78413. return result;
  78414. };
  78415. MorphTarget.FromMesh = function (mesh, name, influence) {
  78416. if (!name) {
  78417. name = mesh.name;
  78418. }
  78419. var result = new MorphTarget(name, influence);
  78420. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78421. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78422. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78423. }
  78424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78425. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78426. }
  78427. return result;
  78428. };
  78429. return MorphTarget;
  78430. }());
  78431. BABYLON.MorphTarget = MorphTarget;
  78432. })(BABYLON || (BABYLON = {}));
  78433. //# sourceMappingURL=babylon.morphTarget.js.map
  78434. var BABYLON;
  78435. (function (BABYLON) {
  78436. var MorphTargetManager = /** @class */ (function () {
  78437. function MorphTargetManager(scene) {
  78438. if (scene === void 0) { scene = null; }
  78439. this._targets = new Array();
  78440. this._targetObservable = new Array();
  78441. this._activeTargets = new BABYLON.SmartArray(16);
  78442. this._supportsNormals = false;
  78443. this._supportsTangents = false;
  78444. this._vertexCount = 0;
  78445. this._uniqueId = 0;
  78446. this._tempInfluences = new Array();
  78447. if (!scene) {
  78448. scene = BABYLON.Engine.LastCreatedScene;
  78449. }
  78450. this._scene = scene;
  78451. if (this._scene) {
  78452. this._scene.morphTargetManagers.push(this);
  78453. this._uniqueId = this._scene.getUniqueId();
  78454. }
  78455. }
  78456. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78457. get: function () {
  78458. return this._uniqueId;
  78459. },
  78460. enumerable: true,
  78461. configurable: true
  78462. });
  78463. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78464. get: function () {
  78465. return this._vertexCount;
  78466. },
  78467. enumerable: true,
  78468. configurable: true
  78469. });
  78470. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78471. get: function () {
  78472. return this._supportsNormals;
  78473. },
  78474. enumerable: true,
  78475. configurable: true
  78476. });
  78477. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78478. get: function () {
  78479. return this._supportsTangents;
  78480. },
  78481. enumerable: true,
  78482. configurable: true
  78483. });
  78484. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78485. get: function () {
  78486. return this._targets.length;
  78487. },
  78488. enumerable: true,
  78489. configurable: true
  78490. });
  78491. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78492. get: function () {
  78493. return this._activeTargets.length;
  78494. },
  78495. enumerable: true,
  78496. configurable: true
  78497. });
  78498. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78499. get: function () {
  78500. return this._influences;
  78501. },
  78502. enumerable: true,
  78503. configurable: true
  78504. });
  78505. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78506. return this._activeTargets.data[index];
  78507. };
  78508. MorphTargetManager.prototype.getTarget = function (index) {
  78509. return this._targets[index];
  78510. };
  78511. MorphTargetManager.prototype.addTarget = function (target) {
  78512. var _this = this;
  78513. this._targets.push(target);
  78514. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78515. _this._syncActiveTargets(needUpdate);
  78516. }));
  78517. this._syncActiveTargets(true);
  78518. };
  78519. MorphTargetManager.prototype.removeTarget = function (target) {
  78520. var index = this._targets.indexOf(target);
  78521. if (index >= 0) {
  78522. this._targets.splice(index, 1);
  78523. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78524. this._syncActiveTargets(true);
  78525. }
  78526. };
  78527. /**
  78528. * Serializes the current manager into a Serialization object.
  78529. * Returns the serialized object.
  78530. */
  78531. MorphTargetManager.prototype.serialize = function () {
  78532. var serializationObject = {};
  78533. serializationObject.id = this.uniqueId;
  78534. serializationObject.targets = [];
  78535. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78536. var target = _a[_i];
  78537. serializationObject.targets.push(target.serialize());
  78538. }
  78539. return serializationObject;
  78540. };
  78541. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78542. var influenceCount = 0;
  78543. this._activeTargets.reset();
  78544. this._supportsNormals = true;
  78545. this._supportsTangents = true;
  78546. this._vertexCount = 0;
  78547. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78548. var target = _a[_i];
  78549. this._activeTargets.push(target);
  78550. this._tempInfluences[influenceCount++] = target.influence;
  78551. var positions = target.getPositions();
  78552. if (positions) {
  78553. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78554. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78555. var vertexCount = positions.length / 3;
  78556. if (this._vertexCount === 0) {
  78557. this._vertexCount = vertexCount;
  78558. }
  78559. else if (this._vertexCount !== vertexCount) {
  78560. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78561. return;
  78562. }
  78563. }
  78564. }
  78565. if (!this._influences || this._influences.length !== influenceCount) {
  78566. this._influences = new Float32Array(influenceCount);
  78567. }
  78568. for (var index = 0; index < influenceCount; index++) {
  78569. this._influences[index] = this._tempInfluences[index];
  78570. }
  78571. if (needUpdate && this._scene) {
  78572. // Flag meshes as dirty to resync with the active targets
  78573. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78574. var mesh = _c[_b];
  78575. if (mesh.morphTargetManager === this) {
  78576. mesh._syncGeometryWithMorphTargetManager();
  78577. }
  78578. }
  78579. }
  78580. };
  78581. // Statics
  78582. MorphTargetManager.Parse = function (serializationObject, scene) {
  78583. var result = new MorphTargetManager(scene);
  78584. result._uniqueId = serializationObject.id;
  78585. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78586. var targetData = _a[_i];
  78587. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78588. }
  78589. return result;
  78590. };
  78591. return MorphTargetManager;
  78592. }());
  78593. BABYLON.MorphTargetManager = MorphTargetManager;
  78594. })(BABYLON || (BABYLON = {}));
  78595. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78596. var BABYLON;
  78597. (function (BABYLON) {
  78598. var Octree = /** @class */ (function () {
  78599. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78600. if (maxDepth === void 0) { maxDepth = 2; }
  78601. this.maxDepth = maxDepth;
  78602. this.dynamicContent = new Array();
  78603. this._maxBlockCapacity = maxBlockCapacity || 64;
  78604. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78605. this._creationFunc = creationFunc;
  78606. }
  78607. // Methods
  78608. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78609. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78610. };
  78611. Octree.prototype.addMesh = function (entry) {
  78612. for (var index = 0; index < this.blocks.length; index++) {
  78613. var block = this.blocks[index];
  78614. block.addEntry(entry);
  78615. }
  78616. };
  78617. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78618. this._selectionContent.reset();
  78619. for (var index = 0; index < this.blocks.length; index++) {
  78620. var block = this.blocks[index];
  78621. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78622. }
  78623. if (allowDuplicate) {
  78624. this._selectionContent.concat(this.dynamicContent);
  78625. }
  78626. else {
  78627. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78628. }
  78629. return this._selectionContent;
  78630. };
  78631. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78632. this._selectionContent.reset();
  78633. for (var index = 0; index < this.blocks.length; index++) {
  78634. var block = this.blocks[index];
  78635. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78636. }
  78637. if (allowDuplicate) {
  78638. this._selectionContent.concat(this.dynamicContent);
  78639. }
  78640. else {
  78641. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78642. }
  78643. return this._selectionContent;
  78644. };
  78645. Octree.prototype.intersectsRay = function (ray) {
  78646. this._selectionContent.reset();
  78647. for (var index = 0; index < this.blocks.length; index++) {
  78648. var block = this.blocks[index];
  78649. block.intersectsRay(ray, this._selectionContent);
  78650. }
  78651. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78652. return this._selectionContent;
  78653. };
  78654. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78655. target.blocks = new Array();
  78656. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78657. // Segmenting space
  78658. for (var x = 0; x < 2; x++) {
  78659. for (var y = 0; y < 2; y++) {
  78660. for (var z = 0; z < 2; z++) {
  78661. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78662. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78663. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78664. block.addEntries(entries);
  78665. target.blocks.push(block);
  78666. }
  78667. }
  78668. }
  78669. };
  78670. Octree.CreationFuncForMeshes = function (entry, block) {
  78671. var boundingInfo = entry.getBoundingInfo();
  78672. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78673. block.entries.push(entry);
  78674. }
  78675. };
  78676. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78677. var boundingInfo = entry.getBoundingInfo();
  78678. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78679. block.entries.push(entry);
  78680. }
  78681. };
  78682. return Octree;
  78683. }());
  78684. BABYLON.Octree = Octree;
  78685. })(BABYLON || (BABYLON = {}));
  78686. //# sourceMappingURL=babylon.octree.js.map
  78687. var BABYLON;
  78688. (function (BABYLON) {
  78689. var OctreeBlock = /** @class */ (function () {
  78690. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78691. this.entries = new Array();
  78692. this._boundingVectors = new Array();
  78693. this._capacity = capacity;
  78694. this._depth = depth;
  78695. this._maxDepth = maxDepth;
  78696. this._creationFunc = creationFunc;
  78697. this._minPoint = minPoint;
  78698. this._maxPoint = maxPoint;
  78699. this._boundingVectors.push(minPoint.clone());
  78700. this._boundingVectors.push(maxPoint.clone());
  78701. this._boundingVectors.push(minPoint.clone());
  78702. this._boundingVectors[2].x = maxPoint.x;
  78703. this._boundingVectors.push(minPoint.clone());
  78704. this._boundingVectors[3].y = maxPoint.y;
  78705. this._boundingVectors.push(minPoint.clone());
  78706. this._boundingVectors[4].z = maxPoint.z;
  78707. this._boundingVectors.push(maxPoint.clone());
  78708. this._boundingVectors[5].z = minPoint.z;
  78709. this._boundingVectors.push(maxPoint.clone());
  78710. this._boundingVectors[6].x = minPoint.x;
  78711. this._boundingVectors.push(maxPoint.clone());
  78712. this._boundingVectors[7].y = minPoint.y;
  78713. }
  78714. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78715. // Property
  78716. get: function () {
  78717. return this._capacity;
  78718. },
  78719. enumerable: true,
  78720. configurable: true
  78721. });
  78722. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78723. get: function () {
  78724. return this._minPoint;
  78725. },
  78726. enumerable: true,
  78727. configurable: true
  78728. });
  78729. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78730. get: function () {
  78731. return this._maxPoint;
  78732. },
  78733. enumerable: true,
  78734. configurable: true
  78735. });
  78736. // Methods
  78737. OctreeBlock.prototype.addEntry = function (entry) {
  78738. if (this.blocks) {
  78739. for (var index = 0; index < this.blocks.length; index++) {
  78740. var block = this.blocks[index];
  78741. block.addEntry(entry);
  78742. }
  78743. return;
  78744. }
  78745. this._creationFunc(entry, this);
  78746. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78747. this.createInnerBlocks();
  78748. }
  78749. };
  78750. OctreeBlock.prototype.addEntries = function (entries) {
  78751. for (var index = 0; index < entries.length; index++) {
  78752. var mesh = entries[index];
  78753. this.addEntry(mesh);
  78754. }
  78755. };
  78756. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78757. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78758. if (this.blocks) {
  78759. for (var index = 0; index < this.blocks.length; index++) {
  78760. var block = this.blocks[index];
  78761. block.select(frustumPlanes, selection, allowDuplicate);
  78762. }
  78763. return;
  78764. }
  78765. if (allowDuplicate) {
  78766. selection.concat(this.entries);
  78767. }
  78768. else {
  78769. selection.concatWithNoDuplicate(this.entries);
  78770. }
  78771. }
  78772. };
  78773. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78774. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78775. if (this.blocks) {
  78776. for (var index = 0; index < this.blocks.length; index++) {
  78777. var block = this.blocks[index];
  78778. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78779. }
  78780. return;
  78781. }
  78782. if (allowDuplicate) {
  78783. selection.concat(this.entries);
  78784. }
  78785. else {
  78786. selection.concatWithNoDuplicate(this.entries);
  78787. }
  78788. }
  78789. };
  78790. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78791. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78792. if (this.blocks) {
  78793. for (var index = 0; index < this.blocks.length; index++) {
  78794. var block = this.blocks[index];
  78795. block.intersectsRay(ray, selection);
  78796. }
  78797. return;
  78798. }
  78799. selection.concatWithNoDuplicate(this.entries);
  78800. }
  78801. };
  78802. OctreeBlock.prototype.createInnerBlocks = function () {
  78803. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78804. };
  78805. return OctreeBlock;
  78806. }());
  78807. BABYLON.OctreeBlock = OctreeBlock;
  78808. })(BABYLON || (BABYLON = {}));
  78809. //# sourceMappingURL=babylon.octreeBlock.js.map
  78810. var BABYLON;
  78811. (function (BABYLON) {
  78812. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78813. __extends(VRDistortionCorrectionPostProcess, _super);
  78814. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78815. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78816. 'LensCenter',
  78817. 'Scale',
  78818. 'ScaleIn',
  78819. 'HmdWarpParam'
  78820. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78821. _this._isRightEye = isRightEye;
  78822. _this._distortionFactors = vrMetrics.distortionK;
  78823. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78824. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78825. _this.adaptScaleToCurrentViewport = true;
  78826. _this.onSizeChangedObservable.add(function () {
  78827. _this.aspectRatio = _this.width * .5 / _this.height;
  78828. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78829. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78830. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78831. });
  78832. _this.onApplyObservable.add(function (effect) {
  78833. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78834. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78835. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78836. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78837. });
  78838. return _this;
  78839. }
  78840. return VRDistortionCorrectionPostProcess;
  78841. }(BABYLON.PostProcess));
  78842. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78843. })(BABYLON || (BABYLON = {}));
  78844. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78845. var BABYLON;
  78846. (function (BABYLON) {
  78847. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78848. __extends(AnaglyphPostProcess, _super);
  78849. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78850. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78851. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78852. _this.onApplyObservable.add(function (effect) {
  78853. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78854. });
  78855. return _this;
  78856. }
  78857. return AnaglyphPostProcess;
  78858. }(BABYLON.PostProcess));
  78859. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78860. })(BABYLON || (BABYLON = {}));
  78861. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78862. var BABYLON;
  78863. (function (BABYLON) {
  78864. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78865. __extends(StereoscopicInterlacePostProcess, _super);
  78866. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78867. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78868. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78869. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78870. _this.onSizeChangedObservable.add(function () {
  78871. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78872. });
  78873. _this.onApplyObservable.add(function (effect) {
  78874. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78875. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78876. });
  78877. return _this;
  78878. }
  78879. return StereoscopicInterlacePostProcess;
  78880. }(BABYLON.PostProcess));
  78881. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78882. })(BABYLON || (BABYLON = {}));
  78883. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78884. var BABYLON;
  78885. (function (BABYLON) {
  78886. /**
  78887. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78888. * Screen rotation is taken into account.
  78889. */
  78890. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78891. function FreeCameraDeviceOrientationInput() {
  78892. var _this = this;
  78893. this._screenOrientationAngle = 0;
  78894. this._screenQuaternion = new BABYLON.Quaternion();
  78895. this._alpha = 0;
  78896. this._beta = 0;
  78897. this._gamma = 0;
  78898. this._orientationChanged = function () {
  78899. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78900. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78901. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78902. };
  78903. this._deviceOrientation = function (evt) {
  78904. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78905. _this._beta = evt.beta !== null ? evt.beta : 0;
  78906. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78907. };
  78908. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78909. this._orientationChanged();
  78910. }
  78911. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78912. get: function () {
  78913. return this._camera;
  78914. },
  78915. set: function (camera) {
  78916. this._camera = camera;
  78917. if (this._camera != null && !this._camera.rotationQuaternion) {
  78918. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78919. }
  78920. },
  78921. enumerable: true,
  78922. configurable: true
  78923. });
  78924. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78925. window.addEventListener("orientationchange", this._orientationChanged);
  78926. window.addEventListener("deviceorientation", this._deviceOrientation);
  78927. //In certain cases, the attach control is called AFTER orientation was changed,
  78928. //So this is needed.
  78929. this._orientationChanged();
  78930. };
  78931. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78932. window.removeEventListener("orientationchange", this._orientationChanged);
  78933. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78934. };
  78935. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78936. //if no device orientation provided, don't update the rotation.
  78937. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78938. if (!this._alpha)
  78939. return;
  78940. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78941. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78942. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78943. //Mirror on XY Plane
  78944. this._camera.rotationQuaternion.z *= -1;
  78945. this._camera.rotationQuaternion.w *= -1;
  78946. };
  78947. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78948. return "FreeCameraDeviceOrientationInput";
  78949. };
  78950. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78951. return "deviceOrientation";
  78952. };
  78953. return FreeCameraDeviceOrientationInput;
  78954. }());
  78955. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78956. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78957. })(BABYLON || (BABYLON = {}));
  78958. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78959. var BABYLON;
  78960. (function (BABYLON) {
  78961. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78962. function ArcRotateCameraVRDeviceOrientationInput() {
  78963. this.alphaCorrection = 1;
  78964. this.betaCorrection = 1;
  78965. this.gammaCorrection = 1;
  78966. this._alpha = 0;
  78967. this._gamma = 0;
  78968. this._dirty = false;
  78969. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78970. }
  78971. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78972. this.camera.attachControl(element, noPreventDefault);
  78973. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78974. };
  78975. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  78976. if (evt.alpha !== null) {
  78977. this._alpha = +evt.alpha | 0;
  78978. }
  78979. if (evt.gamma !== null) {
  78980. this._gamma = +evt.gamma | 0;
  78981. }
  78982. this._dirty = true;
  78983. };
  78984. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  78985. if (this._dirty) {
  78986. this._dirty = false;
  78987. if (this._gamma < 0) {
  78988. this._gamma = 180 + this._gamma;
  78989. }
  78990. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  78991. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  78992. }
  78993. };
  78994. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  78995. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  78996. };
  78997. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  78998. return "ArcRotateCameraVRDeviceOrientationInput";
  78999. };
  79000. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  79001. return "VRDeviceOrientation";
  79002. };
  79003. return ArcRotateCameraVRDeviceOrientationInput;
  79004. }());
  79005. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  79006. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  79007. })(BABYLON || (BABYLON = {}));
  79008. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  79009. var BABYLON;
  79010. (function (BABYLON) {
  79011. var VRCameraMetrics = /** @class */ (function () {
  79012. function VRCameraMetrics() {
  79013. this.compensateDistortion = true;
  79014. }
  79015. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  79016. get: function () {
  79017. return this.hResolution / (2 * this.vResolution);
  79018. },
  79019. enumerable: true,
  79020. configurable: true
  79021. });
  79022. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  79023. get: function () {
  79024. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  79025. },
  79026. enumerable: true,
  79027. configurable: true
  79028. });
  79029. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  79030. get: function () {
  79031. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79032. var h = (4 * meters) / this.hScreenSize;
  79033. return BABYLON.Matrix.Translation(h, 0, 0);
  79034. },
  79035. enumerable: true,
  79036. configurable: true
  79037. });
  79038. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  79039. get: function () {
  79040. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  79041. var h = (4 * meters) / this.hScreenSize;
  79042. return BABYLON.Matrix.Translation(-h, 0, 0);
  79043. },
  79044. enumerable: true,
  79045. configurable: true
  79046. });
  79047. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  79048. get: function () {
  79049. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  79050. },
  79051. enumerable: true,
  79052. configurable: true
  79053. });
  79054. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79055. get: function () {
  79056. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79057. },
  79058. enumerable: true,
  79059. configurable: true
  79060. });
  79061. VRCameraMetrics.GetDefault = function () {
  79062. var result = new VRCameraMetrics();
  79063. result.hResolution = 1280;
  79064. result.vResolution = 800;
  79065. result.hScreenSize = 0.149759993;
  79066. result.vScreenSize = 0.0935999975;
  79067. result.vScreenCenter = 0.0467999987;
  79068. result.eyeToScreenDistance = 0.0410000011;
  79069. result.lensSeparationDistance = 0.0635000020;
  79070. result.interpupillaryDistance = 0.0640000030;
  79071. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79072. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79073. result.postProcessScaleFactor = 1.714605507808412;
  79074. result.lensCenterOffset = 0.151976421;
  79075. return result;
  79076. };
  79077. return VRCameraMetrics;
  79078. }());
  79079. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79080. })(BABYLON || (BABYLON = {}));
  79081. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79082. var BABYLON;
  79083. (function (BABYLON) {
  79084. /**
  79085. * This represents a WebVR camera.
  79086. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79087. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79088. */
  79089. var WebVRFreeCamera = /** @class */ (function (_super) {
  79090. __extends(WebVRFreeCamera, _super);
  79091. /**
  79092. * Instantiates a WebVRFreeCamera.
  79093. * @param name The name of the WebVRFreeCamera
  79094. * @param position The starting anchor position for the camera
  79095. * @param scene The scene the camera belongs to
  79096. * @param webVROptions a set of customizable options for the webVRCamera
  79097. */
  79098. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79099. if (webVROptions === void 0) { webVROptions = {}; }
  79100. var _this = _super.call(this, name, position, scene) || this;
  79101. _this.webVROptions = webVROptions;
  79102. /**
  79103. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79104. */
  79105. _this._vrDevice = null;
  79106. /**
  79107. * The rawPose of the vrDevice.
  79108. */
  79109. _this.rawPose = null;
  79110. _this._specsVersion = "1.1";
  79111. _this._attached = false;
  79112. _this._descendants = [];
  79113. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79114. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79115. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79116. _this._standingMatrix = null;
  79117. /**
  79118. * Represents device position in babylon space.
  79119. */
  79120. _this.devicePosition = BABYLON.Vector3.Zero();
  79121. /**
  79122. * Represents device rotation in babylon space.
  79123. */
  79124. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79125. /**
  79126. * The scale of the device to be used when translating from device space to babylon space.
  79127. */
  79128. _this.deviceScaleFactor = 1;
  79129. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79130. _this._worldToDevice = BABYLON.Matrix.Identity();
  79131. /**
  79132. * References to the webVR controllers for the vrDevice.
  79133. */
  79134. _this.controllers = [];
  79135. /**
  79136. * Emits an event when a controller is attached.
  79137. */
  79138. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79139. /**
  79140. * Emits an event when a controller's mesh has been loaded;
  79141. */
  79142. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79143. /**
  79144. * If the rig cameras be used as parent instead of this camera.
  79145. */
  79146. _this.rigParenting = true;
  79147. _this._defaultHeight = undefined;
  79148. _this._workingVector = BABYLON.Vector3.Zero();
  79149. _this._oneVector = BABYLON.Vector3.One();
  79150. _this._workingMatrix = BABYLON.Matrix.Identity();
  79151. _this._cache.position = BABYLON.Vector3.Zero();
  79152. if (webVROptions.defaultHeight) {
  79153. _this._defaultHeight = webVROptions.defaultHeight;
  79154. _this.position.y = _this._defaultHeight;
  79155. }
  79156. _this.minZ = 0.1;
  79157. //legacy support - the compensation boolean was removed.
  79158. if (arguments.length === 5) {
  79159. _this.webVROptions = arguments[4];
  79160. }
  79161. // default webVR options
  79162. if (_this.webVROptions.trackPosition == undefined) {
  79163. _this.webVROptions.trackPosition = true;
  79164. }
  79165. if (_this.webVROptions.controllerMeshes == undefined) {
  79166. _this.webVROptions.controllerMeshes = true;
  79167. }
  79168. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79169. _this.webVROptions.defaultLightingOnControllers = true;
  79170. }
  79171. _this.rotationQuaternion = new BABYLON.Quaternion();
  79172. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79173. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79174. }
  79175. //enable VR
  79176. var engine = _this.getEngine();
  79177. _this._onVREnabled = function (success) { if (success) {
  79178. _this.initControllers();
  79179. } };
  79180. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79181. engine.initWebVR().add(function (event) {
  79182. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79183. return;
  79184. }
  79185. _this._vrDevice = event.vrDisplay;
  79186. //reset the rig parameters.
  79187. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79188. if (_this._attached) {
  79189. _this.getEngine().enableVR();
  79190. }
  79191. });
  79192. if (typeof (VRFrameData) !== "undefined")
  79193. _this._frameData = new VRFrameData();
  79194. /**
  79195. * The idea behind the following lines:
  79196. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79197. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79198. * the second will not show it correctly.
  79199. *
  79200. * To solve this - each object that has the camera as parent will be added to a protected array.
  79201. * When the rig camera renders, it will take this array and set all of those to be its children.
  79202. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79203. * Amazing!
  79204. */
  79205. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79206. if (camera.parent === _this && _this.rigParenting) {
  79207. _this._descendants = _this.getDescendants(true, function (n) {
  79208. // don't take the cameras or the controllers!
  79209. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79210. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79211. return !isController && !isRigCamera;
  79212. });
  79213. _this._descendants.forEach(function (node) {
  79214. node.parent = camera;
  79215. });
  79216. }
  79217. });
  79218. scene.onAfterCameraRenderObservable.add(function (camera) {
  79219. if (camera.parent === _this && _this.rigParenting) {
  79220. _this._descendants.forEach(function (node) {
  79221. node.parent = _this;
  79222. });
  79223. }
  79224. });
  79225. return _this;
  79226. }
  79227. /**
  79228. * Gets the device distance from the ground in meters.
  79229. * @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.
  79230. */
  79231. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79232. if (this._standingMatrix) {
  79233. // Add standing matrix offset to get real offset from ground in room
  79234. this._standingMatrix.getTranslationToRef(this._workingVector);
  79235. return this._deviceRoomPosition.y + this._workingVector.y;
  79236. }
  79237. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79238. return this._defaultHeight || 0;
  79239. };
  79240. /**
  79241. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79242. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79243. */
  79244. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79245. var _this = this;
  79246. if (callback === void 0) { callback = function (bool) { }; }
  79247. // Use standing matrix if available
  79248. this.getEngine().initWebVRAsync().then(function (result) {
  79249. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79250. callback(false);
  79251. }
  79252. else {
  79253. _this._standingMatrix = new BABYLON.Matrix();
  79254. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79255. if (!_this.getScene().useRightHandedSystem) {
  79256. [2, 6, 8, 9, 14].forEach(function (num) {
  79257. if (_this._standingMatrix) {
  79258. _this._standingMatrix.m[num] *= -1;
  79259. }
  79260. });
  79261. }
  79262. callback(true);
  79263. }
  79264. });
  79265. };
  79266. /**
  79267. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79268. * @returns A promise with a boolean set to if the standing matrix is supported.
  79269. */
  79270. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79271. var _this = this;
  79272. return new Promise(function (res, rej) {
  79273. _this.useStandingMatrix(function (supported) {
  79274. res(supported);
  79275. });
  79276. });
  79277. };
  79278. /**
  79279. * Disposes the camera
  79280. */
  79281. WebVRFreeCamera.prototype.dispose = function () {
  79282. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79283. _super.prototype.dispose.call(this);
  79284. };
  79285. /**
  79286. * Gets a vrController by name.
  79287. * @param name The name of the controller to retreive
  79288. * @returns the controller matching the name specified or null if not found
  79289. */
  79290. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79291. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79292. var gp = _a[_i];
  79293. if (gp.hand === name) {
  79294. return gp;
  79295. }
  79296. }
  79297. return null;
  79298. };
  79299. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79300. /**
  79301. * The controller corrisponding to the users left hand.
  79302. */
  79303. get: function () {
  79304. if (!this._leftController) {
  79305. this._leftController = this.getControllerByName("left");
  79306. }
  79307. return this._leftController;
  79308. },
  79309. enumerable: true,
  79310. configurable: true
  79311. });
  79312. ;
  79313. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79314. /**
  79315. * The controller corrisponding to the users right hand.
  79316. */
  79317. get: function () {
  79318. if (!this._rightController) {
  79319. this._rightController = this.getControllerByName("right");
  79320. }
  79321. return this._rightController;
  79322. },
  79323. enumerable: true,
  79324. configurable: true
  79325. });
  79326. ;
  79327. /**
  79328. * Casts a ray forward from the vrCamera's gaze.
  79329. * @param length Length of the ray (default: 100)
  79330. * @returns the ray corrisponding to the gaze
  79331. */
  79332. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79333. if (length === void 0) { length = 100; }
  79334. if (this.leftCamera) {
  79335. // Use left eye to avoid computation to compute center on every call
  79336. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79337. }
  79338. else {
  79339. return _super.prototype.getForwardRay.call(this, length);
  79340. }
  79341. };
  79342. /**
  79343. * Updates the camera based on device's frame data
  79344. */
  79345. WebVRFreeCamera.prototype._checkInputs = function () {
  79346. if (this._vrDevice && this._vrDevice.isPresenting) {
  79347. this._vrDevice.getFrameData(this._frameData);
  79348. this.updateFromDevice(this._frameData.pose);
  79349. }
  79350. _super.prototype._checkInputs.call(this);
  79351. };
  79352. /**
  79353. * Updates the poseControlled values based on the input device pose.
  79354. * @param poseData Pose coming from the device
  79355. */
  79356. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79357. if (poseData && poseData.orientation) {
  79358. this.rawPose = poseData;
  79359. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79360. if (this.getScene().useRightHandedSystem) {
  79361. this._deviceRoomRotationQuaternion.z *= -1;
  79362. this._deviceRoomRotationQuaternion.w *= -1;
  79363. }
  79364. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79365. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79366. if (this.getScene().useRightHandedSystem) {
  79367. this._deviceRoomPosition.z *= -1;
  79368. }
  79369. }
  79370. }
  79371. };
  79372. /**
  79373. * WebVR's attach control will start broadcasting frames to the device.
  79374. * Note that in certain browsers (chrome for example) this function must be called
  79375. * within a user-interaction callback. Example:
  79376. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79377. *
  79378. * @param element html element to attach the vrDevice to
  79379. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79380. */
  79381. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79382. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79383. this._attached = true;
  79384. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79385. if (this._vrDevice) {
  79386. this.getEngine().enableVR();
  79387. }
  79388. };
  79389. /**
  79390. * Detaches the camera from the html element and disables VR
  79391. *
  79392. * @param element html element to detach from
  79393. */
  79394. WebVRFreeCamera.prototype.detachControl = function (element) {
  79395. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79396. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79397. _super.prototype.detachControl.call(this, element);
  79398. this._attached = false;
  79399. this.getEngine().disableVR();
  79400. };
  79401. /**
  79402. * @returns the name of this class
  79403. */
  79404. WebVRFreeCamera.prototype.getClassName = function () {
  79405. return "WebVRFreeCamera";
  79406. };
  79407. /**
  79408. * Calls resetPose on the vrDisplay
  79409. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79410. */
  79411. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79412. //uses the vrDisplay's "resetPose()".
  79413. //pitch and roll won't be affected.
  79414. this._vrDevice.resetPose();
  79415. };
  79416. /**
  79417. * Updates the rig cameras (left and right eye)
  79418. */
  79419. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79420. var camLeft = this._rigCameras[0];
  79421. var camRight = this._rigCameras[1];
  79422. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79423. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79424. camLeft.position.copyFrom(this._deviceRoomPosition);
  79425. camRight.position.copyFrom(this._deviceRoomPosition);
  79426. };
  79427. /**
  79428. * Updates the cached values of the camera
  79429. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79430. */
  79431. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79432. var _this = this;
  79433. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79434. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79435. if (!this.updateCacheCalled) {
  79436. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79437. this.updateCacheCalled = true;
  79438. this.update();
  79439. }
  79440. // Set working vector to the device position in room space rotated by the new rotation
  79441. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79442. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79443. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79444. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79445. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79446. // Add translation from anchor position
  79447. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79448. this._workingVector.addInPlace(this.position);
  79449. this._workingVector.subtractInPlace(this._cache.position);
  79450. this._deviceToWorld.setTranslation(this._workingVector);
  79451. // Set an inverted matrix to be used when updating the camera
  79452. this._deviceToWorld.invertToRef(this._worldToDevice);
  79453. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79454. this.controllers.forEach(function (controller) {
  79455. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  79456. controller.update();
  79457. });
  79458. }
  79459. if (!ignoreParentClass) {
  79460. _super.prototype._updateCache.call(this);
  79461. }
  79462. this.updateCacheCalled = false;
  79463. };
  79464. /**
  79465. * Updates the current device position and rotation in the babylon world
  79466. */
  79467. WebVRFreeCamera.prototype.update = function () {
  79468. // Get current device position in babylon world
  79469. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79470. // Get current device rotation in babylon world
  79471. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79472. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79473. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79474. _super.prototype.update.call(this);
  79475. };
  79476. /**
  79477. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79478. * @returns an identity matrix
  79479. */
  79480. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79481. return BABYLON.Matrix.Identity();
  79482. };
  79483. /**
  79484. * This function is called by the two RIG cameras.
  79485. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79486. */
  79487. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79488. var _this = this;
  79489. // Update the parent camera prior to using a child camera to avoid desynchronization
  79490. var parentCamera = this._cameraRigParams["parentCamera"];
  79491. parentCamera._updateCache();
  79492. //WebVR 1.1
  79493. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79494. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79495. if (!this.getScene().useRightHandedSystem) {
  79496. [2, 6, 8, 9, 14].forEach(function (num) {
  79497. _this._webvrViewMatrix.m[num] *= -1;
  79498. });
  79499. }
  79500. // update the camera rotation matrix
  79501. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79502. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79503. // Computing target and final matrix
  79504. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79505. // should the view matrix be updated with scale and position offset?
  79506. if (parentCamera.deviceScaleFactor !== 1) {
  79507. this._webvrViewMatrix.invert();
  79508. // scale the position, if set
  79509. if (parentCamera.deviceScaleFactor) {
  79510. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79511. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79512. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79513. }
  79514. this._webvrViewMatrix.invert();
  79515. }
  79516. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79517. return this._webvrViewMatrix;
  79518. };
  79519. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79520. var _this = this;
  79521. var parentCamera = this.parent;
  79522. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79523. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79524. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79525. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79526. //babylon compatible matrix
  79527. if (!this.getScene().useRightHandedSystem) {
  79528. [8, 9, 10, 11].forEach(function (num) {
  79529. _this._projectionMatrix.m[num] *= -1;
  79530. });
  79531. }
  79532. return this._projectionMatrix;
  79533. };
  79534. /**
  79535. * Initializes the controllers and their meshes
  79536. */
  79537. WebVRFreeCamera.prototype.initControllers = function () {
  79538. var _this = this;
  79539. this.controllers = [];
  79540. var manager = this.getScene().gamepadManager;
  79541. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79542. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79543. var webVrController = gamepad;
  79544. if (webVrController.defaultModel) {
  79545. webVrController.defaultModel.setEnabled(false);
  79546. }
  79547. if (webVrController.hand === "right") {
  79548. _this._rightController = null;
  79549. }
  79550. if (webVrController.hand === "left") {
  79551. _this._leftController = null;
  79552. }
  79553. var controllerIndex = _this.controllers.indexOf(webVrController);
  79554. if (controllerIndex !== -1) {
  79555. _this.controllers.splice(controllerIndex, 1);
  79556. }
  79557. }
  79558. });
  79559. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79560. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79561. var webVrController_1 = gamepad;
  79562. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  79563. if (_this.webVROptions.controllerMeshes) {
  79564. if (webVrController_1.defaultModel) {
  79565. webVrController_1.defaultModel.setEnabled(true);
  79566. }
  79567. else {
  79568. // Load the meshes
  79569. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79570. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79571. if (_this.webVROptions.defaultLightingOnControllers) {
  79572. if (!_this._lightOnControllers) {
  79573. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79574. }
  79575. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79576. var children = mesh.getChildren();
  79577. if (children.length !== 0) {
  79578. children.forEach(function (mesh) {
  79579. light.includedOnlyMeshes.push(mesh);
  79580. activateLightOnSubMeshes_1(mesh, light);
  79581. });
  79582. }
  79583. };
  79584. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79585. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79586. }
  79587. });
  79588. }
  79589. }
  79590. webVrController_1.attachToPoseControlledCamera(_this);
  79591. // since this is async - sanity check. Is the controller already stored?
  79592. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79593. //add to the controllers array
  79594. _this.controllers.push(webVrController_1);
  79595. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79596. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79597. // So we're overriding setting left & right manually to be sure
  79598. var firstViveWandDetected = false;
  79599. for (var i = 0; i < _this.controllers.length; i++) {
  79600. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79601. if (!firstViveWandDetected) {
  79602. firstViveWandDetected = true;
  79603. _this.controllers[i].hand = "left";
  79604. }
  79605. else {
  79606. _this.controllers[i].hand = "right";
  79607. }
  79608. }
  79609. }
  79610. //did we find enough controllers? Great! let the developer know.
  79611. if (_this.controllers.length >= 2) {
  79612. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79613. }
  79614. }
  79615. }
  79616. });
  79617. };
  79618. return WebVRFreeCamera;
  79619. }(BABYLON.FreeCamera));
  79620. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79621. })(BABYLON || (BABYLON = {}));
  79622. //# sourceMappingURL=babylon.webVRCamera.js.map
  79623. var BABYLON;
  79624. (function (BABYLON) {
  79625. // We're mainly based on the logic defined into the FreeCamera code
  79626. /**
  79627. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79628. * being tilted forward or back and left or right.
  79629. */
  79630. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79631. __extends(DeviceOrientationCamera, _super);
  79632. /**
  79633. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79634. * @param name The name of the camera
  79635. * @param position The start position camera
  79636. * @param scene The scene the camera belongs to
  79637. */
  79638. function DeviceOrientationCamera(name, position, scene) {
  79639. var _this = _super.call(this, name, position, scene) || this;
  79640. _this._quaternionCache = new BABYLON.Quaternion();
  79641. _this.inputs.addDeviceOrientation();
  79642. return _this;
  79643. }
  79644. /**
  79645. * Gets the current instance class name ("DeviceOrientationCamera").
  79646. * This helps avoiding instanceof at run time.
  79647. * @returns the class name
  79648. */
  79649. DeviceOrientationCamera.prototype.getClassName = function () {
  79650. return "DeviceOrientationCamera";
  79651. };
  79652. /**
  79653. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79654. */
  79655. DeviceOrientationCamera.prototype._checkInputs = function () {
  79656. _super.prototype._checkInputs.call(this);
  79657. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79658. if (this._initialQuaternion) {
  79659. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79660. }
  79661. };
  79662. /**
  79663. * Reset the camera to its default orientation on the specified axis only.
  79664. * @param axis The axis to reset
  79665. */
  79666. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79667. var _this = this;
  79668. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79669. //can only work if this camera has a rotation quaternion already.
  79670. if (!this.rotationQuaternion)
  79671. return;
  79672. if (!this._initialQuaternion) {
  79673. this._initialQuaternion = new BABYLON.Quaternion();
  79674. }
  79675. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79676. ['x', 'y', 'z'].forEach(function (axisName) {
  79677. if (!axis[axisName]) {
  79678. _this._initialQuaternion[axisName] = 0;
  79679. }
  79680. else {
  79681. _this._initialQuaternion[axisName] *= -1;
  79682. }
  79683. });
  79684. this._initialQuaternion.normalize();
  79685. //force rotation update
  79686. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79687. };
  79688. return DeviceOrientationCamera;
  79689. }(BABYLON.FreeCamera));
  79690. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79691. })(BABYLON || (BABYLON = {}));
  79692. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79693. var BABYLON;
  79694. (function (BABYLON) {
  79695. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79696. __extends(VRDeviceOrientationFreeCamera, _super);
  79697. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79698. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79699. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79700. var _this = _super.call(this, name, position, scene) || this;
  79701. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79702. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79703. return _this;
  79704. }
  79705. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79706. return "VRDeviceOrientationFreeCamera";
  79707. };
  79708. return VRDeviceOrientationFreeCamera;
  79709. }(BABYLON.DeviceOrientationCamera));
  79710. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79711. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79712. __extends(VRDeviceOrientationGamepadCamera, _super);
  79713. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79714. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79715. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79716. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79717. _this.inputs.addGamepad();
  79718. return _this;
  79719. }
  79720. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79721. return "VRDeviceOrientationGamepadCamera";
  79722. };
  79723. return VRDeviceOrientationGamepadCamera;
  79724. }(VRDeviceOrientationFreeCamera));
  79725. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79726. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79727. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79728. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79729. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79730. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79731. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79732. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79733. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79734. _this.inputs.addVRDeviceOrientation();
  79735. return _this;
  79736. }
  79737. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79738. return "VRDeviceOrientationArcRotateCamera";
  79739. };
  79740. return VRDeviceOrientationArcRotateCamera;
  79741. }(BABYLON.ArcRotateCamera));
  79742. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79743. })(BABYLON || (BABYLON = {}));
  79744. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79745. var BABYLON;
  79746. (function (BABYLON) {
  79747. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79748. __extends(AnaglyphFreeCamera, _super);
  79749. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79750. var _this = _super.call(this, name, position, scene) || this;
  79751. _this.interaxialDistance = interaxialDistance;
  79752. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79753. return _this;
  79754. }
  79755. AnaglyphFreeCamera.prototype.getClassName = function () {
  79756. return "AnaglyphFreeCamera";
  79757. };
  79758. return AnaglyphFreeCamera;
  79759. }(BABYLON.FreeCamera));
  79760. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79761. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79762. __extends(AnaglyphArcRotateCamera, _super);
  79763. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79764. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79765. _this.interaxialDistance = interaxialDistance;
  79766. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79767. return _this;
  79768. }
  79769. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79770. return "AnaglyphArcRotateCamera";
  79771. };
  79772. return AnaglyphArcRotateCamera;
  79773. }(BABYLON.ArcRotateCamera));
  79774. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79775. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79776. __extends(AnaglyphGamepadCamera, _super);
  79777. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79778. var _this = _super.call(this, name, position, scene) || this;
  79779. _this.interaxialDistance = interaxialDistance;
  79780. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79781. return _this;
  79782. }
  79783. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79784. return "AnaglyphGamepadCamera";
  79785. };
  79786. return AnaglyphGamepadCamera;
  79787. }(BABYLON.GamepadCamera));
  79788. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79789. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79790. __extends(AnaglyphUniversalCamera, _super);
  79791. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79792. var _this = _super.call(this, name, position, scene) || this;
  79793. _this.interaxialDistance = interaxialDistance;
  79794. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79795. return _this;
  79796. }
  79797. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79798. return "AnaglyphUniversalCamera";
  79799. };
  79800. return AnaglyphUniversalCamera;
  79801. }(BABYLON.UniversalCamera));
  79802. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79803. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79804. __extends(StereoscopicFreeCamera, _super);
  79805. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79806. var _this = _super.call(this, name, position, scene) || this;
  79807. _this.interaxialDistance = interaxialDistance;
  79808. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79809. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79810. return _this;
  79811. }
  79812. StereoscopicFreeCamera.prototype.getClassName = function () {
  79813. return "StereoscopicFreeCamera";
  79814. };
  79815. return StereoscopicFreeCamera;
  79816. }(BABYLON.FreeCamera));
  79817. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79818. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79819. __extends(StereoscopicArcRotateCamera, _super);
  79820. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79821. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79822. _this.interaxialDistance = interaxialDistance;
  79823. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79824. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79825. return _this;
  79826. }
  79827. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79828. return "StereoscopicArcRotateCamera";
  79829. };
  79830. return StereoscopicArcRotateCamera;
  79831. }(BABYLON.ArcRotateCamera));
  79832. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79833. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79834. __extends(StereoscopicGamepadCamera, _super);
  79835. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79836. var _this = _super.call(this, name, position, scene) || this;
  79837. _this.interaxialDistance = interaxialDistance;
  79838. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79839. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79840. return _this;
  79841. }
  79842. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79843. return "StereoscopicGamepadCamera";
  79844. };
  79845. return StereoscopicGamepadCamera;
  79846. }(BABYLON.GamepadCamera));
  79847. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79848. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79849. __extends(StereoscopicUniversalCamera, _super);
  79850. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79851. var _this = _super.call(this, name, position, scene) || this;
  79852. _this.interaxialDistance = interaxialDistance;
  79853. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79854. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79855. return _this;
  79856. }
  79857. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79858. return "StereoscopicUniversalCamera";
  79859. };
  79860. return StereoscopicUniversalCamera;
  79861. }(BABYLON.UniversalCamera));
  79862. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79863. })(BABYLON || (BABYLON = {}));
  79864. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79865. var BABYLON;
  79866. (function (BABYLON) {
  79867. var VRExperienceHelperGazer = /** @class */ (function () {
  79868. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  79869. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  79870. this.scene = scene;
  79871. this._pointerDownOnMeshAsked = false;
  79872. this._isActionableMesh = false;
  79873. this._teleportationRequestInitiated = false;
  79874. this._teleportationBackRequestInitiated = false;
  79875. this._dpadPressed = true;
  79876. this._activePointer = false;
  79877. this._id = VRExperienceHelperGazer._idCounter++;
  79878. // Gaze tracker
  79879. if (!gazeTrackerToClone) {
  79880. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  79881. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79882. this._gazeTracker.isPickable = false;
  79883. this._gazeTracker.isVisible = false;
  79884. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  79885. targetMat.specularColor = BABYLON.Color3.Black();
  79886. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79887. targetMat.backFaceCulling = false;
  79888. this._gazeTracker.material = targetMat;
  79889. }
  79890. else {
  79891. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  79892. }
  79893. }
  79894. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  79895. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  79896. };
  79897. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  79898. this._pointerDownOnMeshAsked = true;
  79899. if (this._currentMeshSelected && this._currentHit) {
  79900. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  79901. }
  79902. };
  79903. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  79904. if (this._currentMeshSelected && this._currentHit) {
  79905. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  79906. }
  79907. this._pointerDownOnMeshAsked = false;
  79908. };
  79909. VRExperienceHelperGazer.prototype._activatePointer = function () {
  79910. this._activePointer = true;
  79911. };
  79912. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  79913. this._activePointer = false;
  79914. };
  79915. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  79916. };
  79917. VRExperienceHelperGazer.prototype.dispose = function () {
  79918. this._interactionsEnabled = false;
  79919. this._teleportationEnabled = false;
  79920. };
  79921. VRExperienceHelperGazer._idCounter = 0;
  79922. return VRExperienceHelperGazer;
  79923. }());
  79924. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  79925. __extends(VRExperienceHelperControllerGazer, _super);
  79926. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  79927. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  79928. _this.webVRController = webVRController;
  79929. // Laser pointer
  79930. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  79931. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  79932. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79933. laserPointerMaterial.alpha = 0.6;
  79934. _this._laserPointer.material = laserPointerMaterial;
  79935. _this._laserPointer.rotation.x = Math.PI / 2;
  79936. _this._laserPointer.position.z = -0.5;
  79937. _this._laserPointer.isVisible = false;
  79938. _this._laserPointer.parent = webVRController.mesh;
  79939. return _this;
  79940. }
  79941. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  79942. return this.webVRController.getForwardRay(length);
  79943. };
  79944. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  79945. _super.prototype._activatePointer.call(this);
  79946. this._laserPointer.isVisible = true;
  79947. };
  79948. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  79949. _super.prototype._deactivatePointer.call(this);
  79950. this._laserPointer.isVisible = false;
  79951. };
  79952. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  79953. this._laserPointer.material.emissiveColor = color;
  79954. };
  79955. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  79956. this._laserPointer.parent = mesh;
  79957. };
  79958. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  79959. this._laserPointer.scaling.y = distance;
  79960. this._laserPointer.position.z = -distance / 2;
  79961. };
  79962. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  79963. _super.prototype.dispose.call(this);
  79964. this._laserPointer.dispose();
  79965. };
  79966. return VRExperienceHelperControllerGazer;
  79967. }(VRExperienceHelperGazer));
  79968. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  79969. __extends(VRExperienceHelperCameraGazer, _super);
  79970. function VRExperienceHelperCameraGazer(getCamera, scene) {
  79971. var _this = _super.call(this, scene) || this;
  79972. _this.getCamera = getCamera;
  79973. return _this;
  79974. }
  79975. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  79976. var camera = this.getCamera();
  79977. if (camera) {
  79978. return camera.getForwardRay(length);
  79979. }
  79980. else {
  79981. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  79982. }
  79983. };
  79984. return VRExperienceHelperCameraGazer;
  79985. }(VRExperienceHelperGazer));
  79986. /**
  79987. * Helps to quickly add VR support to an existing scene.
  79988. * See http://doc.babylonjs.com/how_to/webvr_helper
  79989. */
  79990. var VRExperienceHelper = /** @class */ (function () {
  79991. /**
  79992. * Instantiates a VRExperienceHelper.
  79993. * Helps to quickly add VR support to an existing scene.
  79994. * @param scene The scene the VRExperienceHelper belongs to.
  79995. * @param webVROptions Options to modify the vr experience helper's behavior.
  79996. */
  79997. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  79998. if (webVROptions === void 0) { webVROptions = {}; }
  79999. var _this = this;
  80000. this.webVROptions = webVROptions;
  80001. // Can the system support WebVR, even if a headset isn't plugged in?
  80002. this._webVRsupported = false;
  80003. // If WebVR is supported, is a headset plugged in and are we ready to present?
  80004. this._webVRready = false;
  80005. // Are we waiting for the requestPresent callback to complete?
  80006. this._webVRrequesting = false;
  80007. // Are we presenting to the headset right now?
  80008. this._webVRpresenting = false;
  80009. // Are we presenting in the fullscreen fallback?
  80010. this._fullscreenVRpresenting = false;
  80011. /**
  80012. * Observable raised when entering VR.
  80013. */
  80014. this.onEnteringVRObservable = new BABYLON.Observable();
  80015. /**
  80016. * Observable raised when exiting VR.
  80017. */
  80018. this.onExitingVRObservable = new BABYLON.Observable();
  80019. /**
  80020. * Observable raised when controller mesh is loaded.
  80021. */
  80022. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80023. this._useCustomVRButton = false;
  80024. this._teleportationRequested = false;
  80025. this._teleportActive = false;
  80026. this._floorMeshesCollection = [];
  80027. this._rotationAllowed = true;
  80028. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  80029. this._rotationRightAsked = false;
  80030. this._rotationLeftAsked = false;
  80031. this._isDefaultTeleportationTarget = true;
  80032. this._teleportationFillColor = "#444444";
  80033. this._teleportationBorderColor = "#FFFFFF";
  80034. this._rotationAngle = 0;
  80035. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  80036. this._padSensibilityUp = 0.65;
  80037. this._padSensibilityDown = 0.35;
  80038. this.leftController = null;
  80039. this.rightController = null;
  80040. /**
  80041. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  80042. */
  80043. this.onNewMeshSelected = new BABYLON.Observable();
  80044. /**
  80045. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  80046. */
  80047. this.onNewMeshPicked = new BABYLON.Observable();
  80048. /**
  80049. * Observable raised before camera teleportation
  80050. */
  80051. this.onBeforeCameraTeleport = new BABYLON.Observable();
  80052. /**
  80053. * Observable raised after camera teleportation
  80054. */
  80055. this.onAfterCameraTeleport = new BABYLON.Observable();
  80056. /**
  80057. * Observable raised when current selected mesh gets unselected
  80058. */
  80059. this.onSelectedMeshUnselected = new BABYLON.Observable();
  80060. /**
  80061. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  80062. */
  80063. this.teleportationEnabled = true;
  80064. this._teleportationInitialized = false;
  80065. this._interactionsEnabled = false;
  80066. this._interactionsRequested = false;
  80067. this._displayGaze = true;
  80068. this._displayLaserPointer = true;
  80069. this._onResize = function () {
  80070. _this.moveButtonToBottomRight();
  80071. if (_this._fullscreenVRpresenting && _this._webVRready) {
  80072. _this.exitVR();
  80073. }
  80074. };
  80075. this._onFullscreenChange = function () {
  80076. if (document.fullscreen !== undefined) {
  80077. _this._fullscreenVRpresenting = document.fullscreen;
  80078. }
  80079. else if (document.mozFullScreen !== undefined) {
  80080. _this._fullscreenVRpresenting = document.mozFullScreen;
  80081. }
  80082. else if (document.webkitIsFullScreen !== undefined) {
  80083. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  80084. }
  80085. else if (document.msIsFullScreen !== undefined) {
  80086. _this._fullscreenVRpresenting = document.msIsFullScreen;
  80087. }
  80088. if (!_this._fullscreenVRpresenting && _this._canvas) {
  80089. _this.exitVR();
  80090. if (!_this._useCustomVRButton) {
  80091. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  80092. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  80093. }
  80094. }
  80095. };
  80096. this.beforeRender = function () {
  80097. if (_this.leftController && _this.leftController._activePointer) {
  80098. _this._castRayAndSelectObject(_this.leftController);
  80099. }
  80100. if (_this.rightController && _this.rightController._activePointer) {
  80101. _this._castRayAndSelectObject(_this.rightController);
  80102. }
  80103. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  80104. _this._castRayAndSelectObject(_this._cameraGazer);
  80105. }
  80106. else {
  80107. _this._cameraGazer._gazeTracker.isVisible = false;
  80108. }
  80109. };
  80110. this._onNewGamepadConnected = function (gamepad) {
  80111. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  80112. if (gamepad.leftStick) {
  80113. gamepad.onleftstickchanged(function (stickValues) {
  80114. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  80115. // Listening to classic/xbox gamepad only if no VR controller is active
  80116. if ((!_this.leftController && !_this.rightController) ||
  80117. ((_this.leftController && !_this.leftController._activePointer) &&
  80118. (_this.rightController && !_this.rightController._activePointer))) {
  80119. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  80120. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  80121. }
  80122. }
  80123. });
  80124. }
  80125. if (gamepad.rightStick) {
  80126. gamepad.onrightstickchanged(function (stickValues) {
  80127. if (_this._teleportationInitialized) {
  80128. _this._checkRotate(stickValues, _this._cameraGazer);
  80129. }
  80130. });
  80131. }
  80132. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  80133. gamepad.onbuttondown(function (buttonPressed) {
  80134. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80135. _this._cameraGazer._selectionPointerDown();
  80136. }
  80137. });
  80138. gamepad.onbuttonup(function (buttonPressed) {
  80139. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  80140. _this._cameraGazer._selectionPointerUp();
  80141. }
  80142. });
  80143. }
  80144. }
  80145. else {
  80146. var webVRController = gamepad;
  80147. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  80148. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  80149. _this.rightController = controller;
  80150. }
  80151. else {
  80152. _this.leftController = controller;
  80153. }
  80154. _this._tryEnableInteractionOnController(controller);
  80155. }
  80156. };
  80157. // 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
  80158. this._tryEnableInteractionOnController = function (controller) {
  80159. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  80160. _this._enableInteractionOnController(controller);
  80161. }
  80162. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  80163. _this._enableTeleportationOnController(controller);
  80164. }
  80165. };
  80166. this._onNewGamepadDisconnected = function (gamepad) {
  80167. if (gamepad instanceof BABYLON.WebVRController) {
  80168. if (gamepad.hand === "left" && _this.leftController != null) {
  80169. _this.leftController.dispose();
  80170. _this.leftController = null;
  80171. }
  80172. if (gamepad.hand === "right" && _this.rightController != null) {
  80173. _this.rightController.dispose();
  80174. _this.rightController = null;
  80175. }
  80176. }
  80177. };
  80178. this._workingVector = BABYLON.Vector3.Zero();
  80179. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80180. this._workingMatrix = BABYLON.Matrix.Identity();
  80181. this._scene = scene;
  80182. this._canvas = scene.getEngine().getRenderingCanvas();
  80183. // Parse options
  80184. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80185. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80186. }
  80187. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80188. webVROptions.createDeviceOrientationCamera = true;
  80189. }
  80190. if (webVROptions.defaultHeight === undefined) {
  80191. webVROptions.defaultHeight = 1.7;
  80192. }
  80193. if (webVROptions.useCustomVRButton) {
  80194. this._useCustomVRButton = true;
  80195. if (webVROptions.customVRButton) {
  80196. this._btnVR = webVROptions.customVRButton;
  80197. }
  80198. }
  80199. if (webVROptions.rayLength) {
  80200. this._rayLength = webVROptions.rayLength;
  80201. }
  80202. this._defaultHeight = webVROptions.defaultHeight;
  80203. // Set position
  80204. if (this._scene.activeCamera) {
  80205. this._position = this._scene.activeCamera.position.clone();
  80206. }
  80207. else {
  80208. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80209. }
  80210. // Set non-vr camera
  80211. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80212. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80213. // Copy data from existing camera
  80214. if (this._scene.activeCamera) {
  80215. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80216. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80217. // Set rotation from previous camera
  80218. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80219. var targetCamera = this._scene.activeCamera;
  80220. if (targetCamera.rotationQuaternion) {
  80221. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80222. }
  80223. else {
  80224. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80225. }
  80226. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80227. }
  80228. }
  80229. this._scene.activeCamera = this._deviceOrientationCamera;
  80230. if (this._canvas) {
  80231. this._scene.activeCamera.attachControl(this._canvas);
  80232. }
  80233. }
  80234. else {
  80235. this._existingCamera = this._scene.activeCamera;
  80236. }
  80237. // Create VR cameras
  80238. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80239. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80240. }
  80241. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80242. this._webVRCamera.useStandingMatrix();
  80243. // Create default button
  80244. if (!this._useCustomVRButton) {
  80245. this._btnVR = document.createElement("BUTTON");
  80246. this._btnVR.className = "babylonVRicon";
  80247. this._btnVR.id = "babylonVRiconbtn";
  80248. this._btnVR.title = "Click to switch to VR";
  80249. 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) }";
  80250. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80251. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80252. // css += ".babylonVRicon.vrdisplaysupported { }";
  80253. // css += ".babylonVRicon.vrdisplayready { }";
  80254. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80255. var style = document.createElement('style');
  80256. style.appendChild(document.createTextNode(css));
  80257. document.getElementsByTagName('head')[0].appendChild(style);
  80258. this.moveButtonToBottomRight();
  80259. }
  80260. // VR button click event
  80261. if (this._btnVR) {
  80262. this._btnVR.addEventListener("click", function () {
  80263. if (!_this.isInVRMode) {
  80264. _this.enterVR();
  80265. }
  80266. else {
  80267. _this.exitVR();
  80268. }
  80269. });
  80270. }
  80271. // Window events
  80272. window.addEventListener("resize", this._onResize);
  80273. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80274. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80275. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80276. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80277. // Display vr button when headset is connected
  80278. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80279. this.displayVRButton();
  80280. }
  80281. else {
  80282. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80283. if (e.vrDisplay) {
  80284. _this.displayVRButton();
  80285. }
  80286. });
  80287. }
  80288. // Exiting VR mode using 'ESC' key on desktop
  80289. this._onKeyDown = function (event) {
  80290. if (event.keyCode === 27 && _this.isInVRMode) {
  80291. _this.exitVR();
  80292. }
  80293. };
  80294. document.addEventListener("keydown", this._onKeyDown);
  80295. // Exiting VR mode double tapping the touch screen
  80296. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80297. if (_this.isInVRMode) {
  80298. _this.exitVR();
  80299. if (_this._fullscreenVRpresenting) {
  80300. _this._scene.getEngine().switchFullscreen(true);
  80301. }
  80302. }
  80303. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80304. // Listen for WebVR display changes
  80305. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80306. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80307. this._onVRRequestPresentStart = function () {
  80308. _this._webVRrequesting = true;
  80309. _this.updateButtonVisibility();
  80310. };
  80311. this._onVRRequestPresentComplete = function (success) {
  80312. _this._webVRrequesting = false;
  80313. _this.updateButtonVisibility();
  80314. };
  80315. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80316. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80317. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80318. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80319. scene.onDisposeObservable.add(function () {
  80320. _this.dispose();
  80321. });
  80322. // Gamepad connection events
  80323. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80324. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80325. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80326. this.updateButtonVisibility();
  80327. //create easing functions
  80328. this._circleEase = new BABYLON.CircleEase();
  80329. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80330. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  80331. }
  80332. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80333. /** Return this.onEnteringVRObservable
  80334. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80335. */
  80336. get: function () {
  80337. return this.onEnteringVRObservable;
  80338. },
  80339. enumerable: true,
  80340. configurable: true
  80341. });
  80342. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80343. /** Return this.onExitingVRObservable
  80344. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80345. */
  80346. get: function () {
  80347. return this.onExitingVRObservable;
  80348. },
  80349. enumerable: true,
  80350. configurable: true
  80351. });
  80352. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80353. /** Return this.onControllerMeshLoadedObservable
  80354. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80355. */
  80356. get: function () {
  80357. return this.onControllerMeshLoadedObservable;
  80358. },
  80359. enumerable: true,
  80360. configurable: true
  80361. });
  80362. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80363. /**
  80364. * The mesh used to display where the user is going to teleport.
  80365. */
  80366. get: function () {
  80367. return this._teleportationTarget;
  80368. },
  80369. /**
  80370. * Sets the mesh to be used to display where the user is going to teleport.
  80371. */
  80372. set: function (value) {
  80373. if (value) {
  80374. value.name = "teleportationTarget";
  80375. this._isDefaultTeleportationTarget = false;
  80376. this._teleportationTarget = value;
  80377. }
  80378. },
  80379. enumerable: true,
  80380. configurable: true
  80381. });
  80382. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80383. /**
  80384. * The mesh used to display where the user is selecting,
  80385. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80386. * See http://doc.babylonjs.com/resources/baking_transformations
  80387. */
  80388. get: function () {
  80389. return this._cameraGazer._gazeTracker;
  80390. },
  80391. set: function (value) {
  80392. if (value) {
  80393. this._cameraGazer._gazeTracker = value;
  80394. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  80395. this._cameraGazer._gazeTracker.isPickable = false;
  80396. this._cameraGazer._gazeTracker.isVisible = false;
  80397. this._cameraGazer._gazeTracker.name = "gazeTracker";
  80398. if (this.leftController) {
  80399. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80400. }
  80401. if (this.rightController) {
  80402. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  80403. }
  80404. }
  80405. },
  80406. enumerable: true,
  80407. configurable: true
  80408. });
  80409. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80410. /**
  80411. * If the ray of the gaze should be displayed.
  80412. */
  80413. get: function () {
  80414. return this._displayGaze;
  80415. },
  80416. /**
  80417. * Sets if the ray of the gaze should be displayed.
  80418. */
  80419. set: function (value) {
  80420. this._displayGaze = value;
  80421. if (!value) {
  80422. this._cameraGazer._gazeTracker.isVisible = false;
  80423. if (this.leftController) {
  80424. this.leftController._gazeTracker.isVisible = false;
  80425. }
  80426. if (this.rightController) {
  80427. this.rightController._gazeTracker.isVisible = false;
  80428. }
  80429. }
  80430. },
  80431. enumerable: true,
  80432. configurable: true
  80433. });
  80434. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80435. /**
  80436. * If the ray of the LaserPointer should be displayed.
  80437. */
  80438. get: function () {
  80439. return this._displayLaserPointer;
  80440. },
  80441. /**
  80442. * Sets if the ray of the LaserPointer should be displayed.
  80443. */
  80444. set: function (value) {
  80445. this._displayLaserPointer = value;
  80446. if (!value) {
  80447. if (this.rightController) {
  80448. this.rightController._deactivatePointer();
  80449. this.rightController._gazeTracker.isVisible = false;
  80450. }
  80451. if (this.leftController) {
  80452. this.leftController._deactivatePointer();
  80453. this.leftController._gazeTracker.isVisible = false;
  80454. }
  80455. }
  80456. else {
  80457. if (this.rightController) {
  80458. this.rightController._activatePointer();
  80459. }
  80460. else if (this.leftController) {
  80461. this.leftController._activatePointer();
  80462. }
  80463. }
  80464. },
  80465. enumerable: true,
  80466. configurable: true
  80467. });
  80468. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80469. /**
  80470. * The deviceOrientationCamera used as the camera when not in VR.
  80471. */
  80472. get: function () {
  80473. return this._deviceOrientationCamera;
  80474. },
  80475. enumerable: true,
  80476. configurable: true
  80477. });
  80478. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80479. /**
  80480. * Based on the current WebVR support, returns the current VR camera used.
  80481. */
  80482. get: function () {
  80483. if (this._webVRready) {
  80484. return this._webVRCamera;
  80485. }
  80486. else {
  80487. return this._scene.activeCamera;
  80488. }
  80489. },
  80490. enumerable: true,
  80491. configurable: true
  80492. });
  80493. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80494. /**
  80495. * The webVRCamera which is used when in VR.
  80496. */
  80497. get: function () {
  80498. return this._webVRCamera;
  80499. },
  80500. enumerable: true,
  80501. configurable: true
  80502. });
  80503. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80504. /**
  80505. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80506. */
  80507. get: function () {
  80508. return this._vrDeviceOrientationCamera;
  80509. },
  80510. enumerable: true,
  80511. configurable: true
  80512. });
  80513. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  80514. get: function () {
  80515. var result = this._cameraGazer._teleportationRequestInitiated
  80516. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  80517. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  80518. return result;
  80519. },
  80520. enumerable: true,
  80521. configurable: true
  80522. });
  80523. // Raised when one of the controller has loaded successfully its associated default mesh
  80524. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80525. if (this.leftController && this.leftController.webVRController == webVRController) {
  80526. this._tryEnableInteractionOnController(this.leftController);
  80527. }
  80528. if (this.rightController && this.rightController.webVRController == webVRController) {
  80529. this._tryEnableInteractionOnController(this.rightController);
  80530. }
  80531. try {
  80532. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80533. }
  80534. catch (err) {
  80535. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80536. }
  80537. };
  80538. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80539. /**
  80540. * Gets a value indicating if we are currently in VR mode.
  80541. */
  80542. get: function () {
  80543. return this._webVRpresenting || this._fullscreenVRpresenting;
  80544. },
  80545. enumerable: true,
  80546. configurable: true
  80547. });
  80548. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80549. var vrDisplay = this._scene.getEngine().getVRDevice();
  80550. if (vrDisplay) {
  80551. var wasPresenting = this._webVRpresenting;
  80552. // A VR display is connected
  80553. this._webVRpresenting = vrDisplay.isPresenting;
  80554. if (wasPresenting && !this._webVRpresenting)
  80555. this.exitVR();
  80556. }
  80557. else {
  80558. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80559. }
  80560. this.updateButtonVisibility();
  80561. };
  80562. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80563. this._webVRsupported = eventArgs.vrSupported;
  80564. this._webVRready = !!eventArgs.vrDisplay;
  80565. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80566. this.updateButtonVisibility();
  80567. };
  80568. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80569. if (this._canvas && !this._useCustomVRButton) {
  80570. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80571. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80572. }
  80573. };
  80574. VRExperienceHelper.prototype.displayVRButton = function () {
  80575. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80576. document.body.appendChild(this._btnVR);
  80577. this._btnVRDisplayed = true;
  80578. }
  80579. };
  80580. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80581. if (!this._btnVR || this._useCustomVRButton) {
  80582. return;
  80583. }
  80584. this._btnVR.className = "babylonVRicon";
  80585. if (this.isInVRMode) {
  80586. this._btnVR.className += " vrdisplaypresenting";
  80587. }
  80588. else {
  80589. if (this._webVRready)
  80590. this._btnVR.className += " vrdisplayready";
  80591. if (this._webVRsupported)
  80592. this._btnVR.className += " vrdisplaysupported";
  80593. if (this._webVRrequesting)
  80594. this._btnVR.className += " vrdisplayrequesting";
  80595. }
  80596. };
  80597. /**
  80598. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80599. * Otherwise, will use the fullscreen API.
  80600. */
  80601. VRExperienceHelper.prototype.enterVR = function () {
  80602. if (this.onEnteringVRObservable) {
  80603. try {
  80604. this.onEnteringVRObservable.notifyObservers(this);
  80605. }
  80606. catch (err) {
  80607. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80608. }
  80609. }
  80610. if (this._scene.activeCamera) {
  80611. this._position = this._scene.activeCamera.position.clone();
  80612. // make sure that we return to the last active camera
  80613. this._existingCamera = this._scene.activeCamera;
  80614. }
  80615. if (this._webVRrequesting)
  80616. return;
  80617. // If WebVR is supported and a headset is connected
  80618. if (this._webVRready) {
  80619. if (!this._webVRpresenting) {
  80620. this._webVRCamera.position = this._position;
  80621. this._scene.activeCamera = this._webVRCamera;
  80622. }
  80623. }
  80624. else if (this._vrDeviceOrientationCamera) {
  80625. this._vrDeviceOrientationCamera.position = this._position;
  80626. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80627. this._scene.getEngine().switchFullscreen(true);
  80628. this.updateButtonVisibility();
  80629. }
  80630. if (this._scene.activeCamera && this._canvas) {
  80631. this._scene.activeCamera.attachControl(this._canvas);
  80632. }
  80633. if (this._interactionsEnabled) {
  80634. this._scene.registerBeforeRender(this.beforeRender);
  80635. }
  80636. };
  80637. /**
  80638. * Attempt to exit VR, or fullscreen.
  80639. */
  80640. VRExperienceHelper.prototype.exitVR = function () {
  80641. if (this.onExitingVRObservable) {
  80642. try {
  80643. this.onExitingVRObservable.notifyObservers(this);
  80644. }
  80645. catch (err) {
  80646. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80647. }
  80648. }
  80649. if (this._webVRpresenting) {
  80650. this._scene.getEngine().disableVR();
  80651. }
  80652. if (this._scene.activeCamera) {
  80653. this._position = this._scene.activeCamera.position.clone();
  80654. }
  80655. if (this._deviceOrientationCamera) {
  80656. this._deviceOrientationCamera.position = this._position;
  80657. this._scene.activeCamera = this._deviceOrientationCamera;
  80658. if (this._canvas) {
  80659. this._scene.activeCamera.attachControl(this._canvas);
  80660. }
  80661. }
  80662. else if (this._existingCamera) {
  80663. this._existingCamera.position = this._position;
  80664. this._scene.activeCamera = this._existingCamera;
  80665. }
  80666. this.updateButtonVisibility();
  80667. if (this._interactionsEnabled) {
  80668. this._scene.unregisterBeforeRender(this.beforeRender);
  80669. }
  80670. };
  80671. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80672. /**
  80673. * The position of the vr experience helper.
  80674. */
  80675. get: function () {
  80676. return this._position;
  80677. },
  80678. /**
  80679. * Sets the position of the vr experience helper.
  80680. */
  80681. set: function (value) {
  80682. this._position = value;
  80683. if (this._scene.activeCamera) {
  80684. this._scene.activeCamera.position = value;
  80685. }
  80686. },
  80687. enumerable: true,
  80688. configurable: true
  80689. });
  80690. /**
  80691. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80692. */
  80693. VRExperienceHelper.prototype.enableInteractions = function () {
  80694. var _this = this;
  80695. if (!this._interactionsEnabled) {
  80696. this._interactionsRequested = true;
  80697. if (this.leftController) {
  80698. this._enableInteractionOnController(this.leftController);
  80699. }
  80700. if (this.rightController) {
  80701. this._enableInteractionOnController(this.rightController);
  80702. }
  80703. this.raySelectionPredicate = function (mesh) {
  80704. return mesh.isVisible;
  80705. };
  80706. this.meshSelectionPredicate = function (mesh) {
  80707. return true;
  80708. };
  80709. this._raySelectionPredicate = function (mesh) {
  80710. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  80711. && mesh.name.indexOf("teleportationTarget") === -1
  80712. && mesh.name.indexOf("torusTeleportation") === -1
  80713. && mesh.name.indexOf("laserPointer") === -1)) {
  80714. return _this.raySelectionPredicate(mesh);
  80715. }
  80716. return false;
  80717. };
  80718. this._interactionsEnabled = true;
  80719. }
  80720. };
  80721. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80722. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80723. if (this._floorMeshesCollection[i].id === mesh.id) {
  80724. return true;
  80725. }
  80726. }
  80727. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80728. return true;
  80729. }
  80730. return false;
  80731. };
  80732. /**
  80733. * Adds a floor mesh to be used for teleportation.
  80734. * @param floorMesh the mesh to be used for teleportation.
  80735. */
  80736. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80737. if (!this._floorMeshesCollection) {
  80738. return;
  80739. }
  80740. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80741. return;
  80742. }
  80743. this._floorMeshesCollection.push(floorMesh);
  80744. };
  80745. /**
  80746. * Removes a floor mesh from being used for teleportation.
  80747. * @param floorMesh the mesh to be removed.
  80748. */
  80749. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80750. if (!this._floorMeshesCollection) {
  80751. return;
  80752. }
  80753. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80754. if (meshIndex !== -1) {
  80755. this._floorMeshesCollection.splice(meshIndex, 1);
  80756. }
  80757. };
  80758. /**
  80759. * Enables interactions and teleportation using the VR controllers and gaze.
  80760. * @param vrTeleportationOptions options to modify teleportation behavior.
  80761. */
  80762. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80763. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80764. if (!this._teleportationInitialized) {
  80765. this._teleportationRequested = true;
  80766. this.enableInteractions();
  80767. if (vrTeleportationOptions.floorMeshName) {
  80768. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80769. }
  80770. if (vrTeleportationOptions.floorMeshes) {
  80771. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80772. }
  80773. if (this.leftController != null) {
  80774. this._enableTeleportationOnController(this.leftController);
  80775. }
  80776. if (this.rightController != null) {
  80777. this._enableTeleportationOnController(this.rightController);
  80778. }
  80779. // Creates an image processing post process for the vignette not relying
  80780. // on the main scene configuration for image processing to reduce setup and spaces
  80781. // (gamma/linear) conflicts.
  80782. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80783. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80784. imageProcessingConfiguration.vignetteEnabled = true;
  80785. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80786. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80787. this._teleportationInitialized = true;
  80788. if (this._isDefaultTeleportationTarget) {
  80789. this._createTeleportationCircles();
  80790. }
  80791. }
  80792. };
  80793. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  80794. var _this = this;
  80795. var controllerMesh = controller.webVRController.mesh;
  80796. if (controllerMesh) {
  80797. var makeNotPick = function (root) {
  80798. root.name += " laserPointer";
  80799. root.getChildMeshes().forEach(function (c) {
  80800. makeNotPick(c);
  80801. });
  80802. };
  80803. makeNotPick(controllerMesh);
  80804. var childMeshes = controllerMesh.getChildMeshes();
  80805. for (var i = 0; i < childMeshes.length; i++) {
  80806. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80807. controllerMesh = childMeshes[i];
  80808. break;
  80809. }
  80810. }
  80811. controller._setLaserPointerParent(controllerMesh);
  80812. controller._interactionsEnabled = true;
  80813. controller._activatePointer();
  80814. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80815. // Enabling / disabling laserPointer
  80816. if (_this._displayLaserPointer && stateObject.value === 1) {
  80817. if (controller._activePointer) {
  80818. controller._deactivatePointer();
  80819. }
  80820. else {
  80821. controller._activatePointer();
  80822. }
  80823. if (_this.displayGaze) {
  80824. controller._gazeTracker.isVisible = controller._activePointer;
  80825. }
  80826. }
  80827. });
  80828. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80829. if (!controller._pointerDownOnMeshAsked) {
  80830. if (stateObject.value > _this._padSensibilityUp) {
  80831. controller._selectionPointerDown();
  80832. }
  80833. }
  80834. else if (stateObject.value < _this._padSensibilityDown) {
  80835. controller._selectionPointerUp();
  80836. }
  80837. });
  80838. }
  80839. };
  80840. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  80841. // Dont teleport if another gaze already requested teleportation
  80842. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  80843. return;
  80844. }
  80845. if (!gazer._teleportationRequestInitiated) {
  80846. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  80847. gazer._activatePointer();
  80848. gazer._teleportationRequestInitiated = true;
  80849. }
  80850. }
  80851. else {
  80852. // Listening to the proper controller values changes to confirm teleportation
  80853. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80854. if (this._teleportActive) {
  80855. this._teleportCamera(this._haloCenter);
  80856. }
  80857. gazer._teleportationRequestInitiated = false;
  80858. }
  80859. }
  80860. };
  80861. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  80862. // Only rotate when user is not currently selecting a teleportation location
  80863. if (gazer._teleportationRequestInitiated) {
  80864. return;
  80865. }
  80866. if (!this._rotationLeftAsked) {
  80867. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  80868. this._rotationLeftAsked = true;
  80869. if (this._rotationAllowed) {
  80870. this._rotateCamera(false);
  80871. }
  80872. }
  80873. }
  80874. else {
  80875. if (stateObject.x > -this._padSensibilityDown) {
  80876. this._rotationLeftAsked = false;
  80877. }
  80878. }
  80879. if (!this._rotationRightAsked) {
  80880. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  80881. this._rotationRightAsked = true;
  80882. if (this._rotationAllowed) {
  80883. this._rotateCamera(true);
  80884. }
  80885. }
  80886. }
  80887. else {
  80888. if (stateObject.x < this._padSensibilityDown) {
  80889. this._rotationRightAsked = false;
  80890. }
  80891. }
  80892. };
  80893. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  80894. // Only teleport backwards when user is not currently selecting a teleportation location
  80895. if (gazer._teleportationRequestInitiated) {
  80896. return;
  80897. }
  80898. // Teleport backwards
  80899. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  80900. if (!gazer._teleportationBackRequestInitiated) {
  80901. if (!this.currentVRCamera) {
  80902. return;
  80903. }
  80904. // Get rotation and position of the current camera
  80905. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80906. var position = this.currentVRCamera.position;
  80907. // If the camera has device position, use that instead
  80908. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80909. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80910. position = this.currentVRCamera.devicePosition;
  80911. }
  80912. // Get matrix with only the y rotation of the device rotation
  80913. rotation.toEulerAnglesToRef(this._workingVector);
  80914. this._workingVector.z = 0;
  80915. this._workingVector.x = 0;
  80916. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80917. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80918. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80919. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80920. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80921. var ray = new BABYLON.Ray(position, this._workingVector);
  80922. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80923. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80924. this._teleportCamera(hit.pickedPoint);
  80925. }
  80926. gazer._teleportationBackRequestInitiated = true;
  80927. }
  80928. }
  80929. else {
  80930. gazer._teleportationBackRequestInitiated = false;
  80931. }
  80932. };
  80933. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  80934. var _this = this;
  80935. var controllerMesh = controller.webVRController.mesh;
  80936. if (controllerMesh) {
  80937. if (!controller._interactionsEnabled) {
  80938. this._enableInteractionOnController(controller);
  80939. }
  80940. controller._interactionsEnabled = true;
  80941. controller._teleportationEnabled = true;
  80942. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80943. controller._dpadPressed = false;
  80944. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80945. controller._dpadPressed = stateObject.pressed;
  80946. if (!controller._dpadPressed) {
  80947. _this._rotationLeftAsked = false;
  80948. _this._rotationRightAsked = false;
  80949. controller._teleportationBackRequestInitiated = false;
  80950. }
  80951. });
  80952. }
  80953. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80954. if (_this.teleportationEnabled) {
  80955. _this._checkTeleportBackwards(stateObject, controller);
  80956. _this._checkTeleportWithRay(stateObject, controller);
  80957. }
  80958. _this._checkRotate(stateObject, controller);
  80959. });
  80960. }
  80961. };
  80962. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80963. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80964. this._teleportationTarget.isPickable = false;
  80965. var length = 512;
  80966. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80967. dynamicTexture.hasAlpha = true;
  80968. var context = dynamicTexture.getContext();
  80969. var centerX = length / 2;
  80970. var centerY = length / 2;
  80971. var radius = 200;
  80972. context.beginPath();
  80973. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80974. context.fillStyle = this._teleportationFillColor;
  80975. context.fill();
  80976. context.lineWidth = 10;
  80977. context.strokeStyle = this._teleportationBorderColor;
  80978. context.stroke();
  80979. context.closePath();
  80980. dynamicTexture.update();
  80981. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  80982. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  80983. this._teleportationTarget.material = teleportationCircleMaterial;
  80984. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  80985. torus.isPickable = false;
  80986. torus.parent = this._teleportationTarget;
  80987. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80988. var keys = [];
  80989. keys.push({
  80990. frame: 0,
  80991. value: 0
  80992. });
  80993. keys.push({
  80994. frame: 30,
  80995. value: 0.4
  80996. });
  80997. keys.push({
  80998. frame: 60,
  80999. value: 0
  81000. });
  81001. animationInnerCircle.setKeys(keys);
  81002. var easingFunction = new BABYLON.SineEase();
  81003. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81004. animationInnerCircle.setEasingFunction(easingFunction);
  81005. torus.animations = [];
  81006. torus.animations.push(animationInnerCircle);
  81007. this._scene.beginAnimation(torus, 0, 60, true);
  81008. this._hideTeleportationTarget();
  81009. };
  81010. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  81011. this._teleportActive = true;
  81012. if (this._teleportationInitialized) {
  81013. this._teleportationTarget.isVisible = true;
  81014. if (this._isDefaultTeleportationTarget) {
  81015. this._teleportationTarget.getChildren()[0].isVisible = true;
  81016. }
  81017. }
  81018. };
  81019. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  81020. this._teleportActive = false;
  81021. if (this._teleportationInitialized) {
  81022. this._teleportationTarget.isVisible = false;
  81023. if (this._isDefaultTeleportationTarget) {
  81024. this._teleportationTarget.getChildren()[0].isVisible = false;
  81025. }
  81026. }
  81027. };
  81028. VRExperienceHelper.prototype._rotateCamera = function (right) {
  81029. var _this = this;
  81030. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81031. return;
  81032. }
  81033. if (right) {
  81034. this._rotationAngle++;
  81035. }
  81036. else {
  81037. this._rotationAngle--;
  81038. }
  81039. this.currentVRCamera.animations = [];
  81040. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  81041. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81042. var animationRotationKeys = [];
  81043. animationRotationKeys.push({
  81044. frame: 0,
  81045. value: this.currentVRCamera.rotationQuaternion
  81046. });
  81047. animationRotationKeys.push({
  81048. frame: 6,
  81049. value: target
  81050. });
  81051. animationRotation.setKeys(animationRotationKeys);
  81052. animationRotation.setEasingFunction(this._circleEase);
  81053. this.currentVRCamera.animations.push(animationRotation);
  81054. this._postProcessMove.animations = [];
  81055. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81056. var vignetteWeightKeys = [];
  81057. vignetteWeightKeys.push({
  81058. frame: 0,
  81059. value: 0
  81060. });
  81061. vignetteWeightKeys.push({
  81062. frame: 3,
  81063. value: 4
  81064. });
  81065. vignetteWeightKeys.push({
  81066. frame: 6,
  81067. value: 0
  81068. });
  81069. animationPP.setKeys(vignetteWeightKeys);
  81070. animationPP.setEasingFunction(this._circleEase);
  81071. this._postProcessMove.animations.push(animationPP);
  81072. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81073. var vignetteStretchKeys = [];
  81074. vignetteStretchKeys.push({
  81075. frame: 0,
  81076. value: 0
  81077. });
  81078. vignetteStretchKeys.push({
  81079. frame: 3,
  81080. value: 10
  81081. });
  81082. vignetteStretchKeys.push({
  81083. frame: 6,
  81084. value: 0
  81085. });
  81086. animationPP2.setKeys(vignetteStretchKeys);
  81087. animationPP2.setEasingFunction(this._circleEase);
  81088. this._postProcessMove.animations.push(animationPP2);
  81089. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81090. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81091. this._postProcessMove.samples = 4;
  81092. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81093. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  81094. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81095. });
  81096. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  81097. };
  81098. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  81099. if (hit.pickedPoint) {
  81100. if (gazer._teleportationRequestInitiated) {
  81101. this._displayTeleportationTarget();
  81102. this._haloCenter.copyFrom(hit.pickedPoint);
  81103. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  81104. }
  81105. var pickNormal = hit.getNormal(true, false);
  81106. if (pickNormal) {
  81107. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81108. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81109. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  81110. }
  81111. this._teleportationTarget.position.y += 0.1;
  81112. }
  81113. };
  81114. VRExperienceHelper.prototype._teleportCamera = function (location) {
  81115. var _this = this;
  81116. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81117. return;
  81118. }
  81119. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81120. // offset of the headset from the anchor.
  81121. if (this.webVRCamera.leftCamera) {
  81122. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81123. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81124. location.subtractToRef(this._workingVector, this._workingVector);
  81125. }
  81126. else {
  81127. this._workingVector.copyFrom(location);
  81128. }
  81129. // Add height to account for user's height offset
  81130. if (this.isInVRMode) {
  81131. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81132. }
  81133. else {
  81134. this._workingVector.y += this._defaultHeight;
  81135. }
  81136. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81137. // Create animation from the camera's position to the new location
  81138. this.currentVRCamera.animations = [];
  81139. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81140. var animationCameraTeleportationKeys = [{
  81141. frame: 0,
  81142. value: this.currentVRCamera.position
  81143. },
  81144. {
  81145. frame: 11,
  81146. value: this._workingVector
  81147. }
  81148. ];
  81149. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81150. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81151. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81152. this._postProcessMove.animations = [];
  81153. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81154. var vignetteWeightKeys = [];
  81155. vignetteWeightKeys.push({
  81156. frame: 0,
  81157. value: 0
  81158. });
  81159. vignetteWeightKeys.push({
  81160. frame: 5,
  81161. value: 8
  81162. });
  81163. vignetteWeightKeys.push({
  81164. frame: 11,
  81165. value: 0
  81166. });
  81167. animationPP.setKeys(vignetteWeightKeys);
  81168. this._postProcessMove.animations.push(animationPP);
  81169. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81170. var vignetteStretchKeys = [];
  81171. vignetteStretchKeys.push({
  81172. frame: 0,
  81173. value: 0
  81174. });
  81175. vignetteStretchKeys.push({
  81176. frame: 5,
  81177. value: 10
  81178. });
  81179. vignetteStretchKeys.push({
  81180. frame: 11,
  81181. value: 0
  81182. });
  81183. animationPP2.setKeys(vignetteStretchKeys);
  81184. this._postProcessMove.animations.push(animationPP2);
  81185. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81186. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81187. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81188. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81189. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81190. });
  81191. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81192. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81193. });
  81194. this._hideTeleportationTarget();
  81195. };
  81196. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  81197. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81198. return;
  81199. }
  81200. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  81201. // Moving the gazeTracker on the mesh face targetted
  81202. if (hit && hit.pickedPoint) {
  81203. if (this._displayGaze) {
  81204. var multiplier = 1;
  81205. gazer._gazeTracker.isVisible = true;
  81206. if (gazer._isActionableMesh) {
  81207. multiplier = 3;
  81208. }
  81209. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  81210. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  81211. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  81212. var pickNormal = hit.getNormal();
  81213. // To avoid z-fighting
  81214. var deltaFighting = 0.002;
  81215. if (pickNormal) {
  81216. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81217. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81218. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  81219. }
  81220. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  81221. if (gazer._gazeTracker.position.x < 0) {
  81222. gazer._gazeTracker.position.x += deltaFighting;
  81223. }
  81224. else {
  81225. gazer._gazeTracker.position.x -= deltaFighting;
  81226. }
  81227. if (gazer._gazeTracker.position.y < 0) {
  81228. gazer._gazeTracker.position.y += deltaFighting;
  81229. }
  81230. else {
  81231. gazer._gazeTracker.position.y -= deltaFighting;
  81232. }
  81233. if (gazer._gazeTracker.position.z < 0) {
  81234. gazer._gazeTracker.position.z += deltaFighting;
  81235. }
  81236. else {
  81237. gazer._gazeTracker.position.z -= deltaFighting;
  81238. }
  81239. }
  81240. // Changing the size of the laser pointer based on the distance from the targetted point
  81241. gazer._updatePointerDistance(hit.distance);
  81242. }
  81243. else {
  81244. gazer._gazeTracker.isVisible = false;
  81245. }
  81246. if (hit && hit.pickedMesh) {
  81247. gazer._currentHit = hit;
  81248. if (gazer._pointerDownOnMeshAsked) {
  81249. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  81250. }
  81251. // The object selected is the floor, we're in a teleportation scenario
  81252. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81253. // Moving the teleportation area to this targetted point
  81254. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81255. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  81256. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81257. }
  81258. gazer._currentMeshSelected = null;
  81259. if (gazer._teleportationRequestInitiated) {
  81260. this._moveTeleportationSelectorTo(hit, gazer);
  81261. }
  81262. return;
  81263. }
  81264. // If not, we're in a selection scenario
  81265. //this._teleportationAllowed = false;
  81266. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  81267. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81268. this.onNewMeshPicked.notifyObservers(hit);
  81269. gazer._currentMeshSelected = hit.pickedMesh;
  81270. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81271. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81272. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81273. gazer._isActionableMesh = true;
  81274. }
  81275. else {
  81276. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81277. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81278. gazer._isActionableMesh = false;
  81279. }
  81280. try {
  81281. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  81282. }
  81283. catch (err) {
  81284. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81285. }
  81286. }
  81287. else {
  81288. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81289. gazer._currentMeshSelected = null;
  81290. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81291. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81292. }
  81293. }
  81294. }
  81295. else {
  81296. gazer._currentHit = null;
  81297. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  81298. gazer._currentMeshSelected = null;
  81299. //this._teleportationAllowed = false;
  81300. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81301. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81302. }
  81303. };
  81304. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  81305. if (mesh) {
  81306. this.onSelectedMeshUnselected.notifyObservers(mesh);
  81307. }
  81308. };
  81309. /**
  81310. * Sets the color of the laser ray from the vr controllers.
  81311. * @param color new color for the ray.
  81312. */
  81313. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81314. if (this.leftController) {
  81315. this.leftController._setLaserPointerColor(color);
  81316. }
  81317. if (this.rightController) {
  81318. this.rightController._setLaserPointerColor(color);
  81319. }
  81320. };
  81321. /**
  81322. * Sets the color of the ray from the vr headsets gaze.
  81323. * @param color new color for the ray.
  81324. */
  81325. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81326. if (!this._cameraGazer._gazeTracker.material) {
  81327. return;
  81328. }
  81329. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  81330. if (this.leftController) {
  81331. this.leftController._gazeTracker.material.emissiveColor = color;
  81332. }
  81333. if (this.rightController) {
  81334. this.rightController._gazeTracker.material.emissiveColor = color;
  81335. }
  81336. };
  81337. /**
  81338. * Exits VR and disposes of the vr experience helper
  81339. */
  81340. VRExperienceHelper.prototype.dispose = function () {
  81341. if (this.isInVRMode) {
  81342. this.exitVR();
  81343. }
  81344. if (this._postProcessMove) {
  81345. this._postProcessMove.dispose();
  81346. }
  81347. if (this._webVRCamera) {
  81348. this._webVRCamera.dispose();
  81349. }
  81350. if (this._vrDeviceOrientationCamera) {
  81351. this._vrDeviceOrientationCamera.dispose();
  81352. }
  81353. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81354. document.body.removeChild(this._btnVR);
  81355. }
  81356. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81357. this._deviceOrientationCamera.dispose();
  81358. }
  81359. if (this._cameraGazer) {
  81360. this._cameraGazer.dispose();
  81361. }
  81362. if (this.leftController) {
  81363. this.leftController.dispose();
  81364. }
  81365. if (this.rightController) {
  81366. this.rightController.dispose();
  81367. }
  81368. if (this._teleportationTarget) {
  81369. this._teleportationTarget.dispose();
  81370. }
  81371. this._floorMeshesCollection = [];
  81372. document.removeEventListener("keydown", this._onKeyDown);
  81373. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81374. window.removeEventListener("resize", this._onResize);
  81375. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81376. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81377. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81378. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81379. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81380. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81381. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81382. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81383. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81384. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81385. this._scene.unregisterBeforeRender(this.beforeRender);
  81386. };
  81387. /**
  81388. * Gets the name of the VRExperienceHelper class
  81389. * @returns "VRExperienceHelper"
  81390. */
  81391. VRExperienceHelper.prototype.getClassName = function () {
  81392. return "VRExperienceHelper";
  81393. };
  81394. return VRExperienceHelper;
  81395. }());
  81396. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81397. })(BABYLON || (BABYLON = {}));
  81398. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81399. // Mainly based on these 2 articles :
  81400. // 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
  81401. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81402. var BABYLON;
  81403. (function (BABYLON) {
  81404. var JoystickAxis;
  81405. (function (JoystickAxis) {
  81406. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81407. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81408. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81409. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81410. var VirtualJoystick = /** @class */ (function () {
  81411. function VirtualJoystick(leftJoystick) {
  81412. var _this = this;
  81413. if (leftJoystick) {
  81414. this._leftJoystick = true;
  81415. }
  81416. else {
  81417. this._leftJoystick = false;
  81418. }
  81419. VirtualJoystick._globalJoystickIndex++;
  81420. // By default left & right arrow keys are moving the X
  81421. // and up & down keys are moving the Y
  81422. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81423. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81424. this.reverseLeftRight = false;
  81425. this.reverseUpDown = false;
  81426. // collections of pointers
  81427. this._touches = new BABYLON.StringDictionary();
  81428. this.deltaPosition = BABYLON.Vector3.Zero();
  81429. this._joystickSensibility = 25;
  81430. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81431. this._onResize = function (evt) {
  81432. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81433. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81434. if (VirtualJoystick.vjCanvas) {
  81435. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81436. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81437. }
  81438. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81439. };
  81440. // injecting a canvas element on top of the canvas 3D game
  81441. if (!VirtualJoystick.vjCanvas) {
  81442. window.addEventListener("resize", this._onResize, false);
  81443. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81444. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81445. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81446. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81447. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81448. VirtualJoystick.vjCanvas.style.width = "100%";
  81449. VirtualJoystick.vjCanvas.style.height = "100%";
  81450. VirtualJoystick.vjCanvas.style.position = "absolute";
  81451. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81452. VirtualJoystick.vjCanvas.style.top = "0px";
  81453. VirtualJoystick.vjCanvas.style.left = "0px";
  81454. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81455. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81456. // Support for jQuery PEP polyfill
  81457. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81458. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81459. if (!context) {
  81460. throw new Error("Unable to create canvas for virtual joystick");
  81461. }
  81462. VirtualJoystick.vjCanvasContext = context;
  81463. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81464. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81465. document.body.appendChild(VirtualJoystick.vjCanvas);
  81466. }
  81467. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81468. this.pressed = false;
  81469. // default joystick color
  81470. this._joystickColor = "cyan";
  81471. this._joystickPointerID = -1;
  81472. // current joystick position
  81473. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81474. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81475. // origin joystick position
  81476. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81477. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81478. this._onPointerDownHandlerRef = function (evt) {
  81479. _this._onPointerDown(evt);
  81480. };
  81481. this._onPointerMoveHandlerRef = function (evt) {
  81482. _this._onPointerMove(evt);
  81483. };
  81484. this._onPointerUpHandlerRef = function (evt) {
  81485. _this._onPointerUp(evt);
  81486. };
  81487. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81488. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81489. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81490. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81491. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81492. evt.preventDefault(); // Disables system menu
  81493. }, false);
  81494. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81495. }
  81496. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81497. this._joystickSensibility = newJoystickSensibility;
  81498. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81499. };
  81500. VirtualJoystick.prototype._onPointerDown = function (e) {
  81501. var positionOnScreenCondition;
  81502. e.preventDefault();
  81503. if (this._leftJoystick === true) {
  81504. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81505. }
  81506. else {
  81507. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81508. }
  81509. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81510. // First contact will be dedicated to the virtual joystick
  81511. this._joystickPointerID = e.pointerId;
  81512. this._joystickPointerStartPos.x = e.clientX;
  81513. this._joystickPointerStartPos.y = e.clientY;
  81514. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81515. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81516. this._deltaJoystickVector.x = 0;
  81517. this._deltaJoystickVector.y = 0;
  81518. this.pressed = true;
  81519. this._touches.add(e.pointerId.toString(), e);
  81520. }
  81521. else {
  81522. // You can only trigger the action buttons with a joystick declared
  81523. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81524. this._action();
  81525. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81526. }
  81527. }
  81528. };
  81529. VirtualJoystick.prototype._onPointerMove = function (e) {
  81530. // If the current pointer is the one associated to the joystick (first touch contact)
  81531. if (this._joystickPointerID == e.pointerId) {
  81532. this._joystickPointerPos.x = e.clientX;
  81533. this._joystickPointerPos.y = e.clientY;
  81534. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81535. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81536. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81537. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81538. switch (this._axisTargetedByLeftAndRight) {
  81539. case JoystickAxis.X:
  81540. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81541. break;
  81542. case JoystickAxis.Y:
  81543. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81544. break;
  81545. case JoystickAxis.Z:
  81546. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81547. break;
  81548. }
  81549. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81550. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81551. switch (this._axisTargetedByUpAndDown) {
  81552. case JoystickAxis.X:
  81553. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81554. break;
  81555. case JoystickAxis.Y:
  81556. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81557. break;
  81558. case JoystickAxis.Z:
  81559. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81560. break;
  81561. }
  81562. }
  81563. else {
  81564. var data = this._touches.get(e.pointerId.toString());
  81565. if (data) {
  81566. data.x = e.clientX;
  81567. data.y = e.clientY;
  81568. }
  81569. }
  81570. };
  81571. VirtualJoystick.prototype._onPointerUp = function (e) {
  81572. if (this._joystickPointerID == e.pointerId) {
  81573. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81574. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81575. this._joystickPointerID = -1;
  81576. this.pressed = false;
  81577. }
  81578. else {
  81579. var touch = this._touches.get(e.pointerId.toString());
  81580. if (touch) {
  81581. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81582. }
  81583. }
  81584. this._deltaJoystickVector.x = 0;
  81585. this._deltaJoystickVector.y = 0;
  81586. this._touches.remove(e.pointerId.toString());
  81587. };
  81588. /**
  81589. * Change the color of the virtual joystick
  81590. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81591. */
  81592. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81593. this._joystickColor = newColor;
  81594. };
  81595. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81596. this._action = action;
  81597. };
  81598. // Define which axis you'd like to control for left & right
  81599. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81600. switch (axis) {
  81601. case JoystickAxis.X:
  81602. case JoystickAxis.Y:
  81603. case JoystickAxis.Z:
  81604. this._axisTargetedByLeftAndRight = axis;
  81605. break;
  81606. default:
  81607. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81608. break;
  81609. }
  81610. };
  81611. // Define which axis you'd like to control for up & down
  81612. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81613. switch (axis) {
  81614. case JoystickAxis.X:
  81615. case JoystickAxis.Y:
  81616. case JoystickAxis.Z:
  81617. this._axisTargetedByUpAndDown = axis;
  81618. break;
  81619. default:
  81620. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81621. break;
  81622. }
  81623. };
  81624. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81625. var _this = this;
  81626. if (this.pressed) {
  81627. this._touches.forEach(function (key, touch) {
  81628. if (touch.pointerId === _this._joystickPointerID) {
  81629. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81630. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81631. VirtualJoystick.vjCanvasContext.beginPath();
  81632. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81633. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81634. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81635. VirtualJoystick.vjCanvasContext.stroke();
  81636. VirtualJoystick.vjCanvasContext.closePath();
  81637. VirtualJoystick.vjCanvasContext.beginPath();
  81638. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81639. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81640. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81641. VirtualJoystick.vjCanvasContext.stroke();
  81642. VirtualJoystick.vjCanvasContext.closePath();
  81643. VirtualJoystick.vjCanvasContext.beginPath();
  81644. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81645. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81646. VirtualJoystick.vjCanvasContext.stroke();
  81647. VirtualJoystick.vjCanvasContext.closePath();
  81648. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81649. }
  81650. else {
  81651. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81652. VirtualJoystick.vjCanvasContext.beginPath();
  81653. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81654. VirtualJoystick.vjCanvasContext.beginPath();
  81655. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81656. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81657. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81658. VirtualJoystick.vjCanvasContext.stroke();
  81659. VirtualJoystick.vjCanvasContext.closePath();
  81660. touch.prevX = touch.x;
  81661. touch.prevY = touch.y;
  81662. }
  81663. ;
  81664. });
  81665. }
  81666. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81667. };
  81668. VirtualJoystick.prototype.releaseCanvas = function () {
  81669. if (VirtualJoystick.vjCanvas) {
  81670. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81671. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81672. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81673. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81674. window.removeEventListener("resize", this._onResize);
  81675. document.body.removeChild(VirtualJoystick.vjCanvas);
  81676. VirtualJoystick.vjCanvas = null;
  81677. }
  81678. };
  81679. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81680. VirtualJoystick._globalJoystickIndex = 0;
  81681. return VirtualJoystick;
  81682. }());
  81683. BABYLON.VirtualJoystick = VirtualJoystick;
  81684. })(BABYLON || (BABYLON = {}));
  81685. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81686. var BABYLON;
  81687. (function (BABYLON) {
  81688. // We're mainly based on the logic defined into the FreeCamera code
  81689. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81690. __extends(VirtualJoysticksCamera, _super);
  81691. function VirtualJoysticksCamera(name, position, scene) {
  81692. var _this = _super.call(this, name, position, scene) || this;
  81693. _this.inputs.addVirtualJoystick();
  81694. return _this;
  81695. }
  81696. VirtualJoysticksCamera.prototype.getClassName = function () {
  81697. return "VirtualJoysticksCamera";
  81698. };
  81699. return VirtualJoysticksCamera;
  81700. }(BABYLON.FreeCamera));
  81701. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81702. })(BABYLON || (BABYLON = {}));
  81703. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81704. var BABYLON;
  81705. (function (BABYLON) {
  81706. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81707. function FreeCameraVirtualJoystickInput() {
  81708. }
  81709. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81710. return this._leftjoystick;
  81711. };
  81712. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81713. return this._rightjoystick;
  81714. };
  81715. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81716. if (this._leftjoystick) {
  81717. var camera = this.camera;
  81718. var speed = camera._computeLocalCameraSpeed() * 50;
  81719. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81720. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81721. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81722. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81723. if (!this._leftjoystick.pressed) {
  81724. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81725. }
  81726. if (!this._rightjoystick.pressed) {
  81727. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81728. }
  81729. }
  81730. };
  81731. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81732. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81733. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81734. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81735. this._leftjoystick.setJoystickSensibility(0.15);
  81736. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81737. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81738. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81739. this._rightjoystick.reverseUpDown = true;
  81740. this._rightjoystick.setJoystickSensibility(0.05);
  81741. this._rightjoystick.setJoystickColor("yellow");
  81742. };
  81743. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81744. this._leftjoystick.releaseCanvas();
  81745. this._rightjoystick.releaseCanvas();
  81746. };
  81747. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81748. return "FreeCameraVirtualJoystickInput";
  81749. };
  81750. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81751. return "virtualJoystick";
  81752. };
  81753. return FreeCameraVirtualJoystickInput;
  81754. }());
  81755. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81756. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81757. })(BABYLON || (BABYLON = {}));
  81758. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81759. var BABYLON;
  81760. (function (BABYLON) {
  81761. var SimplificationSettings = /** @class */ (function () {
  81762. function SimplificationSettings(quality, distance, optimizeMesh) {
  81763. this.quality = quality;
  81764. this.distance = distance;
  81765. this.optimizeMesh = optimizeMesh;
  81766. }
  81767. return SimplificationSettings;
  81768. }());
  81769. BABYLON.SimplificationSettings = SimplificationSettings;
  81770. var SimplificationQueue = /** @class */ (function () {
  81771. function SimplificationQueue() {
  81772. this.running = false;
  81773. this._simplificationArray = [];
  81774. }
  81775. SimplificationQueue.prototype.addTask = function (task) {
  81776. this._simplificationArray.push(task);
  81777. };
  81778. SimplificationQueue.prototype.executeNext = function () {
  81779. var task = this._simplificationArray.pop();
  81780. if (task) {
  81781. this.running = true;
  81782. this.runSimplification(task);
  81783. }
  81784. else {
  81785. this.running = false;
  81786. }
  81787. };
  81788. SimplificationQueue.prototype.runSimplification = function (task) {
  81789. var _this = this;
  81790. if (task.parallelProcessing) {
  81791. //parallel simplifier
  81792. task.settings.forEach(function (setting) {
  81793. var simplifier = _this.getSimplifier(task);
  81794. simplifier.simplify(setting, function (newMesh) {
  81795. task.mesh.addLODLevel(setting.distance, newMesh);
  81796. newMesh.isVisible = true;
  81797. //check if it is the last
  81798. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81799. //all done, run the success callback.
  81800. task.successCallback();
  81801. }
  81802. _this.executeNext();
  81803. });
  81804. });
  81805. }
  81806. else {
  81807. //single simplifier.
  81808. var simplifier = this.getSimplifier(task);
  81809. var runDecimation = function (setting, callback) {
  81810. simplifier.simplify(setting, function (newMesh) {
  81811. task.mesh.addLODLevel(setting.distance, newMesh);
  81812. newMesh.isVisible = true;
  81813. //run the next quality level
  81814. callback();
  81815. });
  81816. };
  81817. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81818. runDecimation(task.settings[loop.index], function () {
  81819. loop.executeNext();
  81820. });
  81821. }, function () {
  81822. //execution ended, run the success callback.
  81823. if (task.successCallback) {
  81824. task.successCallback();
  81825. }
  81826. _this.executeNext();
  81827. });
  81828. }
  81829. };
  81830. SimplificationQueue.prototype.getSimplifier = function (task) {
  81831. switch (task.simplificationType) {
  81832. case SimplificationType.QUADRATIC:
  81833. default:
  81834. return new QuadraticErrorSimplification(task.mesh);
  81835. }
  81836. };
  81837. return SimplificationQueue;
  81838. }());
  81839. BABYLON.SimplificationQueue = SimplificationQueue;
  81840. /**
  81841. * The implemented types of simplification.
  81842. * At the moment only Quadratic Error Decimation is implemented.
  81843. */
  81844. var SimplificationType;
  81845. (function (SimplificationType) {
  81846. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81847. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81848. var DecimationTriangle = /** @class */ (function () {
  81849. function DecimationTriangle(vertices) {
  81850. this.vertices = vertices;
  81851. this.error = new Array(4);
  81852. this.deleted = false;
  81853. this.isDirty = false;
  81854. this.deletePending = false;
  81855. this.borderFactor = 0;
  81856. }
  81857. return DecimationTriangle;
  81858. }());
  81859. BABYLON.DecimationTriangle = DecimationTriangle;
  81860. var DecimationVertex = /** @class */ (function () {
  81861. function DecimationVertex(position, id) {
  81862. this.position = position;
  81863. this.id = id;
  81864. this.isBorder = true;
  81865. this.q = new QuadraticMatrix();
  81866. this.triangleCount = 0;
  81867. this.triangleStart = 0;
  81868. this.originalOffsets = [];
  81869. }
  81870. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81871. this.position.copyFrom(newPosition);
  81872. };
  81873. return DecimationVertex;
  81874. }());
  81875. BABYLON.DecimationVertex = DecimationVertex;
  81876. var QuadraticMatrix = /** @class */ (function () {
  81877. function QuadraticMatrix(data) {
  81878. this.data = new Array(10);
  81879. for (var i = 0; i < 10; ++i) {
  81880. if (data && data[i]) {
  81881. this.data[i] = data[i];
  81882. }
  81883. else {
  81884. this.data[i] = 0;
  81885. }
  81886. }
  81887. }
  81888. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81889. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81890. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81891. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81892. return det;
  81893. };
  81894. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81895. for (var i = 0; i < 10; ++i) {
  81896. this.data[i] += matrix.data[i];
  81897. }
  81898. };
  81899. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81900. for (var i = 0; i < 10; ++i) {
  81901. this.data[i] += data[i];
  81902. }
  81903. };
  81904. QuadraticMatrix.prototype.add = function (matrix) {
  81905. var m = new QuadraticMatrix();
  81906. for (var i = 0; i < 10; ++i) {
  81907. m.data[i] = this.data[i] + matrix.data[i];
  81908. }
  81909. return m;
  81910. };
  81911. QuadraticMatrix.FromData = function (a, b, c, d) {
  81912. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81913. };
  81914. //returning an array to avoid garbage collection
  81915. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81916. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81917. };
  81918. return QuadraticMatrix;
  81919. }());
  81920. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81921. var Reference = /** @class */ (function () {
  81922. function Reference(vertexId, triangleId) {
  81923. this.vertexId = vertexId;
  81924. this.triangleId = triangleId;
  81925. }
  81926. return Reference;
  81927. }());
  81928. BABYLON.Reference = Reference;
  81929. /**
  81930. * An implementation of the Quadratic Error simplification algorithm.
  81931. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81932. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81933. * @author RaananW
  81934. */
  81935. var QuadraticErrorSimplification = /** @class */ (function () {
  81936. function QuadraticErrorSimplification(_mesh) {
  81937. this._mesh = _mesh;
  81938. this.syncIterations = 5000;
  81939. this.aggressiveness = 7;
  81940. this.decimationIterations = 100;
  81941. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81942. }
  81943. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81944. var _this = this;
  81945. this.initDecimatedMesh();
  81946. //iterating through the submeshes array, one after the other.
  81947. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81948. _this.initWithMesh(loop.index, function () {
  81949. _this.runDecimation(settings, loop.index, function () {
  81950. loop.executeNext();
  81951. });
  81952. }, settings.optimizeMesh);
  81953. }, function () {
  81954. setTimeout(function () {
  81955. successCallback(_this._reconstructedMesh);
  81956. }, 0);
  81957. });
  81958. };
  81959. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81960. var _this = this;
  81961. var targetCount = ~~(this.triangles.length * settings.quality);
  81962. var deletedTriangles = 0;
  81963. var triangleCount = this.triangles.length;
  81964. var iterationFunction = function (iteration, callback) {
  81965. setTimeout(function () {
  81966. if (iteration % 5 === 0) {
  81967. _this.updateMesh(iteration === 0);
  81968. }
  81969. for (var i = 0; i < _this.triangles.length; ++i) {
  81970. _this.triangles[i].isDirty = false;
  81971. }
  81972. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81973. var trianglesIterator = function (i) {
  81974. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  81975. var t = _this.triangles[tIdx];
  81976. if (!t)
  81977. return;
  81978. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  81979. return;
  81980. }
  81981. for (var j = 0; j < 3; ++j) {
  81982. if (t.error[j] < threshold) {
  81983. var deleted0 = [];
  81984. var deleted1 = [];
  81985. var v0 = t.vertices[j];
  81986. var v1 = t.vertices[(j + 1) % 3];
  81987. if (v0.isBorder || v1.isBorder)
  81988. continue;
  81989. var p = BABYLON.Vector3.Zero();
  81990. var n = BABYLON.Vector3.Zero();
  81991. var uv = BABYLON.Vector2.Zero();
  81992. var color = new BABYLON.Color4(0, 0, 0, 1);
  81993. _this.calculateError(v0, v1, p, n, uv, color);
  81994. var delTr = new Array();
  81995. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  81996. continue;
  81997. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  81998. continue;
  81999. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  82000. continue;
  82001. var uniqueArray = new Array();
  82002. delTr.forEach(function (deletedT) {
  82003. if (uniqueArray.indexOf(deletedT) === -1) {
  82004. deletedT.deletePending = true;
  82005. uniqueArray.push(deletedT);
  82006. }
  82007. });
  82008. if (uniqueArray.length % 2 !== 0) {
  82009. continue;
  82010. }
  82011. v0.q = v1.q.add(v0.q);
  82012. v0.updatePosition(p);
  82013. var tStart = _this.references.length;
  82014. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  82015. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  82016. var tCount = _this.references.length - tStart;
  82017. if (tCount <= v0.triangleCount) {
  82018. if (tCount) {
  82019. for (var c = 0; c < tCount; c++) {
  82020. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  82021. }
  82022. }
  82023. }
  82024. else {
  82025. v0.triangleStart = tStart;
  82026. }
  82027. v0.triangleCount = tCount;
  82028. break;
  82029. }
  82030. }
  82031. };
  82032. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  82033. }, 0);
  82034. };
  82035. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  82036. if (triangleCount - deletedTriangles <= targetCount)
  82037. loop.breakLoop();
  82038. else {
  82039. iterationFunction(loop.index, function () {
  82040. loop.executeNext();
  82041. });
  82042. }
  82043. }, function () {
  82044. setTimeout(function () {
  82045. //reconstruct this part of the mesh
  82046. _this.reconstructMesh(submeshIndex);
  82047. successCallback();
  82048. }, 0);
  82049. });
  82050. };
  82051. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  82052. var _this = this;
  82053. this.vertices = [];
  82054. this.triangles = [];
  82055. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82056. var indices = this._mesh.getIndices();
  82057. var submesh = this._mesh.subMeshes[submeshIndex];
  82058. var findInVertices = function (positionToSearch) {
  82059. if (optimizeMesh) {
  82060. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  82061. if (_this.vertices[ii].position.equals(positionToSearch)) {
  82062. return _this.vertices[ii];
  82063. }
  82064. }
  82065. }
  82066. return null;
  82067. };
  82068. var vertexReferences = [];
  82069. var vertexInit = function (i) {
  82070. if (!positionData) {
  82071. return;
  82072. }
  82073. var offset = i + submesh.verticesStart;
  82074. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  82075. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  82076. vertex.originalOffsets.push(offset);
  82077. if (vertex.id === _this.vertices.length) {
  82078. _this.vertices.push(vertex);
  82079. }
  82080. vertexReferences.push(vertex.id);
  82081. };
  82082. //var totalVertices = mesh.getTotalVertices();
  82083. var totalVertices = submesh.verticesCount;
  82084. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  82085. var indicesInit = function (i) {
  82086. if (!indices) {
  82087. return;
  82088. }
  82089. var offset = (submesh.indexStart / 3) + i;
  82090. var pos = (offset * 3);
  82091. var i0 = indices[pos + 0];
  82092. var i1 = indices[pos + 1];
  82093. var i2 = indices[pos + 2];
  82094. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  82095. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  82096. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  82097. var triangle = new DecimationTriangle([v0, v1, v2]);
  82098. triangle.originalOffset = pos;
  82099. _this.triangles.push(triangle);
  82100. };
  82101. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  82102. _this.init(callback);
  82103. });
  82104. });
  82105. };
  82106. QuadraticErrorSimplification.prototype.init = function (callback) {
  82107. var _this = this;
  82108. var triangleInit1 = function (i) {
  82109. var t = _this.triangles[i];
  82110. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  82111. for (var j = 0; j < 3; j++) {
  82112. 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))));
  82113. }
  82114. };
  82115. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  82116. var triangleInit2 = function (i) {
  82117. var t = _this.triangles[i];
  82118. for (var j = 0; j < 3; ++j) {
  82119. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82120. }
  82121. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82122. };
  82123. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82124. callback();
  82125. });
  82126. });
  82127. };
  82128. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82129. var newTriangles = [];
  82130. var i;
  82131. for (i = 0; i < this.vertices.length; ++i) {
  82132. this.vertices[i].triangleCount = 0;
  82133. }
  82134. var t;
  82135. var j;
  82136. for (i = 0; i < this.triangles.length; ++i) {
  82137. if (!this.triangles[i].deleted) {
  82138. t = this.triangles[i];
  82139. for (j = 0; j < 3; ++j) {
  82140. t.vertices[j].triangleCount = 1;
  82141. }
  82142. newTriangles.push(t);
  82143. }
  82144. }
  82145. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82146. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82147. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82148. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82149. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82150. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82151. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82152. var vertexCount = 0;
  82153. for (i = 0; i < this.vertices.length; ++i) {
  82154. var vertex = this.vertices[i];
  82155. vertex.id = vertexCount;
  82156. if (vertex.triangleCount) {
  82157. vertex.originalOffsets.forEach(function (originalOffset) {
  82158. if (!normalData) {
  82159. return;
  82160. }
  82161. newPositionData.push(vertex.position.x);
  82162. newPositionData.push(vertex.position.y);
  82163. newPositionData.push(vertex.position.z);
  82164. newNormalData.push(normalData[originalOffset * 3]);
  82165. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82166. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82167. if (uvs && uvs.length) {
  82168. newUVsData.push(uvs[(originalOffset * 2)]);
  82169. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82170. }
  82171. else if (colorsData && colorsData.length) {
  82172. newColorsData.push(colorsData[(originalOffset * 4)]);
  82173. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82174. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82175. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82176. }
  82177. ++vertexCount;
  82178. });
  82179. }
  82180. }
  82181. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82182. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82183. var submeshesArray = this._reconstructedMesh.subMeshes;
  82184. this._reconstructedMesh.subMeshes = [];
  82185. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82186. var originalIndices = this._mesh.getIndices();
  82187. for (i = 0; i < newTriangles.length; ++i) {
  82188. t = newTriangles[i]; //now get the new referencing point for each vertex
  82189. [0, 1, 2].forEach(function (idx) {
  82190. var id = originalIndices[t.originalOffset + idx];
  82191. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82192. if (offset < 0)
  82193. offset = 0;
  82194. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82195. });
  82196. }
  82197. //overwriting the old vertex buffers and indices.
  82198. this._reconstructedMesh.setIndices(newIndicesArray);
  82199. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82200. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82201. if (newUVsData.length > 0)
  82202. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82203. if (newColorsData.length > 0)
  82204. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82205. //create submesh
  82206. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82207. if (submeshIndex > 0) {
  82208. this._reconstructedMesh.subMeshes = [];
  82209. submeshesArray.forEach(function (submesh) {
  82210. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82211. });
  82212. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82213. }
  82214. };
  82215. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82216. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82217. this._reconstructedMesh.material = this._mesh.material;
  82218. this._reconstructedMesh.parent = this._mesh.parent;
  82219. this._reconstructedMesh.isVisible = false;
  82220. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82221. };
  82222. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82223. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82224. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82225. if (t.deleted)
  82226. continue;
  82227. var s = this.references[vertex1.triangleStart + i].vertexId;
  82228. var v1 = t.vertices[(s + 1) % 3];
  82229. var v2 = t.vertices[(s + 2) % 3];
  82230. if ((v1 === vertex2 || v2 === vertex2)) {
  82231. deletedArray[i] = true;
  82232. delTr.push(t);
  82233. continue;
  82234. }
  82235. var d1 = v1.position.subtract(point);
  82236. d1 = d1.normalize();
  82237. var d2 = v2.position.subtract(point);
  82238. d2 = d2.normalize();
  82239. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82240. return true;
  82241. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82242. deletedArray[i] = false;
  82243. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82244. return true;
  82245. }
  82246. return false;
  82247. };
  82248. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82249. var newDeleted = deletedTriangles;
  82250. for (var i = 0; i < vertex.triangleCount; ++i) {
  82251. var ref = this.references[vertex.triangleStart + i];
  82252. var t = this.triangles[ref.triangleId];
  82253. if (t.deleted)
  82254. continue;
  82255. if (deletedArray[i] && t.deletePending) {
  82256. t.deleted = true;
  82257. newDeleted++;
  82258. continue;
  82259. }
  82260. t.vertices[ref.vertexId] = origVertex;
  82261. t.isDirty = true;
  82262. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82263. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82264. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82265. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82266. this.references.push(ref);
  82267. }
  82268. return newDeleted;
  82269. };
  82270. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82271. for (var i = 0; i < this.vertices.length; ++i) {
  82272. var vCount = [];
  82273. var vId = [];
  82274. var v = this.vertices[i];
  82275. var j;
  82276. for (j = 0; j < v.triangleCount; ++j) {
  82277. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82278. for (var ii = 0; ii < 3; ii++) {
  82279. var ofs = 0;
  82280. var vv = triangle.vertices[ii];
  82281. while (ofs < vCount.length) {
  82282. if (vId[ofs] === vv.id)
  82283. break;
  82284. ++ofs;
  82285. }
  82286. if (ofs === vCount.length) {
  82287. vCount.push(1);
  82288. vId.push(vv.id);
  82289. }
  82290. else {
  82291. vCount[ofs]++;
  82292. }
  82293. }
  82294. }
  82295. for (j = 0; j < vCount.length; ++j) {
  82296. if (vCount[j] === 1) {
  82297. this.vertices[vId[j]].isBorder = true;
  82298. }
  82299. else {
  82300. this.vertices[vId[j]].isBorder = false;
  82301. }
  82302. }
  82303. }
  82304. };
  82305. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82306. if (identifyBorders === void 0) { identifyBorders = false; }
  82307. var i;
  82308. if (!identifyBorders) {
  82309. var newTrianglesVector = [];
  82310. for (i = 0; i < this.triangles.length; ++i) {
  82311. if (!this.triangles[i].deleted) {
  82312. newTrianglesVector.push(this.triangles[i]);
  82313. }
  82314. }
  82315. this.triangles = newTrianglesVector;
  82316. }
  82317. for (i = 0; i < this.vertices.length; ++i) {
  82318. this.vertices[i].triangleCount = 0;
  82319. this.vertices[i].triangleStart = 0;
  82320. }
  82321. var t;
  82322. var j;
  82323. var v;
  82324. for (i = 0; i < this.triangles.length; ++i) {
  82325. t = this.triangles[i];
  82326. for (j = 0; j < 3; ++j) {
  82327. v = t.vertices[j];
  82328. v.triangleCount++;
  82329. }
  82330. }
  82331. var tStart = 0;
  82332. for (i = 0; i < this.vertices.length; ++i) {
  82333. this.vertices[i].triangleStart = tStart;
  82334. tStart += this.vertices[i].triangleCount;
  82335. this.vertices[i].triangleCount = 0;
  82336. }
  82337. var newReferences = new Array(this.triangles.length * 3);
  82338. for (i = 0; i < this.triangles.length; ++i) {
  82339. t = this.triangles[i];
  82340. for (j = 0; j < 3; ++j) {
  82341. v = t.vertices[j];
  82342. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82343. v.triangleCount++;
  82344. }
  82345. }
  82346. this.references = newReferences;
  82347. if (identifyBorders) {
  82348. this.identifyBorder();
  82349. }
  82350. };
  82351. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82352. var x = point.x;
  82353. var y = point.y;
  82354. var z = point.z;
  82355. 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
  82356. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82357. };
  82358. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82359. var q = vertex1.q.add(vertex2.q);
  82360. var border = vertex1.isBorder && vertex2.isBorder;
  82361. var error = 0;
  82362. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82363. if (qDet !== 0 && !border) {
  82364. if (!pointResult) {
  82365. pointResult = BABYLON.Vector3.Zero();
  82366. }
  82367. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82368. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82369. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82370. error = this.vertexError(q, pointResult);
  82371. }
  82372. else {
  82373. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82374. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82375. var error1 = this.vertexError(q, vertex1.position);
  82376. var error2 = this.vertexError(q, vertex2.position);
  82377. var error3 = this.vertexError(q, p3);
  82378. error = Math.min(error1, error2, error3);
  82379. if (error === error1) {
  82380. if (pointResult) {
  82381. pointResult.copyFrom(vertex1.position);
  82382. }
  82383. }
  82384. else if (error === error2) {
  82385. if (pointResult) {
  82386. pointResult.copyFrom(vertex2.position);
  82387. }
  82388. }
  82389. else {
  82390. if (pointResult) {
  82391. pointResult.copyFrom(p3);
  82392. }
  82393. }
  82394. }
  82395. return error;
  82396. };
  82397. return QuadraticErrorSimplification;
  82398. }());
  82399. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82400. })(BABYLON || (BABYLON = {}));
  82401. //# sourceMappingURL=babylon.meshSimplification.js.map
  82402. var BABYLON;
  82403. (function (BABYLON) {
  82404. var MeshLODLevel = /** @class */ (function () {
  82405. function MeshLODLevel(distance, mesh) {
  82406. this.distance = distance;
  82407. this.mesh = mesh;
  82408. }
  82409. return MeshLODLevel;
  82410. }());
  82411. BABYLON.MeshLODLevel = MeshLODLevel;
  82412. })(BABYLON || (BABYLON = {}));
  82413. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82414. var BABYLON;
  82415. (function (BABYLON) {
  82416. /**
  82417. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82419. */
  82420. var SceneOptimization = /** @class */ (function () {
  82421. /**
  82422. * Creates the SceneOptimization object
  82423. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82424. * @param desc defines the description associated with the optimization
  82425. */
  82426. function SceneOptimization(
  82427. /**
  82428. * Defines the priority of this optimization (0 by default which means first in the list)
  82429. */
  82430. priority) {
  82431. if (priority === void 0) { priority = 0; }
  82432. this.priority = priority;
  82433. }
  82434. /**
  82435. * Gets a string describing the action executed by the current optimization
  82436. * @returns description string
  82437. */
  82438. SceneOptimization.prototype.getDescription = function () {
  82439. return "";
  82440. };
  82441. /**
  82442. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82443. * @param scene defines the current scene where to apply this optimization
  82444. * @param optimizer defines the current optimizer
  82445. * @returns true if everything that can be done was applied
  82446. */
  82447. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82448. return true;
  82449. };
  82450. ;
  82451. return SceneOptimization;
  82452. }());
  82453. BABYLON.SceneOptimization = SceneOptimization;
  82454. /**
  82455. * Defines an optimization used to reduce the size of render target textures
  82456. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82457. */
  82458. var TextureOptimization = /** @class */ (function (_super) {
  82459. __extends(TextureOptimization, _super);
  82460. /**
  82461. * Creates the TextureOptimization object
  82462. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82463. * @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
  82464. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82465. */
  82466. function TextureOptimization(
  82467. /**
  82468. * Defines the priority of this optimization (0 by default which means first in the list)
  82469. */
  82470. priority,
  82471. /**
  82472. * 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
  82473. */
  82474. maximumSize,
  82475. /**
  82476. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82477. */
  82478. step) {
  82479. if (priority === void 0) { priority = 0; }
  82480. if (maximumSize === void 0) { maximumSize = 1024; }
  82481. if (step === void 0) { step = 0.5; }
  82482. var _this = _super.call(this, priority) || this;
  82483. _this.priority = priority;
  82484. _this.maximumSize = maximumSize;
  82485. _this.step = step;
  82486. return _this;
  82487. }
  82488. /**
  82489. * Gets a string describing the action executed by the current optimization
  82490. * @returns description string
  82491. */
  82492. TextureOptimization.prototype.getDescription = function () {
  82493. return "Reducing render target texture size to " + this.maximumSize;
  82494. };
  82495. /**
  82496. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82497. * @param scene defines the current scene where to apply this optimization
  82498. * @param optimizer defines the current optimizer
  82499. * @returns true if everything that can be done was applied
  82500. */
  82501. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82502. var allDone = true;
  82503. for (var index = 0; index < scene.textures.length; index++) {
  82504. var texture = scene.textures[index];
  82505. if (!texture.canRescale || texture.getContext) {
  82506. continue;
  82507. }
  82508. var currentSize = texture.getSize();
  82509. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82510. if (maxDimension > this.maximumSize) {
  82511. texture.scale(this.step);
  82512. allDone = false;
  82513. }
  82514. }
  82515. return allDone;
  82516. };
  82517. return TextureOptimization;
  82518. }(SceneOptimization));
  82519. BABYLON.TextureOptimization = TextureOptimization;
  82520. /**
  82521. * Defines an optimization used to increase or decrease the rendering resolution
  82522. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82523. */
  82524. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82525. __extends(HardwareScalingOptimization, _super);
  82526. /**
  82527. * Creates the HardwareScalingOptimization object
  82528. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82529. * @param maximumScale defines the maximum scale to use (2 by default)
  82530. * @param step defines the step to use between two passes (0.5 by default)
  82531. */
  82532. function HardwareScalingOptimization(
  82533. /**
  82534. * Defines the priority of this optimization (0 by default which means first in the list)
  82535. */
  82536. priority,
  82537. /**
  82538. * Defines the maximum scale to use (2 by default)
  82539. */
  82540. maximumScale,
  82541. /**
  82542. * Defines the step to use between two passes (0.5 by default)
  82543. */
  82544. step) {
  82545. if (priority === void 0) { priority = 0; }
  82546. if (maximumScale === void 0) { maximumScale = 2; }
  82547. if (step === void 0) { step = 0.25; }
  82548. var _this = _super.call(this, priority) || this;
  82549. _this.priority = priority;
  82550. _this.maximumScale = maximumScale;
  82551. _this.step = step;
  82552. _this._currentScale = -1;
  82553. _this._directionOffset = 1;
  82554. return _this;
  82555. }
  82556. /**
  82557. * Gets a string describing the action executed by the current optimization
  82558. * @return description string
  82559. */
  82560. HardwareScalingOptimization.prototype.getDescription = function () {
  82561. return "Setting hardware scaling level to " + this._currentScale;
  82562. };
  82563. /**
  82564. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82565. * @param scene defines the current scene where to apply this optimization
  82566. * @param optimizer defines the current optimizer
  82567. * @returns true if everything that can be done was applied
  82568. */
  82569. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82570. if (this._currentScale === -1) {
  82571. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82572. if (this._currentScale > this.maximumScale) {
  82573. this._directionOffset = -1;
  82574. }
  82575. }
  82576. this._currentScale += this._directionOffset * this.step;
  82577. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82578. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82579. };
  82580. ;
  82581. return HardwareScalingOptimization;
  82582. }(SceneOptimization));
  82583. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82584. /**
  82585. * Defines an optimization used to remove shadows
  82586. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82587. */
  82588. var ShadowsOptimization = /** @class */ (function (_super) {
  82589. __extends(ShadowsOptimization, _super);
  82590. function ShadowsOptimization() {
  82591. return _super !== null && _super.apply(this, arguments) || this;
  82592. }
  82593. /**
  82594. * Gets a string describing the action executed by the current optimization
  82595. * @return description string
  82596. */
  82597. ShadowsOptimization.prototype.getDescription = function () {
  82598. return "Turning shadows on/off";
  82599. };
  82600. /**
  82601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82602. * @param scene defines the current scene where to apply this optimization
  82603. * @param optimizer defines the current optimizer
  82604. * @returns true if everything that can be done was applied
  82605. */
  82606. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82607. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82608. return true;
  82609. };
  82610. ;
  82611. return ShadowsOptimization;
  82612. }(SceneOptimization));
  82613. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82614. /**
  82615. * Defines an optimization used to turn post-processes off
  82616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82617. */
  82618. var PostProcessesOptimization = /** @class */ (function (_super) {
  82619. __extends(PostProcessesOptimization, _super);
  82620. function PostProcessesOptimization() {
  82621. return _super !== null && _super.apply(this, arguments) || this;
  82622. }
  82623. /**
  82624. * Gets a string describing the action executed by the current optimization
  82625. * @return description string
  82626. */
  82627. PostProcessesOptimization.prototype.getDescription = function () {
  82628. return "Turning post-processes on/off";
  82629. };
  82630. /**
  82631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82632. * @param scene defines the current scene where to apply this optimization
  82633. * @param optimizer defines the current optimizer
  82634. * @returns true if everything that can be done was applied
  82635. */
  82636. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82637. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82638. return true;
  82639. };
  82640. ;
  82641. return PostProcessesOptimization;
  82642. }(SceneOptimization));
  82643. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82644. /**
  82645. * Defines an optimization used to turn lens flares off
  82646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82647. */
  82648. var LensFlaresOptimization = /** @class */ (function (_super) {
  82649. __extends(LensFlaresOptimization, _super);
  82650. function LensFlaresOptimization() {
  82651. return _super !== null && _super.apply(this, arguments) || this;
  82652. }
  82653. /**
  82654. * Gets a string describing the action executed by the current optimization
  82655. * @return description string
  82656. */
  82657. LensFlaresOptimization.prototype.getDescription = function () {
  82658. return "Turning lens flares on/off";
  82659. };
  82660. /**
  82661. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82662. * @param scene defines the current scene where to apply this optimization
  82663. * @param optimizer defines the current optimizer
  82664. * @returns true if everything that can be done was applied
  82665. */
  82666. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82667. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82668. return true;
  82669. };
  82670. ;
  82671. return LensFlaresOptimization;
  82672. }(SceneOptimization));
  82673. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82674. /**
  82675. * Defines an optimization based on user defined callback.
  82676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82677. */
  82678. var CustomOptimization = /** @class */ (function (_super) {
  82679. __extends(CustomOptimization, _super);
  82680. function CustomOptimization() {
  82681. return _super !== null && _super.apply(this, arguments) || this;
  82682. }
  82683. /**
  82684. * Gets a string describing the action executed by the current optimization
  82685. * @returns description string
  82686. */
  82687. CustomOptimization.prototype.getDescription = function () {
  82688. if (this.onGetDescription) {
  82689. return this.onGetDescription();
  82690. }
  82691. return "Running user defined callback";
  82692. };
  82693. /**
  82694. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82695. * @param scene defines the current scene where to apply this optimization
  82696. * @param optimizer defines the current optimizer
  82697. * @returns true if everything that can be done was applied
  82698. */
  82699. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82700. if (this.onApply) {
  82701. return this.onApply(scene, optimizer);
  82702. }
  82703. return true;
  82704. };
  82705. ;
  82706. return CustomOptimization;
  82707. }(SceneOptimization));
  82708. BABYLON.CustomOptimization = CustomOptimization;
  82709. /**
  82710. * Defines an optimization used to turn particles off
  82711. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82712. */
  82713. var ParticlesOptimization = /** @class */ (function (_super) {
  82714. __extends(ParticlesOptimization, _super);
  82715. function ParticlesOptimization() {
  82716. return _super !== null && _super.apply(this, arguments) || this;
  82717. }
  82718. /**
  82719. * Gets a string describing the action executed by the current optimization
  82720. * @return description string
  82721. */
  82722. ParticlesOptimization.prototype.getDescription = function () {
  82723. return "Turning particles on/off";
  82724. };
  82725. /**
  82726. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82727. * @param scene defines the current scene where to apply this optimization
  82728. * @param optimizer defines the current optimizer
  82729. * @returns true if everything that can be done was applied
  82730. */
  82731. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82732. scene.particlesEnabled = optimizer.isInImprovementMode;
  82733. return true;
  82734. };
  82735. ;
  82736. return ParticlesOptimization;
  82737. }(SceneOptimization));
  82738. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82739. /**
  82740. * Defines an optimization used to turn render targets off
  82741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82742. */
  82743. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82744. __extends(RenderTargetsOptimization, _super);
  82745. function RenderTargetsOptimization() {
  82746. return _super !== null && _super.apply(this, arguments) || this;
  82747. }
  82748. /**
  82749. * Gets a string describing the action executed by the current optimization
  82750. * @return description string
  82751. */
  82752. RenderTargetsOptimization.prototype.getDescription = function () {
  82753. return "Turning render targets off";
  82754. };
  82755. /**
  82756. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82757. * @param scene defines the current scene where to apply this optimization
  82758. * @param optimizer defines the current optimizer
  82759. * @returns true if everything that can be done was applied
  82760. */
  82761. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82762. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82763. return true;
  82764. };
  82765. ;
  82766. return RenderTargetsOptimization;
  82767. }(SceneOptimization));
  82768. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82769. /**
  82770. * Defines an optimization used to merge meshes with compatible materials
  82771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82772. */
  82773. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82774. __extends(MergeMeshesOptimization, _super);
  82775. function MergeMeshesOptimization() {
  82776. var _this = _super !== null && _super.apply(this, arguments) || this;
  82777. _this._canBeMerged = function (abstractMesh) {
  82778. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82779. return false;
  82780. }
  82781. var mesh = abstractMesh;
  82782. if (!mesh.isVisible || !mesh.isEnabled()) {
  82783. return false;
  82784. }
  82785. if (mesh.instances.length > 0) {
  82786. return false;
  82787. }
  82788. if (mesh.skeleton || mesh.hasLODLevels) {
  82789. return false;
  82790. }
  82791. if (mesh.parent) {
  82792. return false;
  82793. }
  82794. return true;
  82795. };
  82796. return _this;
  82797. }
  82798. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82799. /**
  82800. * Gets or sets a boolean which defines if optimization octree has to be updated
  82801. */
  82802. get: function () {
  82803. return MergeMeshesOptimization._UpdateSelectionTree;
  82804. },
  82805. /**
  82806. * Gets or sets a boolean which defines if optimization octree has to be updated
  82807. */
  82808. set: function (value) {
  82809. MergeMeshesOptimization._UpdateSelectionTree = value;
  82810. },
  82811. enumerable: true,
  82812. configurable: true
  82813. });
  82814. /**
  82815. * Gets a string describing the action executed by the current optimization
  82816. * @return description string
  82817. */
  82818. MergeMeshesOptimization.prototype.getDescription = function () {
  82819. return "Merging similar meshes together";
  82820. };
  82821. /**
  82822. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82823. * @param scene defines the current scene where to apply this optimization
  82824. * @param optimizer defines the current optimizer
  82825. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82826. * @returns true if everything that can be done was applied
  82827. */
  82828. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82829. var globalPool = scene.meshes.slice(0);
  82830. var globalLength = globalPool.length;
  82831. for (var index = 0; index < globalLength; index++) {
  82832. var currentPool = new Array();
  82833. var current = globalPool[index];
  82834. // Checks
  82835. if (!this._canBeMerged(current)) {
  82836. continue;
  82837. }
  82838. currentPool.push(current);
  82839. // Find compatible meshes
  82840. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82841. var otherMesh = globalPool[subIndex];
  82842. if (!this._canBeMerged(otherMesh)) {
  82843. continue;
  82844. }
  82845. if (otherMesh.material !== current.material) {
  82846. continue;
  82847. }
  82848. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82849. continue;
  82850. }
  82851. currentPool.push(otherMesh);
  82852. globalLength--;
  82853. globalPool.splice(subIndex, 1);
  82854. subIndex--;
  82855. }
  82856. if (currentPool.length < 2) {
  82857. continue;
  82858. }
  82859. // Merge meshes
  82860. BABYLON.Mesh.MergeMeshes(currentPool);
  82861. }
  82862. if (updateSelectionTree != undefined) {
  82863. if (updateSelectionTree) {
  82864. scene.createOrUpdateSelectionOctree();
  82865. }
  82866. }
  82867. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82868. scene.createOrUpdateSelectionOctree();
  82869. }
  82870. return true;
  82871. };
  82872. ;
  82873. MergeMeshesOptimization._UpdateSelectionTree = false;
  82874. return MergeMeshesOptimization;
  82875. }(SceneOptimization));
  82876. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82877. /**
  82878. * Defines a list of options used by SceneOptimizer
  82879. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82880. */
  82881. var SceneOptimizerOptions = /** @class */ (function () {
  82882. /**
  82883. * Creates a new list of options used by SceneOptimizer
  82884. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82885. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82886. */
  82887. function SceneOptimizerOptions(
  82888. /**
  82889. * Defines the target frame rate to reach (60 by default)
  82890. */
  82891. targetFrameRate,
  82892. /**
  82893. * Defines the interval between two checkes (2000ms by default)
  82894. */
  82895. trackerDuration) {
  82896. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82897. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82898. this.targetFrameRate = targetFrameRate;
  82899. this.trackerDuration = trackerDuration;
  82900. /**
  82901. * Gets the list of optimizations to apply
  82902. */
  82903. this.optimizations = new Array();
  82904. }
  82905. /**
  82906. * Add a new optimization
  82907. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82908. * @returns the current SceneOptimizerOptions
  82909. */
  82910. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82911. this.optimizations.push(optimization);
  82912. return this;
  82913. };
  82914. /**
  82915. * Add a new custom optimization
  82916. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82917. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82918. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82919. * @returns the current SceneOptimizerOptions
  82920. */
  82921. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82922. if (priority === void 0) { priority = 0; }
  82923. var optimization = new CustomOptimization(priority);
  82924. optimization.onApply = onApply;
  82925. optimization.onGetDescription = onGetDescription;
  82926. this.optimizations.push(optimization);
  82927. return this;
  82928. };
  82929. /**
  82930. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82931. * @param targetFrameRate defines the target frame rate (60 by default)
  82932. * @returns a SceneOptimizerOptions object
  82933. */
  82934. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82935. var result = new SceneOptimizerOptions(targetFrameRate);
  82936. var priority = 0;
  82937. result.addOptimization(new MergeMeshesOptimization(priority));
  82938. result.addOptimization(new ShadowsOptimization(priority));
  82939. result.addOptimization(new LensFlaresOptimization(priority));
  82940. // Next priority
  82941. priority++;
  82942. result.addOptimization(new PostProcessesOptimization(priority));
  82943. result.addOptimization(new ParticlesOptimization(priority));
  82944. // Next priority
  82945. priority++;
  82946. result.addOptimization(new TextureOptimization(priority, 1024));
  82947. return result;
  82948. };
  82949. /**
  82950. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82951. * @param targetFrameRate defines the target frame rate (60 by default)
  82952. * @returns a SceneOptimizerOptions object
  82953. */
  82954. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82955. var result = new SceneOptimizerOptions(targetFrameRate);
  82956. var priority = 0;
  82957. result.addOptimization(new MergeMeshesOptimization(priority));
  82958. result.addOptimization(new ShadowsOptimization(priority));
  82959. result.addOptimization(new LensFlaresOptimization(priority));
  82960. // Next priority
  82961. priority++;
  82962. result.addOptimization(new PostProcessesOptimization(priority));
  82963. result.addOptimization(new ParticlesOptimization(priority));
  82964. // Next priority
  82965. priority++;
  82966. result.addOptimization(new TextureOptimization(priority, 512));
  82967. // Next priority
  82968. priority++;
  82969. result.addOptimization(new RenderTargetsOptimization(priority));
  82970. // Next priority
  82971. priority++;
  82972. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82973. return result;
  82974. };
  82975. /**
  82976. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  82977. * @param targetFrameRate defines the target frame rate (60 by default)
  82978. * @returns a SceneOptimizerOptions object
  82979. */
  82980. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  82981. var result = new SceneOptimizerOptions(targetFrameRate);
  82982. var priority = 0;
  82983. result.addOptimization(new MergeMeshesOptimization(priority));
  82984. result.addOptimization(new ShadowsOptimization(priority));
  82985. result.addOptimization(new LensFlaresOptimization(priority));
  82986. // Next priority
  82987. priority++;
  82988. result.addOptimization(new PostProcessesOptimization(priority));
  82989. result.addOptimization(new ParticlesOptimization(priority));
  82990. // Next priority
  82991. priority++;
  82992. result.addOptimization(new TextureOptimization(priority, 256));
  82993. // Next priority
  82994. priority++;
  82995. result.addOptimization(new RenderTargetsOptimization(priority));
  82996. // Next priority
  82997. priority++;
  82998. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  82999. return result;
  83000. };
  83001. return SceneOptimizerOptions;
  83002. }());
  83003. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  83004. /**
  83005. * Class used to run optimizations in order to reach a target frame rate
  83006. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  83007. */
  83008. var SceneOptimizer = /** @class */ (function () {
  83009. /**
  83010. * Creates a new SceneOptimizer
  83011. * @param scene defines the scene to work on
  83012. * @param options defines the options to use with the SceneOptimizer
  83013. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  83014. * @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)
  83015. */
  83016. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  83017. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  83018. if (improvementMode === void 0) { improvementMode = false; }
  83019. var _this = this;
  83020. this._isRunning = false;
  83021. this._currentPriorityLevel = 0;
  83022. this._targetFrameRate = 60;
  83023. this._trackerDuration = 2000;
  83024. this._currentFrameRate = 0;
  83025. this._improvementMode = false;
  83026. /**
  83027. * Defines an observable called when the optimizer reaches the target frame rate
  83028. */
  83029. this.onSuccessObservable = new BABYLON.Observable();
  83030. /**
  83031. * Defines an observable called when the optimizer enables an optimization
  83032. */
  83033. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  83034. /**
  83035. * Defines an observable called when the optimizer is not able to reach the target frame rate
  83036. */
  83037. this.onFailureObservable = new BABYLON.Observable();
  83038. if (!options) {
  83039. this._options = new SceneOptimizerOptions();
  83040. }
  83041. else {
  83042. this._options = options;
  83043. }
  83044. if (this._options.targetFrameRate) {
  83045. this._targetFrameRate = this._options.targetFrameRate;
  83046. }
  83047. if (this._options.trackerDuration) {
  83048. this._trackerDuration = this._options.trackerDuration;
  83049. }
  83050. if (autoGeneratePriorities) {
  83051. var priority = 0;
  83052. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  83053. var optim = _a[_i];
  83054. optim.priority = priority++;
  83055. }
  83056. }
  83057. this._improvementMode = improvementMode;
  83058. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83059. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  83060. _this._sceneDisposeObserver = null;
  83061. _this.dispose();
  83062. });
  83063. }
  83064. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  83065. /**
  83066. * Gets a boolean indicating if the optimizer is in improvement mode
  83067. */
  83068. get: function () {
  83069. return this._improvementMode;
  83070. },
  83071. enumerable: true,
  83072. configurable: true
  83073. });
  83074. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  83075. /**
  83076. * Gets the current priority level (0 at start)
  83077. */
  83078. get: function () {
  83079. return this._currentPriorityLevel;
  83080. },
  83081. enumerable: true,
  83082. configurable: true
  83083. });
  83084. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  83085. /**
  83086. * Gets the current frame rate checked by the SceneOptimizer
  83087. */
  83088. get: function () {
  83089. return this._currentFrameRate;
  83090. },
  83091. enumerable: true,
  83092. configurable: true
  83093. });
  83094. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  83095. /**
  83096. * Gets or sets the current target frame rate (60 by default)
  83097. */
  83098. get: function () {
  83099. return this._targetFrameRate;
  83100. },
  83101. /**
  83102. * Gets or sets the current target frame rate (60 by default)
  83103. */
  83104. set: function (value) {
  83105. this._targetFrameRate = value;
  83106. },
  83107. enumerable: true,
  83108. configurable: true
  83109. });
  83110. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  83111. /**
  83112. * Gets or sets the current interval between two checks (every 2000ms by default)
  83113. */
  83114. get: function () {
  83115. return this._trackerDuration;
  83116. },
  83117. /**
  83118. * Gets or sets the current interval between two checks (every 2000ms by default)
  83119. */
  83120. set: function (value) {
  83121. this._trackerDuration = value;
  83122. },
  83123. enumerable: true,
  83124. configurable: true
  83125. });
  83126. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83127. /**
  83128. * Gets the list of active optimizations
  83129. */
  83130. get: function () {
  83131. return this._options.optimizations;
  83132. },
  83133. enumerable: true,
  83134. configurable: true
  83135. });
  83136. /**
  83137. * Stops the current optimizer
  83138. */
  83139. SceneOptimizer.prototype.stop = function () {
  83140. this._isRunning = false;
  83141. };
  83142. /**
  83143. * Reset the optimizer to initial step (current priority level = 0)
  83144. */
  83145. SceneOptimizer.prototype.reset = function () {
  83146. this._currentPriorityLevel = 0;
  83147. };
  83148. /**
  83149. * Start the optimizer. By default it will try to reach a specific framerate
  83150. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83151. */
  83152. SceneOptimizer.prototype.start = function () {
  83153. var _this = this;
  83154. if (this._isRunning) {
  83155. return;
  83156. }
  83157. this._isRunning = true;
  83158. // Let's wait for the scene to be ready before running our check
  83159. this._scene.executeWhenReady(function () {
  83160. setTimeout(function () {
  83161. _this._checkCurrentState();
  83162. }, _this._trackerDuration);
  83163. });
  83164. };
  83165. SceneOptimizer.prototype._checkCurrentState = function () {
  83166. var _this = this;
  83167. if (!this._isRunning) {
  83168. return;
  83169. }
  83170. var scene = this._scene;
  83171. var options = this._options;
  83172. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83173. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83174. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83175. this._isRunning = false;
  83176. this.onSuccessObservable.notifyObservers(this);
  83177. return;
  83178. }
  83179. // Apply current level of optimizations
  83180. var allDone = true;
  83181. var noOptimizationApplied = true;
  83182. for (var index = 0; index < options.optimizations.length; index++) {
  83183. var optimization = options.optimizations[index];
  83184. if (optimization.priority === this._currentPriorityLevel) {
  83185. noOptimizationApplied = false;
  83186. allDone = allDone && optimization.apply(scene, this);
  83187. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83188. }
  83189. }
  83190. // If no optimization was applied, this is a failure :(
  83191. if (noOptimizationApplied) {
  83192. this._isRunning = false;
  83193. this.onFailureObservable.notifyObservers(this);
  83194. return;
  83195. }
  83196. // If all optimizations were done, move to next level
  83197. if (allDone) {
  83198. this._currentPriorityLevel++;
  83199. }
  83200. // Let's the system running for a specific amount of time before checking FPS
  83201. scene.executeWhenReady(function () {
  83202. setTimeout(function () {
  83203. _this._checkCurrentState();
  83204. }, _this._trackerDuration);
  83205. });
  83206. };
  83207. /**
  83208. * Release all resources
  83209. */
  83210. SceneOptimizer.prototype.dispose = function () {
  83211. this.stop();
  83212. this.onSuccessObservable.clear();
  83213. this.onFailureObservable.clear();
  83214. this.onNewOptimizationAppliedObservable.clear();
  83215. if (this._sceneDisposeObserver) {
  83216. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83217. }
  83218. };
  83219. /**
  83220. * Helper function to create a SceneOptimizer with one single line of code
  83221. * @param scene defines the scene to work on
  83222. * @param options defines the options to use with the SceneOptimizer
  83223. * @param onSuccess defines a callback to call on success
  83224. * @param onFailure defines a callback to call on failure
  83225. * @returns the new SceneOptimizer object
  83226. */
  83227. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83228. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83229. if (onSuccess) {
  83230. optimizer.onSuccessObservable.add(function () {
  83231. onSuccess();
  83232. });
  83233. }
  83234. if (onFailure) {
  83235. optimizer.onFailureObservable.add(function () {
  83236. onFailure();
  83237. });
  83238. }
  83239. optimizer.start();
  83240. return optimizer;
  83241. };
  83242. return SceneOptimizer;
  83243. }());
  83244. BABYLON.SceneOptimizer = SceneOptimizer;
  83245. })(BABYLON || (BABYLON = {}));
  83246. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83247. var BABYLON;
  83248. (function (BABYLON) {
  83249. var OutlineRenderer = /** @class */ (function () {
  83250. function OutlineRenderer(scene) {
  83251. this.zOffset = 1;
  83252. this._scene = scene;
  83253. }
  83254. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83255. var _this = this;
  83256. if (useOverlay === void 0) { useOverlay = false; }
  83257. var scene = this._scene;
  83258. var engine = this._scene.getEngine();
  83259. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83260. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83261. return;
  83262. }
  83263. var mesh = subMesh.getRenderingMesh();
  83264. var material = subMesh.getMaterial();
  83265. if (!material || !scene.activeCamera) {
  83266. return;
  83267. }
  83268. engine.enableEffect(this._effect);
  83269. // Logarithmic depth
  83270. if (material.useLogarithmicDepth) {
  83271. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83272. }
  83273. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83274. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83275. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83276. // Bones
  83277. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83278. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83279. }
  83280. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83281. // Alpha test
  83282. if (material && material.needAlphaTesting()) {
  83283. var alphaTexture = material.getAlphaTestTexture();
  83284. if (alphaTexture) {
  83285. this._effect.setTexture("diffuseSampler", alphaTexture);
  83286. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83287. }
  83288. }
  83289. engine.setZOffset(-this.zOffset);
  83290. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83291. engine.setZOffset(0);
  83292. };
  83293. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83294. var defines = [];
  83295. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83296. var mesh = subMesh.getMesh();
  83297. var material = subMesh.getMaterial();
  83298. if (material) {
  83299. // Alpha test
  83300. if (material.needAlphaTesting()) {
  83301. defines.push("#define ALPHATEST");
  83302. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83303. attribs.push(BABYLON.VertexBuffer.UVKind);
  83304. defines.push("#define UV1");
  83305. }
  83306. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83307. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83308. defines.push("#define UV2");
  83309. }
  83310. }
  83311. //Logarithmic depth
  83312. if (material.useLogarithmicDepth) {
  83313. defines.push("#define LOGARITHMICDEPTH");
  83314. }
  83315. }
  83316. // Bones
  83317. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83318. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83319. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83320. if (mesh.numBoneInfluencers > 4) {
  83321. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83322. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83323. }
  83324. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83325. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83326. }
  83327. else {
  83328. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83329. }
  83330. // Instances
  83331. if (useInstances) {
  83332. defines.push("#define INSTANCES");
  83333. attribs.push("world0");
  83334. attribs.push("world1");
  83335. attribs.push("world2");
  83336. attribs.push("world3");
  83337. }
  83338. // Get correct effect
  83339. var join = defines.join("\n");
  83340. if (this._cachedDefines !== join) {
  83341. this._cachedDefines = join;
  83342. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83343. }
  83344. return this._effect.isReady();
  83345. };
  83346. return OutlineRenderer;
  83347. }());
  83348. BABYLON.OutlineRenderer = OutlineRenderer;
  83349. })(BABYLON || (BABYLON = {}));
  83350. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83351. var BABYLON;
  83352. (function (BABYLON) {
  83353. var FaceAdjacencies = /** @class */ (function () {
  83354. function FaceAdjacencies() {
  83355. this.edges = new Array();
  83356. this.edgesConnectedCount = 0;
  83357. }
  83358. return FaceAdjacencies;
  83359. }());
  83360. var EdgesRenderer = /** @class */ (function () {
  83361. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83362. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83363. if (epsilon === void 0) { epsilon = 0.95; }
  83364. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83365. this.edgesWidthScalerForOrthographic = 1000.0;
  83366. this.edgesWidthScalerForPerspective = 50.0;
  83367. this._linesPositions = new Array();
  83368. this._linesNormals = new Array();
  83369. this._linesIndices = new Array();
  83370. this._buffers = {};
  83371. this._checkVerticesInsteadOfIndices = false;
  83372. this._source = source;
  83373. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83374. this._epsilon = epsilon;
  83375. this._prepareRessources();
  83376. this._generateEdgesLines();
  83377. }
  83378. EdgesRenderer.prototype._prepareRessources = function () {
  83379. if (this._lineShader) {
  83380. return;
  83381. }
  83382. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83383. attributes: ["position", "normal"],
  83384. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83385. });
  83386. this._lineShader.disableDepthWrite = true;
  83387. this._lineShader.backFaceCulling = false;
  83388. };
  83389. EdgesRenderer.prototype._rebuild = function () {
  83390. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83391. if (buffer) {
  83392. buffer._rebuild();
  83393. }
  83394. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83395. if (buffer) {
  83396. buffer._rebuild();
  83397. }
  83398. var scene = this._source.getScene();
  83399. var engine = scene.getEngine();
  83400. this._ib = engine.createIndexBuffer(this._linesIndices);
  83401. };
  83402. EdgesRenderer.prototype.dispose = function () {
  83403. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83404. if (buffer) {
  83405. buffer.dispose();
  83406. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83407. }
  83408. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83409. if (buffer) {
  83410. buffer.dispose();
  83411. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83412. }
  83413. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83414. this._lineShader.dispose();
  83415. };
  83416. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83417. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83418. return 0;
  83419. }
  83420. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83421. return 1;
  83422. }
  83423. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83424. return 2;
  83425. }
  83426. return -1;
  83427. };
  83428. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83429. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83430. return 0;
  83431. }
  83432. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83433. return 1;
  83434. }
  83435. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83436. return 2;
  83437. }
  83438. return -1;
  83439. };
  83440. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83441. var needToCreateLine;
  83442. if (edge === undefined) {
  83443. needToCreateLine = true;
  83444. }
  83445. else {
  83446. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83447. needToCreateLine = dotProduct < this._epsilon;
  83448. }
  83449. if (needToCreateLine) {
  83450. var offset = this._linesPositions.length / 3;
  83451. var normal = p0.subtract(p1);
  83452. normal.normalize();
  83453. // Positions
  83454. this._linesPositions.push(p0.x);
  83455. this._linesPositions.push(p0.y);
  83456. this._linesPositions.push(p0.z);
  83457. this._linesPositions.push(p0.x);
  83458. this._linesPositions.push(p0.y);
  83459. this._linesPositions.push(p0.z);
  83460. this._linesPositions.push(p1.x);
  83461. this._linesPositions.push(p1.y);
  83462. this._linesPositions.push(p1.z);
  83463. this._linesPositions.push(p1.x);
  83464. this._linesPositions.push(p1.y);
  83465. this._linesPositions.push(p1.z);
  83466. // Normals
  83467. this._linesNormals.push(p1.x);
  83468. this._linesNormals.push(p1.y);
  83469. this._linesNormals.push(p1.z);
  83470. this._linesNormals.push(-1);
  83471. this._linesNormals.push(p1.x);
  83472. this._linesNormals.push(p1.y);
  83473. this._linesNormals.push(p1.z);
  83474. this._linesNormals.push(1);
  83475. this._linesNormals.push(p0.x);
  83476. this._linesNormals.push(p0.y);
  83477. this._linesNormals.push(p0.z);
  83478. this._linesNormals.push(-1);
  83479. this._linesNormals.push(p0.x);
  83480. this._linesNormals.push(p0.y);
  83481. this._linesNormals.push(p0.z);
  83482. this._linesNormals.push(1);
  83483. // Indices
  83484. this._linesIndices.push(offset);
  83485. this._linesIndices.push(offset + 1);
  83486. this._linesIndices.push(offset + 2);
  83487. this._linesIndices.push(offset);
  83488. this._linesIndices.push(offset + 2);
  83489. this._linesIndices.push(offset + 3);
  83490. }
  83491. };
  83492. EdgesRenderer.prototype._generateEdgesLines = function () {
  83493. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83494. var indices = this._source.getIndices();
  83495. if (!indices || !positions) {
  83496. return;
  83497. }
  83498. // First let's find adjacencies
  83499. var adjacencies = new Array();
  83500. var faceNormals = new Array();
  83501. var index;
  83502. var faceAdjacencies;
  83503. // Prepare faces
  83504. for (index = 0; index < indices.length; index += 3) {
  83505. faceAdjacencies = new FaceAdjacencies();
  83506. var p0Index = indices[index];
  83507. var p1Index = indices[index + 1];
  83508. var p2Index = indices[index + 2];
  83509. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83510. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83511. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83512. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83513. faceNormal.normalize();
  83514. faceNormals.push(faceNormal);
  83515. adjacencies.push(faceAdjacencies);
  83516. }
  83517. // Scan
  83518. for (index = 0; index < adjacencies.length; index++) {
  83519. faceAdjacencies = adjacencies[index];
  83520. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83521. var otherFaceAdjacencies = adjacencies[otherIndex];
  83522. if (faceAdjacencies.edgesConnectedCount === 3) {
  83523. break;
  83524. }
  83525. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83526. continue;
  83527. }
  83528. var otherP0 = indices[otherIndex * 3];
  83529. var otherP1 = indices[otherIndex * 3 + 1];
  83530. var otherP2 = indices[otherIndex * 3 + 2];
  83531. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83532. var otherEdgeIndex = 0;
  83533. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83534. continue;
  83535. }
  83536. switch (edgeIndex) {
  83537. case 0:
  83538. if (this._checkVerticesInsteadOfIndices) {
  83539. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83540. }
  83541. else {
  83542. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83543. }
  83544. break;
  83545. case 1:
  83546. if (this._checkVerticesInsteadOfIndices) {
  83547. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83548. }
  83549. else {
  83550. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83551. }
  83552. break;
  83553. case 2:
  83554. if (this._checkVerticesInsteadOfIndices) {
  83555. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83556. }
  83557. else {
  83558. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83559. }
  83560. break;
  83561. }
  83562. if (otherEdgeIndex === -1) {
  83563. continue;
  83564. }
  83565. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83566. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83567. faceAdjacencies.edgesConnectedCount++;
  83568. otherFaceAdjacencies.edgesConnectedCount++;
  83569. if (faceAdjacencies.edgesConnectedCount === 3) {
  83570. break;
  83571. }
  83572. }
  83573. }
  83574. }
  83575. // Create lines
  83576. for (index = 0; index < adjacencies.length; index++) {
  83577. // 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
  83578. var current = adjacencies[index];
  83579. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83580. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83581. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83582. }
  83583. // Merge into a single mesh
  83584. var engine = this._source.getScene().getEngine();
  83585. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83586. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83587. this._ib = engine.createIndexBuffer(this._linesIndices);
  83588. this._indicesCount = this._linesIndices.length;
  83589. };
  83590. EdgesRenderer.prototype.render = function () {
  83591. var scene = this._source.getScene();
  83592. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83593. return;
  83594. }
  83595. var engine = scene.getEngine();
  83596. this._lineShader._preBind();
  83597. // VBOs
  83598. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83599. scene.resetCachedMaterial();
  83600. this._lineShader.setColor4("color", this._source.edgesColor);
  83601. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83602. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83603. }
  83604. else {
  83605. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83606. }
  83607. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83608. this._lineShader.bind(this._source.getWorldMatrix());
  83609. // Draw order
  83610. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83611. this._lineShader.unbind();
  83612. engine.setDepthWrite(true);
  83613. };
  83614. return EdgesRenderer;
  83615. }());
  83616. BABYLON.EdgesRenderer = EdgesRenderer;
  83617. })(BABYLON || (BABYLON = {}));
  83618. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83619. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83620. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83621. s = arguments[i];
  83622. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83623. t[p] = s[p];
  83624. }
  83625. return t;
  83626. };
  83627. var BABYLON;
  83628. (function (BABYLON) {
  83629. /**
  83630. * The effect layer Helps adding post process effect blended with the main pass.
  83631. *
  83632. * This can be for instance use to generate glow or higlight effects on the scene.
  83633. *
  83634. * The effect layer class can not be used directly and is intented to inherited from to be
  83635. * customized per effects.
  83636. */
  83637. var EffectLayer = /** @class */ (function () {
  83638. /**
  83639. * Instantiates a new effect Layer and references it in the scene.
  83640. * @param name The name of the layer
  83641. * @param scene The scene to use the layer in
  83642. */
  83643. function EffectLayer(
  83644. /** The Friendly of the effect in the scene */
  83645. name, scene) {
  83646. this.name = name;
  83647. this._vertexBuffers = {};
  83648. this._maxSize = 0;
  83649. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83650. this._shouldRender = true;
  83651. this._postProcesses = [];
  83652. this._textures = [];
  83653. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83654. /**
  83655. * The clear color of the texture used to generate the glow map.
  83656. */
  83657. this.neutralColor = new BABYLON.Color4();
  83658. /**
  83659. * Specifies wether the highlight layer is enabled or not.
  83660. */
  83661. this.isEnabled = true;
  83662. /**
  83663. * An event triggered when the effect layer has been disposed.
  83664. */
  83665. this.onDisposeObservable = new BABYLON.Observable();
  83666. /**
  83667. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83668. */
  83669. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83670. /**
  83671. * An event triggered when the generated texture is being merged in the scene.
  83672. */
  83673. this.onBeforeComposeObservable = new BABYLON.Observable();
  83674. /**
  83675. * An event triggered when the generated texture has been merged in the scene.
  83676. */
  83677. this.onAfterComposeObservable = new BABYLON.Observable();
  83678. /**
  83679. * An event triggered when the efffect layer changes its size.
  83680. */
  83681. this.onSizeChangedObservable = new BABYLON.Observable();
  83682. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83683. this._engine = scene.getEngine();
  83684. this._maxSize = this._engine.getCaps().maxTextureSize;
  83685. this._scene.effectLayers.push(this);
  83686. // Generate Buffers
  83687. this._generateIndexBuffer();
  83688. this._genrateVertexBuffer();
  83689. }
  83690. Object.defineProperty(EffectLayer.prototype, "camera", {
  83691. /**
  83692. * Gets the camera attached to the layer.
  83693. */
  83694. get: function () {
  83695. return this._effectLayerOptions.camera;
  83696. },
  83697. enumerable: true,
  83698. configurable: true
  83699. });
  83700. /**
  83701. * Initializes the effect layer with the required options.
  83702. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83703. */
  83704. EffectLayer.prototype._init = function (options) {
  83705. // Adapt options
  83706. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83707. this._setMainTextureSize();
  83708. this._createMainTexture();
  83709. this._createTextureAndPostProcesses();
  83710. this._mergeEffect = this._createMergeEffect();
  83711. };
  83712. /**
  83713. * Generates the index buffer of the full screen quad blending to the main canvas.
  83714. */
  83715. EffectLayer.prototype._generateIndexBuffer = function () {
  83716. // Indices
  83717. var indices = [];
  83718. indices.push(0);
  83719. indices.push(1);
  83720. indices.push(2);
  83721. indices.push(0);
  83722. indices.push(2);
  83723. indices.push(3);
  83724. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83725. };
  83726. /**
  83727. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83728. */
  83729. EffectLayer.prototype._genrateVertexBuffer = function () {
  83730. // VBO
  83731. var vertices = [];
  83732. vertices.push(1, 1);
  83733. vertices.push(-1, 1);
  83734. vertices.push(-1, -1);
  83735. vertices.push(1, -1);
  83736. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83737. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83738. };
  83739. /**
  83740. * Sets the main texture desired size which is the closest power of two
  83741. * of the engine canvas size.
  83742. */
  83743. EffectLayer.prototype._setMainTextureSize = function () {
  83744. if (this._effectLayerOptions.mainTextureFixedSize) {
  83745. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83746. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83747. }
  83748. else {
  83749. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83750. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83751. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83752. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83753. }
  83754. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83755. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83756. };
  83757. /**
  83758. * Creates the main texture for the effect layer.
  83759. */
  83760. EffectLayer.prototype._createMainTexture = function () {
  83761. var _this = this;
  83762. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83763. width: this._mainTextureDesiredSize.width,
  83764. height: this._mainTextureDesiredSize.height
  83765. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83766. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83767. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83768. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83769. this._mainTexture.anisotropicFilteringLevel = 1;
  83770. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83771. this._mainTexture.renderParticles = false;
  83772. this._mainTexture.renderList = null;
  83773. this._mainTexture.ignoreCameraViewport = true;
  83774. // Custom render function
  83775. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83776. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83777. var index;
  83778. var engine = _this._scene.getEngine();
  83779. if (depthOnlySubMeshes.length) {
  83780. engine.setColorWrite(false);
  83781. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83782. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83783. }
  83784. engine.setColorWrite(true);
  83785. }
  83786. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83787. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83788. }
  83789. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83790. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83791. }
  83792. for (index = 0; index < transparentSubMeshes.length; index++) {
  83793. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83794. }
  83795. };
  83796. this._mainTexture.onClearObservable.add(function (engine) {
  83797. engine.clear(_this.neutralColor, true, true, true);
  83798. });
  83799. };
  83800. /**
  83801. * Checks for the readiness of the element composing the layer.
  83802. * @param subMesh the mesh to check for
  83803. * @param useInstances specify wether or not to use instances to render the mesh
  83804. * @param emissiveTexture the associated emissive texture used to generate the glow
  83805. * @return true if ready otherwise, false
  83806. */
  83807. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83808. var material = subMesh.getMaterial();
  83809. if (!material) {
  83810. return false;
  83811. }
  83812. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83813. return false;
  83814. }
  83815. var defines = [];
  83816. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83817. var mesh = subMesh.getMesh();
  83818. var uv1 = false;
  83819. var uv2 = false;
  83820. // Alpha test
  83821. if (material && material.needAlphaTesting()) {
  83822. var alphaTexture = material.getAlphaTestTexture();
  83823. if (alphaTexture) {
  83824. defines.push("#define ALPHATEST");
  83825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83826. alphaTexture.coordinatesIndex === 1) {
  83827. defines.push("#define DIFFUSEUV2");
  83828. uv2 = true;
  83829. }
  83830. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83831. defines.push("#define DIFFUSEUV1");
  83832. uv1 = true;
  83833. }
  83834. }
  83835. }
  83836. // Emissive
  83837. if (emissiveTexture) {
  83838. defines.push("#define EMISSIVE");
  83839. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83840. emissiveTexture.coordinatesIndex === 1) {
  83841. defines.push("#define EMISSIVEUV2");
  83842. uv2 = true;
  83843. }
  83844. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83845. defines.push("#define EMISSIVEUV1");
  83846. uv1 = true;
  83847. }
  83848. }
  83849. if (uv1) {
  83850. attribs.push(BABYLON.VertexBuffer.UVKind);
  83851. defines.push("#define UV1");
  83852. }
  83853. if (uv2) {
  83854. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83855. defines.push("#define UV2");
  83856. }
  83857. // Bones
  83858. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83861. if (mesh.numBoneInfluencers > 4) {
  83862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83864. }
  83865. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83866. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83867. }
  83868. else {
  83869. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83870. }
  83871. // Instances
  83872. if (useInstances) {
  83873. defines.push("#define INSTANCES");
  83874. attribs.push("world0");
  83875. attribs.push("world1");
  83876. attribs.push("world2");
  83877. attribs.push("world3");
  83878. }
  83879. // Get correct effect
  83880. var join = defines.join("\n");
  83881. if (this._cachedDefines !== join) {
  83882. this._cachedDefines = join;
  83883. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83884. }
  83885. return this._effectLayerMapGenerationEffect.isReady();
  83886. };
  83887. /**
  83888. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83889. */
  83890. EffectLayer.prototype.render = function () {
  83891. var currentEffect = this._mergeEffect;
  83892. // Check
  83893. if (!currentEffect.isReady())
  83894. return;
  83895. for (var i = 0; i < this._postProcesses.length; i++) {
  83896. if (!this._postProcesses[i].isReady()) {
  83897. return;
  83898. }
  83899. }
  83900. var engine = this._scene.getEngine();
  83901. this.onBeforeComposeObservable.notifyObservers(this);
  83902. // Render
  83903. engine.enableEffect(currentEffect);
  83904. engine.setState(false);
  83905. // VBOs
  83906. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83907. // Cache
  83908. var previousAlphaMode = engine.getAlphaMode();
  83909. // Go Blend.
  83910. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83911. // Blends the map on the main canvas.
  83912. this._internalRender(currentEffect);
  83913. // Restore Alpha
  83914. engine.setAlphaMode(previousAlphaMode);
  83915. this.onAfterComposeObservable.notifyObservers(this);
  83916. // Handle size changes.
  83917. var size = this._mainTexture.getSize();
  83918. this._setMainTextureSize();
  83919. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83920. // Recreate RTT and post processes on size change.
  83921. this.onSizeChangedObservable.notifyObservers(this);
  83922. this._disposeTextureAndPostProcesses();
  83923. this._createMainTexture();
  83924. this._createTextureAndPostProcesses();
  83925. }
  83926. };
  83927. /**
  83928. * Determine if a given mesh will be used in the current effect.
  83929. * @param mesh mesh to test
  83930. * @returns true if the mesh will be used
  83931. */
  83932. EffectLayer.prototype.hasMesh = function (mesh) {
  83933. return true;
  83934. };
  83935. /**
  83936. * Returns true if the layer contains information to display, otherwise false.
  83937. * @returns true if the glow layer should be rendered
  83938. */
  83939. EffectLayer.prototype.shouldRender = function () {
  83940. return this.isEnabled && this._shouldRender;
  83941. };
  83942. /**
  83943. * Returns true if the mesh should render, otherwise false.
  83944. * @param mesh The mesh to render
  83945. * @returns true if it should render otherwise false
  83946. */
  83947. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83948. return true;
  83949. };
  83950. /**
  83951. * Returns true if the mesh should render, otherwise false.
  83952. * @param mesh The mesh to render
  83953. * @returns true if it should render otherwise false
  83954. */
  83955. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83956. return true;
  83957. };
  83958. /**
  83959. * Renders the submesh passed in parameter to the generation map.
  83960. */
  83961. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83962. var _this = this;
  83963. if (!this.shouldRender()) {
  83964. return;
  83965. }
  83966. var material = subMesh.getMaterial();
  83967. var mesh = subMesh.getRenderingMesh();
  83968. var scene = this._scene;
  83969. var engine = scene.getEngine();
  83970. if (!material) {
  83971. return;
  83972. }
  83973. // Do not block in blend mode.
  83974. if (material.needAlphaBlendingForMesh(mesh)) {
  83975. return;
  83976. }
  83977. // Culling
  83978. engine.setState(material.backFaceCulling);
  83979. // Managing instances
  83980. var batch = mesh._getInstancesRenderList(subMesh._id);
  83981. if (batch.mustReturn) {
  83982. return;
  83983. }
  83984. // Early Exit per mesh
  83985. if (!this._shouldRenderMesh(mesh)) {
  83986. return;
  83987. }
  83988. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83989. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  83990. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  83991. engine.enableEffect(this._effectLayerMapGenerationEffect);
  83992. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  83993. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  83994. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  83995. // Alpha test
  83996. if (material && material.needAlphaTesting()) {
  83997. var alphaTexture = material.getAlphaTestTexture();
  83998. if (alphaTexture) {
  83999. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  84000. var textureMatrix = alphaTexture.getTextureMatrix();
  84001. if (textureMatrix) {
  84002. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  84003. }
  84004. }
  84005. }
  84006. // Glow emissive only
  84007. if (this._emissiveTextureAndColor.texture) {
  84008. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  84009. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  84010. }
  84011. // Bones
  84012. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84013. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84014. }
  84015. // Draw
  84016. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  84017. }
  84018. else {
  84019. // Need to reset refresh rate of the shadowMap
  84020. this._mainTexture.resetRefreshCounter();
  84021. }
  84022. };
  84023. /**
  84024. * Rebuild the required buffers.
  84025. * @ignore Internal use only.
  84026. */
  84027. EffectLayer.prototype._rebuild = function () {
  84028. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84029. if (vb) {
  84030. vb._rebuild();
  84031. }
  84032. this._generateIndexBuffer();
  84033. };
  84034. /**
  84035. * Dispose only the render target textures and post process.
  84036. */
  84037. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  84038. this._mainTexture.dispose();
  84039. for (var i = 0; i < this._postProcesses.length; i++) {
  84040. if (this._postProcesses[i]) {
  84041. this._postProcesses[i].dispose();
  84042. }
  84043. }
  84044. this._postProcesses = [];
  84045. for (var i = 0; i < this._textures.length; i++) {
  84046. if (this._textures[i]) {
  84047. this._textures[i].dispose();
  84048. }
  84049. }
  84050. this._textures = [];
  84051. };
  84052. /**
  84053. * Dispose the highlight layer and free resources.
  84054. */
  84055. EffectLayer.prototype.dispose = function () {
  84056. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84057. if (vertexBuffer) {
  84058. vertexBuffer.dispose();
  84059. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84060. }
  84061. if (this._indexBuffer) {
  84062. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84063. this._indexBuffer = null;
  84064. }
  84065. // Clean textures and post processes
  84066. this._disposeTextureAndPostProcesses();
  84067. // Remove from scene
  84068. var index = this._scene.effectLayers.indexOf(this, 0);
  84069. if (index > -1) {
  84070. this._scene.effectLayers.splice(index, 1);
  84071. }
  84072. // Callback
  84073. this.onDisposeObservable.notifyObservers(this);
  84074. this.onDisposeObservable.clear();
  84075. this.onBeforeRenderMainTextureObservable.clear();
  84076. this.onBeforeComposeObservable.clear();
  84077. this.onAfterComposeObservable.clear();
  84078. this.onSizeChangedObservable.clear();
  84079. };
  84080. return EffectLayer;
  84081. }());
  84082. BABYLON.EffectLayer = EffectLayer;
  84083. })(BABYLON || (BABYLON = {}));
  84084. //# sourceMappingURL=babylon.effectLayer.js.map
  84085. var BABYLON;
  84086. (function (BABYLON) {
  84087. /**
  84088. * Special Glow Blur post process only blurring the alpha channel
  84089. * It enforces keeping the most luminous color in the color channel.
  84090. */
  84091. var GlowBlurPostProcess = /** @class */ (function (_super) {
  84092. __extends(GlowBlurPostProcess, _super);
  84093. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  84094. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84095. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  84096. _this.direction = direction;
  84097. _this.kernel = kernel;
  84098. _this.onApplyObservable.add(function (effect) {
  84099. effect.setFloat2("screenSize", _this.width, _this.height);
  84100. effect.setVector2("direction", _this.direction);
  84101. effect.setFloat("blurWidth", _this.kernel);
  84102. });
  84103. return _this;
  84104. }
  84105. return GlowBlurPostProcess;
  84106. }(BABYLON.PostProcess));
  84107. /**
  84108. * The highlight layer Helps adding a glow effect around a mesh.
  84109. *
  84110. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84111. * glowy meshes to your scene.
  84112. *
  84113. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  84114. */
  84115. var HighlightLayer = /** @class */ (function (_super) {
  84116. __extends(HighlightLayer, _super);
  84117. /**
  84118. * Instantiates a new highlight Layer and references it to the scene..
  84119. * @param name The name of the layer
  84120. * @param scene The scene to use the layer in
  84121. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84122. */
  84123. function HighlightLayer(name, scene, options) {
  84124. var _this = _super.call(this, name, scene) || this;
  84125. _this.name = name;
  84126. /**
  84127. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84128. */
  84129. _this.innerGlow = true;
  84130. /**
  84131. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84132. */
  84133. _this.outerGlow = true;
  84134. /**
  84135. * An event triggered when the highlight layer is being blurred.
  84136. */
  84137. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84138. /**
  84139. * An event triggered when the highlight layer has been blurred.
  84140. */
  84141. _this.onAfterBlurObservable = new BABYLON.Observable();
  84142. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84143. _this._meshes = {};
  84144. _this._excludedMeshes = {};
  84145. _this.neutralColor = HighlightLayer.NeutralColor;
  84146. // Warn on stencil
  84147. if (!_this._engine.isStencilEnable) {
  84148. 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 }");
  84149. }
  84150. // Adapt options
  84151. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84152. // Initialize the layer
  84153. _this._init({
  84154. alphaBlendingMode: _this._options.alphaBlendingMode,
  84155. camera: _this._options.camera,
  84156. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84157. mainTextureRatio: _this._options.mainTextureRatio
  84158. });
  84159. // Do not render as long as no meshes have been added
  84160. _this._shouldRender = false;
  84161. return _this;
  84162. }
  84163. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84164. /**
  84165. * Gets the horizontal size of the blur.
  84166. */
  84167. get: function () {
  84168. return this._horizontalBlurPostprocess.kernel;
  84169. },
  84170. /**
  84171. * Specifies the horizontal size of the blur.
  84172. */
  84173. set: function (value) {
  84174. this._horizontalBlurPostprocess.kernel = value;
  84175. },
  84176. enumerable: true,
  84177. configurable: true
  84178. });
  84179. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84180. /**
  84181. * Gets the vertical size of the blur.
  84182. */
  84183. get: function () {
  84184. return this._verticalBlurPostprocess.kernel;
  84185. },
  84186. /**
  84187. * Specifies the vertical size of the blur.
  84188. */
  84189. set: function (value) {
  84190. this._verticalBlurPostprocess.kernel = value;
  84191. },
  84192. enumerable: true,
  84193. configurable: true
  84194. });
  84195. /**
  84196. * Get the effect name of the layer.
  84197. * @return The effect name
  84198. */
  84199. HighlightLayer.prototype.getEffectName = function () {
  84200. return HighlightLayer.EffectName;
  84201. };
  84202. /**
  84203. * Create the merge effect. This is the shader use to blit the information back
  84204. * to the main canvas at the end of the scene rendering.
  84205. */
  84206. HighlightLayer.prototype._createMergeEffect = function () {
  84207. // Effect
  84208. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84209. };
  84210. /**
  84211. * Creates the render target textures and post processes used in the highlight layer.
  84212. */
  84213. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84214. var _this = this;
  84215. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84216. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84217. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84218. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84219. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84220. width: blurTextureWidth,
  84221. height: blurTextureHeight
  84222. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84223. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84224. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84225. this._blurTexture.anisotropicFilteringLevel = 16;
  84226. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84227. this._blurTexture.renderParticles = false;
  84228. this._blurTexture.ignoreCameraViewport = true;
  84229. this._textures = [this._blurTexture];
  84230. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84231. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84232. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84233. effect.setTexture("textureSampler", _this._mainTexture);
  84234. });
  84235. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84236. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84237. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84238. });
  84239. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84240. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84241. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84242. });
  84243. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84244. }
  84245. else {
  84246. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84247. width: blurTextureWidth,
  84248. height: blurTextureHeight
  84249. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84250. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84251. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84252. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84253. effect.setTexture("textureSampler", _this._mainTexture);
  84254. });
  84255. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84256. width: blurTextureWidth,
  84257. height: blurTextureHeight
  84258. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84259. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84260. }
  84261. this._mainTexture.onAfterUnbindObservable.add(function () {
  84262. _this.onBeforeBlurObservable.notifyObservers(_this);
  84263. var internalTexture = _this._blurTexture.getInternalTexture();
  84264. if (internalTexture) {
  84265. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84266. }
  84267. _this.onAfterBlurObservable.notifyObservers(_this);
  84268. });
  84269. // Prevent autoClear.
  84270. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84271. };
  84272. /**
  84273. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84274. */
  84275. HighlightLayer.prototype.needStencil = function () {
  84276. return true;
  84277. };
  84278. /**
  84279. * Checks for the readiness of the element composing the layer.
  84280. * @param subMesh the mesh to check for
  84281. * @param useInstances specify wether or not to use instances to render the mesh
  84282. * @param emissiveTexture the associated emissive texture used to generate the glow
  84283. * @return true if ready otherwise, false
  84284. */
  84285. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84286. var material = subMesh.getMaterial();
  84287. var mesh = subMesh.getRenderingMesh();
  84288. if (!material || !mesh || !this._meshes) {
  84289. return false;
  84290. }
  84291. var emissiveTexture = null;
  84292. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84293. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84294. emissiveTexture = material.emissiveTexture;
  84295. }
  84296. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84297. };
  84298. /**
  84299. * Implementation specific of rendering the generating effect on the main canvas.
  84300. * @param effect The effect used to render through
  84301. */
  84302. HighlightLayer.prototype._internalRender = function (effect) {
  84303. // Texture
  84304. effect.setTexture("textureSampler", this._blurTexture);
  84305. // Cache
  84306. var engine = this._engine;
  84307. var previousStencilBuffer = engine.getStencilBuffer();
  84308. var previousStencilFunction = engine.getStencilFunction();
  84309. var previousStencilMask = engine.getStencilMask();
  84310. var previousStencilOperationPass = engine.getStencilOperationPass();
  84311. var previousStencilOperationFail = engine.getStencilOperationFail();
  84312. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84313. var previousStencilReference = engine.getStencilFunctionReference();
  84314. // Stencil operations
  84315. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84316. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84317. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84318. // Draw order
  84319. engine.setStencilMask(0x00);
  84320. engine.setStencilBuffer(true);
  84321. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84322. // 2 passes inner outer
  84323. if (this.outerGlow) {
  84324. effect.setFloat("offset", 0);
  84325. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84326. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84327. }
  84328. if (this.innerGlow) {
  84329. effect.setFloat("offset", 1);
  84330. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84331. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84332. }
  84333. // Restore Cache
  84334. engine.setStencilFunction(previousStencilFunction);
  84335. engine.setStencilMask(previousStencilMask);
  84336. engine.setStencilBuffer(previousStencilBuffer);
  84337. engine.setStencilOperationPass(previousStencilOperationPass);
  84338. engine.setStencilOperationFail(previousStencilOperationFail);
  84339. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84340. engine.setStencilFunctionReference(previousStencilReference);
  84341. };
  84342. /**
  84343. * Returns true if the layer contains information to display, otherwise false.
  84344. */
  84345. HighlightLayer.prototype.shouldRender = function () {
  84346. if (_super.prototype.shouldRender.call(this)) {
  84347. return this._meshes ? true : false;
  84348. }
  84349. return false;
  84350. };
  84351. /**
  84352. * Returns true if the mesh should render, otherwise false.
  84353. * @param mesh The mesh to render
  84354. * @returns true if it should render otherwise false
  84355. */
  84356. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84357. // Excluded Mesh
  84358. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84359. return false;
  84360. }
  84361. ;
  84362. return true;
  84363. };
  84364. /**
  84365. * Sets the required values for both the emissive texture and and the main color.
  84366. */
  84367. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84368. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84369. if (highlightLayerMesh) {
  84370. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84371. }
  84372. else {
  84373. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84374. }
  84375. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84376. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84377. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84378. }
  84379. else {
  84380. this._emissiveTextureAndColor.texture = null;
  84381. }
  84382. };
  84383. /**
  84384. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84385. * @param mesh The mesh to exclude from the highlight layer
  84386. */
  84387. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84388. if (!this._excludedMeshes) {
  84389. return;
  84390. }
  84391. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84392. if (!meshExcluded) {
  84393. this._excludedMeshes[mesh.uniqueId] = {
  84394. mesh: mesh,
  84395. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84396. mesh.getEngine().setStencilBuffer(false);
  84397. }),
  84398. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84399. mesh.getEngine().setStencilBuffer(true);
  84400. }),
  84401. };
  84402. }
  84403. };
  84404. /**
  84405. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84406. * @param mesh The mesh to highlight
  84407. */
  84408. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84409. if (!this._excludedMeshes) {
  84410. return;
  84411. }
  84412. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84413. if (meshExcluded) {
  84414. if (meshExcluded.beforeRender) {
  84415. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84416. }
  84417. if (meshExcluded.afterRender) {
  84418. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84419. }
  84420. }
  84421. this._excludedMeshes[mesh.uniqueId] = null;
  84422. };
  84423. /**
  84424. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84425. * @param mesh mesh to test
  84426. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84427. */
  84428. HighlightLayer.prototype.hasMesh = function (mesh) {
  84429. if (!this._meshes) {
  84430. return false;
  84431. }
  84432. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84433. };
  84434. /**
  84435. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84436. * @param mesh The mesh to highlight
  84437. * @param color The color of the highlight
  84438. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84439. */
  84440. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84441. var _this = this;
  84442. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84443. if (!this._meshes) {
  84444. return;
  84445. }
  84446. var meshHighlight = this._meshes[mesh.uniqueId];
  84447. if (meshHighlight) {
  84448. meshHighlight.color = color;
  84449. }
  84450. else {
  84451. this._meshes[mesh.uniqueId] = {
  84452. mesh: mesh,
  84453. color: color,
  84454. // Lambda required for capture due to Observable this context
  84455. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84456. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84457. _this._defaultStencilReference(mesh);
  84458. }
  84459. else {
  84460. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84461. }
  84462. }),
  84463. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84464. glowEmissiveOnly: glowEmissiveOnly
  84465. };
  84466. }
  84467. this._shouldRender = true;
  84468. };
  84469. /**
  84470. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84471. * @param mesh The mesh to highlight
  84472. */
  84473. HighlightLayer.prototype.removeMesh = function (mesh) {
  84474. if (!this._meshes) {
  84475. return;
  84476. }
  84477. var meshHighlight = this._meshes[mesh.uniqueId];
  84478. if (meshHighlight) {
  84479. if (meshHighlight.observerHighlight) {
  84480. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84481. }
  84482. if (meshHighlight.observerDefault) {
  84483. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84484. }
  84485. delete this._meshes[mesh.uniqueId];
  84486. }
  84487. this._shouldRender = false;
  84488. for (var meshHighlightToCheck in this._meshes) {
  84489. if (this._meshes[meshHighlightToCheck]) {
  84490. this._shouldRender = true;
  84491. break;
  84492. }
  84493. }
  84494. };
  84495. /**
  84496. * Force the stencil to the normal expected value for none glowing parts
  84497. */
  84498. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84499. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84500. };
  84501. /**
  84502. * Free any resources and references associated to a mesh.
  84503. * Internal use
  84504. * @param mesh The mesh to free.
  84505. */
  84506. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84507. this.removeMesh(mesh);
  84508. this.removeExcludedMesh(mesh);
  84509. };
  84510. /**
  84511. * Dispose the highlight layer and free resources.
  84512. */
  84513. HighlightLayer.prototype.dispose = function () {
  84514. if (this._meshes) {
  84515. // Clean mesh references
  84516. for (var id in this._meshes) {
  84517. var meshHighlight = this._meshes[id];
  84518. if (meshHighlight && meshHighlight.mesh) {
  84519. if (meshHighlight.observerHighlight) {
  84520. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84521. }
  84522. if (meshHighlight.observerDefault) {
  84523. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84524. }
  84525. }
  84526. }
  84527. this._meshes = null;
  84528. }
  84529. if (this._excludedMeshes) {
  84530. for (var id in this._excludedMeshes) {
  84531. var meshHighlight = this._excludedMeshes[id];
  84532. if (meshHighlight) {
  84533. if (meshHighlight.beforeRender) {
  84534. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84535. }
  84536. if (meshHighlight.afterRender) {
  84537. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84538. }
  84539. }
  84540. }
  84541. this._excludedMeshes = null;
  84542. }
  84543. _super.prototype.dispose.call(this);
  84544. };
  84545. /**
  84546. * Effect Name of the highlight layer.
  84547. */
  84548. HighlightLayer.EffectName = "HighlightLayer";
  84549. /**
  84550. * The neutral color used during the preparation of the glow effect.
  84551. * This is black by default as the blend operation is a blend operation.
  84552. */
  84553. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84554. /**
  84555. * Stencil value used for glowing meshes.
  84556. */
  84557. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84558. /**
  84559. * Stencil value used for the other meshes in the scene.
  84560. */
  84561. HighlightLayer.NormalMeshStencilReference = 0x01;
  84562. return HighlightLayer;
  84563. }(BABYLON.EffectLayer));
  84564. BABYLON.HighlightLayer = HighlightLayer;
  84565. })(BABYLON || (BABYLON = {}));
  84566. //# sourceMappingURL=babylon.highlightLayer.js.map
  84567. var BABYLON;
  84568. (function (BABYLON) {
  84569. /**
  84570. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84571. *
  84572. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84573. * glowy meshes to your scene.
  84574. *
  84575. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84576. */
  84577. var GlowLayer = /** @class */ (function (_super) {
  84578. __extends(GlowLayer, _super);
  84579. /**
  84580. * Instantiates a new glow Layer and references it to the scene.
  84581. * @param name The name of the layer
  84582. * @param scene The scene to use the layer in
  84583. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84584. */
  84585. function GlowLayer(name, scene, options) {
  84586. var _this = _super.call(this, name, scene) || this;
  84587. _this.name = name;
  84588. _this._intensity = 1.0;
  84589. _this._includedOnlyMeshes = [];
  84590. _this._excludedMeshes = [];
  84591. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84592. // Adapt options
  84593. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84594. // Initialize the layer
  84595. _this._init({
  84596. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84597. camera: _this._options.camera,
  84598. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84599. mainTextureRatio: _this._options.mainTextureRatio
  84600. });
  84601. return _this;
  84602. }
  84603. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84604. /**
  84605. * Gets the kernel size of the blur.
  84606. */
  84607. get: function () {
  84608. return this._horizontalBlurPostprocess1.kernel;
  84609. },
  84610. /**
  84611. * Sets the kernel size of the blur.
  84612. */
  84613. set: function (value) {
  84614. this._horizontalBlurPostprocess1.kernel = value;
  84615. this._verticalBlurPostprocess1.kernel = value;
  84616. this._horizontalBlurPostprocess2.kernel = value;
  84617. this._verticalBlurPostprocess2.kernel = value;
  84618. },
  84619. enumerable: true,
  84620. configurable: true
  84621. });
  84622. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84623. /**
  84624. * Gets the glow intensity.
  84625. */
  84626. get: function () {
  84627. return this._intensity;
  84628. },
  84629. /**
  84630. * Sets the glow intensity.
  84631. */
  84632. set: function (value) {
  84633. this._intensity = value;
  84634. },
  84635. enumerable: true,
  84636. configurable: true
  84637. });
  84638. /**
  84639. * Get the effect name of the layer.
  84640. * @return The effect name
  84641. */
  84642. GlowLayer.prototype.getEffectName = function () {
  84643. return GlowLayer.EffectName;
  84644. };
  84645. /**
  84646. * Create the merge effect. This is the shader use to blit the information back
  84647. * to the main canvas at the end of the scene rendering.
  84648. */
  84649. GlowLayer.prototype._createMergeEffect = function () {
  84650. // Effect
  84651. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84652. };
  84653. /**
  84654. * Creates the render target textures and post processes used in the glow layer.
  84655. */
  84656. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84657. var _this = this;
  84658. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84659. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84660. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84661. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84662. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84663. width: blurTextureWidth,
  84664. height: blurTextureHeight
  84665. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84666. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84667. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84668. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84669. this._blurTexture1.renderParticles = false;
  84670. this._blurTexture1.ignoreCameraViewport = true;
  84671. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84672. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84673. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84674. width: blurTextureWidth2,
  84675. height: blurTextureHeight2
  84676. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84677. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84678. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84679. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84680. this._blurTexture2.renderParticles = false;
  84681. this._blurTexture2.ignoreCameraViewport = true;
  84682. this._textures = [this._blurTexture1, this._blurTexture2];
  84683. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84684. width: blurTextureWidth,
  84685. height: blurTextureHeight
  84686. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84687. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84688. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84689. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84690. effect.setTexture("textureSampler", _this._mainTexture);
  84691. });
  84692. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84693. width: blurTextureWidth,
  84694. height: blurTextureHeight
  84695. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84696. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84697. width: blurTextureWidth2,
  84698. height: blurTextureHeight2
  84699. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84700. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84701. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84702. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84703. effect.setTexture("textureSampler", _this._blurTexture1);
  84704. });
  84705. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84706. width: blurTextureWidth2,
  84707. height: blurTextureHeight2
  84708. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84709. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84710. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84711. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84712. this._mainTexture.samples = this._options.mainTextureSamples;
  84713. this._mainTexture.onAfterUnbindObservable.add(function () {
  84714. var internalTexture = _this._blurTexture1.getInternalTexture();
  84715. if (internalTexture) {
  84716. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84717. internalTexture = _this._blurTexture2.getInternalTexture();
  84718. if (internalTexture) {
  84719. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84720. }
  84721. }
  84722. });
  84723. // Prevent autoClear.
  84724. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84725. };
  84726. /**
  84727. * Checks for the readiness of the element composing the layer.
  84728. * @param subMesh the mesh to check for
  84729. * @param useInstances specify wether or not to use instances to render the mesh
  84730. * @param emissiveTexture the associated emissive texture used to generate the glow
  84731. * @return true if ready otherwise, false
  84732. */
  84733. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84734. var material = subMesh.getMaterial();
  84735. var mesh = subMesh.getRenderingMesh();
  84736. if (!material || !mesh) {
  84737. return false;
  84738. }
  84739. var emissiveTexture = material.emissiveTexture;
  84740. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84741. };
  84742. /**
  84743. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84744. */
  84745. GlowLayer.prototype.needStencil = function () {
  84746. return false;
  84747. };
  84748. /**
  84749. * Implementation specific of rendering the generating effect on the main canvas.
  84750. * @param effect The effect used to render through
  84751. */
  84752. GlowLayer.prototype._internalRender = function (effect) {
  84753. // Texture
  84754. effect.setTexture("textureSampler", this._blurTexture1);
  84755. effect.setTexture("textureSampler2", this._blurTexture2);
  84756. effect.setFloat("offset", this._intensity);
  84757. // Cache
  84758. var engine = this._engine;
  84759. var previousStencilBuffer = engine.getStencilBuffer();
  84760. // Draw order
  84761. engine.setStencilBuffer(false);
  84762. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84763. // Draw order
  84764. engine.setStencilBuffer(previousStencilBuffer);
  84765. };
  84766. /**
  84767. * Sets the required values for both the emissive texture and and the main color.
  84768. */
  84769. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84770. var textureLevel = 1.0;
  84771. if (this.customEmissiveTextureSelector) {
  84772. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84773. }
  84774. else {
  84775. if (material) {
  84776. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84777. if (this._emissiveTextureAndColor.texture) {
  84778. textureLevel = this._emissiveTextureAndColor.texture.level;
  84779. }
  84780. }
  84781. else {
  84782. this._emissiveTextureAndColor.texture = null;
  84783. }
  84784. }
  84785. if (this.customEmissiveColorSelector) {
  84786. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84787. }
  84788. else {
  84789. if (material.emissiveColor) {
  84790. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84791. }
  84792. else {
  84793. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84794. }
  84795. }
  84796. };
  84797. /**
  84798. * Returns true if the mesh should render, otherwise false.
  84799. * @param mesh The mesh to render
  84800. * @returns true if it should render otherwise false
  84801. */
  84802. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84803. return this.hasMesh(mesh);
  84804. };
  84805. /**
  84806. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84807. * @param mesh The mesh to exclude from the glow layer
  84808. */
  84809. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84810. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84811. this._excludedMeshes.push(mesh.uniqueId);
  84812. }
  84813. };
  84814. /**
  84815. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84816. * @param mesh The mesh to remove
  84817. */
  84818. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84819. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84820. if (index !== -1) {
  84821. this._excludedMeshes.splice(index, 1);
  84822. }
  84823. };
  84824. /**
  84825. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84826. * @param mesh The mesh to include in the glow layer
  84827. */
  84828. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84829. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84830. this._includedOnlyMeshes.push(mesh.uniqueId);
  84831. }
  84832. };
  84833. /**
  84834. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84835. * @param mesh The mesh to remove
  84836. */
  84837. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84838. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84839. if (index !== -1) {
  84840. this._includedOnlyMeshes.splice(index, 1);
  84841. }
  84842. };
  84843. /**
  84844. * Determine if a given mesh will be used in the glow layer
  84845. * @param mesh The mesh to test
  84846. * @returns true if the mesh will be highlighted by the current glow layer
  84847. */
  84848. GlowLayer.prototype.hasMesh = function (mesh) {
  84849. // Included Mesh
  84850. if (this._includedOnlyMeshes.length) {
  84851. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84852. }
  84853. ;
  84854. // Excluded Mesh
  84855. if (this._excludedMeshes.length) {
  84856. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84857. }
  84858. ;
  84859. return true;
  84860. };
  84861. /**
  84862. * Free any resources and references associated to a mesh.
  84863. * Internal use
  84864. * @param mesh The mesh to free.
  84865. */
  84866. GlowLayer.prototype._disposeMesh = function (mesh) {
  84867. this.removeIncludedOnlyMesh(mesh);
  84868. this.removeExcludedMesh(mesh);
  84869. };
  84870. /**
  84871. * Effect Name of the layer.
  84872. */
  84873. GlowLayer.EffectName = "GlowLayer";
  84874. /**
  84875. * The default blur kernel size used for the glow.
  84876. */
  84877. GlowLayer.DefaultBlurKernelSize = 32;
  84878. /**
  84879. * The default texture size ratio used for the glow.
  84880. */
  84881. GlowLayer.DefaultTextureRatio = 0.5;
  84882. return GlowLayer;
  84883. }(BABYLON.EffectLayer));
  84884. BABYLON.GlowLayer = GlowLayer;
  84885. })(BABYLON || (BABYLON = {}));
  84886. //# sourceMappingURL=babylon.glowLayer.js.map
  84887. var BABYLON;
  84888. (function (BABYLON) {
  84889. /**
  84890. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84891. */
  84892. var AssetTaskState;
  84893. (function (AssetTaskState) {
  84894. /**
  84895. * Initialization
  84896. */
  84897. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84898. /**
  84899. * Running
  84900. */
  84901. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84902. /**
  84903. * Done
  84904. */
  84905. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84906. /**
  84907. * Error
  84908. */
  84909. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84910. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84911. /**
  84912. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84913. */
  84914. var AbstractAssetTask = /** @class */ (function () {
  84915. /**
  84916. * Creates a new {BABYLON.AssetsManager}
  84917. * @param name defines the name of the task
  84918. */
  84919. function AbstractAssetTask(
  84920. /**
  84921. * Task name
  84922. */ name) {
  84923. this.name = name;
  84924. this._isCompleted = false;
  84925. this._taskState = AssetTaskState.INIT;
  84926. }
  84927. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84928. /**
  84929. * Get if the task is completed
  84930. */
  84931. get: function () {
  84932. return this._isCompleted;
  84933. },
  84934. enumerable: true,
  84935. configurable: true
  84936. });
  84937. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84938. /**
  84939. * Gets the current state of the task
  84940. */
  84941. get: function () {
  84942. return this._taskState;
  84943. },
  84944. enumerable: true,
  84945. configurable: true
  84946. });
  84947. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84948. /**
  84949. * Gets the current error object (if task is in error)
  84950. */
  84951. get: function () {
  84952. return this._errorObject;
  84953. },
  84954. enumerable: true,
  84955. configurable: true
  84956. });
  84957. /**
  84958. * Internal only
  84959. * @ignore
  84960. */
  84961. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84962. if (this._errorObject) {
  84963. return;
  84964. }
  84965. this._errorObject = {
  84966. message: message,
  84967. exception: exception
  84968. };
  84969. };
  84970. /**
  84971. * Execute the current task
  84972. * @param scene defines the scene where you want your assets to be loaded
  84973. * @param onSuccess is a callback called when the task is successfully executed
  84974. * @param onError is a callback called if an error occurs
  84975. */
  84976. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84977. var _this = this;
  84978. this._taskState = AssetTaskState.RUNNING;
  84979. this.runTask(scene, function () {
  84980. _this.onDoneCallback(onSuccess, onError);
  84981. }, function (msg, exception) {
  84982. _this.onErrorCallback(onError, msg, exception);
  84983. });
  84984. };
  84985. /**
  84986. * Execute the current task
  84987. * @param scene defines the scene where you want your assets to be loaded
  84988. * @param onSuccess is a callback called when the task is successfully executed
  84989. * @param onError is a callback called if an error occurs
  84990. */
  84991. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84992. throw new Error("runTask is not implemented");
  84993. };
  84994. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  84995. this._taskState = AssetTaskState.ERROR;
  84996. this._errorObject = {
  84997. message: message,
  84998. exception: exception
  84999. };
  85000. if (this.onError) {
  85001. this.onError(this, message, exception);
  85002. }
  85003. onError();
  85004. };
  85005. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  85006. try {
  85007. this._taskState = AssetTaskState.DONE;
  85008. this._isCompleted = true;
  85009. if (this.onSuccess) {
  85010. this.onSuccess(this);
  85011. }
  85012. onSuccess();
  85013. }
  85014. catch (e) {
  85015. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  85016. }
  85017. };
  85018. return AbstractAssetTask;
  85019. }());
  85020. BABYLON.AbstractAssetTask = AbstractAssetTask;
  85021. /**
  85022. * Class used to share progress information about assets loading
  85023. */
  85024. var AssetsProgressEvent = /** @class */ (function () {
  85025. /**
  85026. * Creates a {BABYLON.AssetsProgressEvent}
  85027. * @param remainingCount defines the number of remaining tasks to process
  85028. * @param totalCount defines the total number of tasks
  85029. * @param task defines the task that was just processed
  85030. */
  85031. function AssetsProgressEvent(remainingCount, totalCount, task) {
  85032. this.remainingCount = remainingCount;
  85033. this.totalCount = totalCount;
  85034. this.task = task;
  85035. }
  85036. return AssetsProgressEvent;
  85037. }());
  85038. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  85039. /**
  85040. * Define a task used by {BABYLON.AssetsManager} to load meshes
  85041. */
  85042. var MeshAssetTask = /** @class */ (function (_super) {
  85043. __extends(MeshAssetTask, _super);
  85044. /**
  85045. * Creates a new {BABYLON.MeshAssetTask}
  85046. * @param name defines the name of the task
  85047. * @param meshesNames defines the list of mesh's names you want to load
  85048. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  85049. * @param sceneFilename defines the filename of the scene to load from
  85050. */
  85051. function MeshAssetTask(
  85052. /**
  85053. * Defines the name of the task
  85054. */
  85055. name,
  85056. /**
  85057. * Defines the list of mesh's names you want to load
  85058. */
  85059. meshesNames,
  85060. /**
  85061. * Defines the root url to use as a base to load your meshes and associated resources
  85062. */
  85063. rootUrl,
  85064. /**
  85065. * Defines the filename of the scene to load from
  85066. */
  85067. sceneFilename) {
  85068. var _this = _super.call(this, name) || this;
  85069. _this.name = name;
  85070. _this.meshesNames = meshesNames;
  85071. _this.rootUrl = rootUrl;
  85072. _this.sceneFilename = sceneFilename;
  85073. return _this;
  85074. }
  85075. /**
  85076. * Execute the current task
  85077. * @param scene defines the scene where you want your assets to be loaded
  85078. * @param onSuccess is a callback called when the task is successfully executed
  85079. * @param onError is a callback called if an error occurs
  85080. */
  85081. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85082. var _this = this;
  85083. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  85084. _this.loadedMeshes = meshes;
  85085. _this.loadedParticleSystems = particleSystems;
  85086. _this.loadedSkeletons = skeletons;
  85087. onSuccess();
  85088. }, null, function (scene, message, exception) {
  85089. onError(message, exception);
  85090. });
  85091. };
  85092. return MeshAssetTask;
  85093. }(AbstractAssetTask));
  85094. BABYLON.MeshAssetTask = MeshAssetTask;
  85095. /**
  85096. * Define a task used by {BABYLON.AssetsManager} to load text content
  85097. */
  85098. var TextFileAssetTask = /** @class */ (function (_super) {
  85099. __extends(TextFileAssetTask, _super);
  85100. /**
  85101. * Creates a new TextFileAssetTask object
  85102. * @param name defines the name of the task
  85103. * @param url defines the location of the file to load
  85104. */
  85105. function TextFileAssetTask(
  85106. /**
  85107. * Defines the name of the task
  85108. */
  85109. name,
  85110. /**
  85111. * Defines the location of the file to load
  85112. */
  85113. url) {
  85114. var _this = _super.call(this, name) || this;
  85115. _this.name = name;
  85116. _this.url = url;
  85117. return _this;
  85118. }
  85119. /**
  85120. * Execute the current task
  85121. * @param scene defines the scene where you want your assets to be loaded
  85122. * @param onSuccess is a callback called when the task is successfully executed
  85123. * @param onError is a callback called if an error occurs
  85124. */
  85125. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85126. var _this = this;
  85127. scene._loadFile(this.url, function (data) {
  85128. _this.text = data;
  85129. onSuccess();
  85130. }, undefined, false, false, function (request, exception) {
  85131. if (request) {
  85132. onError(request.status + " " + request.statusText, exception);
  85133. }
  85134. });
  85135. };
  85136. return TextFileAssetTask;
  85137. }(AbstractAssetTask));
  85138. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85139. /**
  85140. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85141. */
  85142. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85143. __extends(BinaryFileAssetTask, _super);
  85144. /**
  85145. * Creates a new BinaryFileAssetTask object
  85146. * @param name defines the name of the new task
  85147. * @param url defines the location of the file to load
  85148. */
  85149. function BinaryFileAssetTask(
  85150. /**
  85151. * Defines the name of the task
  85152. */
  85153. name,
  85154. /**
  85155. * Defines the location of the file to load
  85156. */
  85157. url) {
  85158. var _this = _super.call(this, name) || this;
  85159. _this.name = name;
  85160. _this.url = url;
  85161. return _this;
  85162. }
  85163. /**
  85164. * Execute the current task
  85165. * @param scene defines the scene where you want your assets to be loaded
  85166. * @param onSuccess is a callback called when the task is successfully executed
  85167. * @param onError is a callback called if an error occurs
  85168. */
  85169. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85170. var _this = this;
  85171. scene._loadFile(this.url, function (data) {
  85172. _this.data = data;
  85173. onSuccess();
  85174. }, undefined, true, true, function (request, exception) {
  85175. if (request) {
  85176. onError(request.status + " " + request.statusText, exception);
  85177. }
  85178. });
  85179. };
  85180. return BinaryFileAssetTask;
  85181. }(AbstractAssetTask));
  85182. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85183. /**
  85184. * Define a task used by {BABYLON.AssetsManager} to load images
  85185. */
  85186. var ImageAssetTask = /** @class */ (function (_super) {
  85187. __extends(ImageAssetTask, _super);
  85188. /**
  85189. * Creates a new ImageAssetTask
  85190. * @param name defines the name of the task
  85191. * @param url defines the location of the image to load
  85192. */
  85193. function ImageAssetTask(
  85194. /**
  85195. * Defines the name of the task
  85196. */
  85197. name,
  85198. /**
  85199. * Defines the location of the image to load
  85200. */
  85201. url) {
  85202. var _this = _super.call(this, name) || this;
  85203. _this.name = name;
  85204. _this.url = url;
  85205. return _this;
  85206. }
  85207. /**
  85208. * Execute the current task
  85209. * @param scene defines the scene where you want your assets to be loaded
  85210. * @param onSuccess is a callback called when the task is successfully executed
  85211. * @param onError is a callback called if an error occurs
  85212. */
  85213. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85214. var _this = this;
  85215. var img = new Image();
  85216. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85217. img.onload = function () {
  85218. _this.image = img;
  85219. onSuccess();
  85220. };
  85221. img.onerror = function (err) {
  85222. onError("Error loading image", err);
  85223. };
  85224. img.src = this.url;
  85225. };
  85226. return ImageAssetTask;
  85227. }(AbstractAssetTask));
  85228. BABYLON.ImageAssetTask = ImageAssetTask;
  85229. /**
  85230. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85231. */
  85232. var TextureAssetTask = /** @class */ (function (_super) {
  85233. __extends(TextureAssetTask, _super);
  85234. /**
  85235. * Creates a new TextureAssetTask object
  85236. * @param name defines the name of the task
  85237. * @param url defines the location of the file to load
  85238. * @param noMipmap defines if mipmap should not be generated (default is false)
  85239. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85240. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85241. */
  85242. function TextureAssetTask(
  85243. /**
  85244. * Defines the name of the task
  85245. */
  85246. name,
  85247. /**
  85248. * Defines the location of the file to load
  85249. */
  85250. url,
  85251. /**
  85252. * Defines if mipmap should not be generated (default is false)
  85253. */
  85254. noMipmap,
  85255. /**
  85256. * Defines if texture must be inverted on Y axis (default is false)
  85257. */
  85258. invertY,
  85259. /**
  85260. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85261. */
  85262. samplingMode) {
  85263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85264. var _this = _super.call(this, name) || this;
  85265. _this.name = name;
  85266. _this.url = url;
  85267. _this.noMipmap = noMipmap;
  85268. _this.invertY = invertY;
  85269. _this.samplingMode = samplingMode;
  85270. return _this;
  85271. }
  85272. /**
  85273. * Execute the current task
  85274. * @param scene defines the scene where you want your assets to be loaded
  85275. * @param onSuccess is a callback called when the task is successfully executed
  85276. * @param onError is a callback called if an error occurs
  85277. */
  85278. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85279. var onload = function () {
  85280. onSuccess();
  85281. };
  85282. var onerror = function (message, exception) {
  85283. onError(message, exception);
  85284. };
  85285. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85286. };
  85287. return TextureAssetTask;
  85288. }(AbstractAssetTask));
  85289. BABYLON.TextureAssetTask = TextureAssetTask;
  85290. /**
  85291. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85292. */
  85293. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85294. __extends(CubeTextureAssetTask, _super);
  85295. /**
  85296. * Creates a new CubeTextureAssetTask
  85297. * @param name defines the name of the task
  85298. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85299. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85300. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85301. * @param files defines the explicit list of files (undefined by default)
  85302. */
  85303. function CubeTextureAssetTask(
  85304. /**
  85305. * Defines the name of the task
  85306. */
  85307. name,
  85308. /**
  85309. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85310. */
  85311. url,
  85312. /**
  85313. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85314. */
  85315. extensions,
  85316. /**
  85317. * Defines if mipmaps should not be generated (default is false)
  85318. */
  85319. noMipmap,
  85320. /**
  85321. * Defines the explicit list of files (undefined by default)
  85322. */
  85323. files) {
  85324. var _this = _super.call(this, name) || this;
  85325. _this.name = name;
  85326. _this.url = url;
  85327. _this.extensions = extensions;
  85328. _this.noMipmap = noMipmap;
  85329. _this.files = files;
  85330. return _this;
  85331. }
  85332. /**
  85333. * Execute the current task
  85334. * @param scene defines the scene where you want your assets to be loaded
  85335. * @param onSuccess is a callback called when the task is successfully executed
  85336. * @param onError is a callback called if an error occurs
  85337. */
  85338. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85339. var onload = function () {
  85340. onSuccess();
  85341. };
  85342. var onerror = function (message, exception) {
  85343. onError(message, exception);
  85344. };
  85345. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85346. };
  85347. return CubeTextureAssetTask;
  85348. }(AbstractAssetTask));
  85349. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85350. /**
  85351. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85352. */
  85353. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85354. __extends(HDRCubeTextureAssetTask, _super);
  85355. /**
  85356. * Creates a new HDRCubeTextureAssetTask object
  85357. * @param name defines the name of the task
  85358. * @param url defines the location of the file to load
  85359. * @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.
  85360. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85361. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85362. * @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)
  85363. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85364. */
  85365. function HDRCubeTextureAssetTask(
  85366. /**
  85367. * Defines the name of the task
  85368. */
  85369. name,
  85370. /**
  85371. * Defines the location of the file to load
  85372. */
  85373. url,
  85374. /**
  85375. * 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.
  85376. */
  85377. size,
  85378. /**
  85379. * Defines if mipmaps should not be generated (default is false)
  85380. */
  85381. noMipmap,
  85382. /**
  85383. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85384. */
  85385. generateHarmonics,
  85386. /**
  85387. * 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)
  85388. */
  85389. useInGammaSpace,
  85390. /**
  85391. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85392. */
  85393. usePMREMGenerator) {
  85394. if (noMipmap === void 0) { noMipmap = false; }
  85395. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85396. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85397. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85398. var _this = _super.call(this, name) || this;
  85399. _this.name = name;
  85400. _this.url = url;
  85401. _this.size = size;
  85402. _this.noMipmap = noMipmap;
  85403. _this.generateHarmonics = generateHarmonics;
  85404. _this.useInGammaSpace = useInGammaSpace;
  85405. _this.usePMREMGenerator = usePMREMGenerator;
  85406. return _this;
  85407. }
  85408. /**
  85409. * Execute the current task
  85410. * @param scene defines the scene where you want your assets to be loaded
  85411. * @param onSuccess is a callback called when the task is successfully executed
  85412. * @param onError is a callback called if an error occurs
  85413. */
  85414. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85415. var onload = function () {
  85416. onSuccess();
  85417. };
  85418. var onerror = function (message, exception) {
  85419. onError(message, exception);
  85420. };
  85421. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85422. };
  85423. return HDRCubeTextureAssetTask;
  85424. }(AbstractAssetTask));
  85425. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85426. /**
  85427. * This class can be used to easily import assets into a scene
  85428. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85429. */
  85430. var AssetsManager = /** @class */ (function () {
  85431. /**
  85432. * Creates a new AssetsManager
  85433. * @param scene defines the scene to work on
  85434. */
  85435. function AssetsManager(scene) {
  85436. this._isLoading = false;
  85437. this._tasks = new Array();
  85438. this._waitingTasksCount = 0;
  85439. this._totalTasksCount = 0;
  85440. /**
  85441. * Observable called when all tasks are processed
  85442. */
  85443. this.onTaskSuccessObservable = new BABYLON.Observable();
  85444. /**
  85445. * Observable called when a task had an error
  85446. */
  85447. this.onTaskErrorObservable = new BABYLON.Observable();
  85448. /**
  85449. * Observable called when a task is successful
  85450. */
  85451. this.onTasksDoneObservable = new BABYLON.Observable();
  85452. /**
  85453. * Observable called when a task is done (whatever the result is)
  85454. */
  85455. this.onProgressObservable = new BABYLON.Observable();
  85456. /**
  85457. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85458. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85459. */
  85460. this.useDefaultLoadingScreen = true;
  85461. this._scene = scene;
  85462. }
  85463. /**
  85464. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85465. * @param taskName defines the name of the new task
  85466. * @param meshesNames defines the name of meshes to load
  85467. * @param rootUrl defines the root url to use to locate files
  85468. * @param sceneFilename defines the filename of the scene file
  85469. * @returns a new {BABYLON.MeshAssetTask} object
  85470. */
  85471. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85472. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85473. this._tasks.push(task);
  85474. return task;
  85475. };
  85476. /**
  85477. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85478. * @param taskName defines the name of the new task
  85479. * @param url defines the url of the file to load
  85480. * @returns a new {BABYLON.TextFileAssetTask} object
  85481. */
  85482. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85483. var task = new TextFileAssetTask(taskName, url);
  85484. this._tasks.push(task);
  85485. return task;
  85486. };
  85487. /**
  85488. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85489. * @param taskName defines the name of the new task
  85490. * @param url defines the url of the file to load
  85491. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85492. */
  85493. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85494. var task = new BinaryFileAssetTask(taskName, url);
  85495. this._tasks.push(task);
  85496. return task;
  85497. };
  85498. /**
  85499. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85500. * @param taskName defines the name of the new task
  85501. * @param url defines the url of the file to load
  85502. * @returns a new {BABYLON.ImageAssetTask} object
  85503. */
  85504. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85505. var task = new ImageAssetTask(taskName, url);
  85506. this._tasks.push(task);
  85507. return task;
  85508. };
  85509. /**
  85510. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85511. * @param taskName defines the name of the new task
  85512. * @param url defines the url of the file to load
  85513. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85514. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85515. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85516. * @returns a new {BABYLON.TextureAssetTask} object
  85517. */
  85518. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85519. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85520. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85521. this._tasks.push(task);
  85522. return task;
  85523. };
  85524. /**
  85525. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85526. * @param taskName defines the name of the new task
  85527. * @param url defines the url of the file to load
  85528. * @param extensions defines the extension to use to load the cube map (can be null)
  85529. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85530. * @param files defines the list of files to load (can be null)
  85531. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85532. */
  85533. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85534. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85535. this._tasks.push(task);
  85536. return task;
  85537. };
  85538. /**
  85539. *
  85540. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85541. * @param taskName defines the name of the new task
  85542. * @param url defines the url of the file to load
  85543. * @param size defines the size you want for the cubemap (can be null)
  85544. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85545. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85546. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85547. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85548. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85549. */
  85550. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85551. if (noMipmap === void 0) { noMipmap = false; }
  85552. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85553. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85554. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85555. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85556. this._tasks.push(task);
  85557. return task;
  85558. };
  85559. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85560. var _this = this;
  85561. this._waitingTasksCount--;
  85562. try {
  85563. if (task.taskState === AssetTaskState.DONE) {
  85564. // Let's remove successfull tasks
  85565. BABYLON.Tools.SetImmediate(function () {
  85566. var index = _this._tasks.indexOf(task);
  85567. if (index > -1) {
  85568. _this._tasks.splice(index, 1);
  85569. }
  85570. });
  85571. }
  85572. if (this.onProgress) {
  85573. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85574. }
  85575. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85576. }
  85577. catch (e) {
  85578. BABYLON.Tools.Error("Error running progress callbacks.");
  85579. console.log(e);
  85580. }
  85581. if (this._waitingTasksCount === 0) {
  85582. try {
  85583. if (this.onFinish) {
  85584. this.onFinish(this._tasks);
  85585. }
  85586. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85587. }
  85588. catch (e) {
  85589. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85590. console.log(e);
  85591. }
  85592. this._isLoading = false;
  85593. this._scene.getEngine().hideLoadingUI();
  85594. }
  85595. };
  85596. AssetsManager.prototype._runTask = function (task) {
  85597. var _this = this;
  85598. var done = function () {
  85599. try {
  85600. if (_this.onTaskSuccess) {
  85601. _this.onTaskSuccess(task);
  85602. }
  85603. _this.onTaskSuccessObservable.notifyObservers(task);
  85604. _this._decreaseWaitingTasksCount(task);
  85605. }
  85606. catch (e) {
  85607. error("Error executing task success callbacks", e);
  85608. }
  85609. };
  85610. var error = function (message, exception) {
  85611. task._setErrorObject(message, exception);
  85612. if (_this.onTaskError) {
  85613. _this.onTaskError(task);
  85614. }
  85615. _this.onTaskErrorObservable.notifyObservers(task);
  85616. _this._decreaseWaitingTasksCount(task);
  85617. };
  85618. task.run(this._scene, done, error);
  85619. };
  85620. /**
  85621. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85622. * @return the current instance of the {BABYLON.AssetsManager}
  85623. */
  85624. AssetsManager.prototype.reset = function () {
  85625. this._isLoading = false;
  85626. this._tasks = new Array();
  85627. return this;
  85628. };
  85629. /**
  85630. * Start the loading process
  85631. * @return the current instance of the {BABYLON.AssetsManager}
  85632. */
  85633. AssetsManager.prototype.load = function () {
  85634. if (this._isLoading) {
  85635. return this;
  85636. }
  85637. this._isLoading = true;
  85638. this._waitingTasksCount = this._tasks.length;
  85639. this._totalTasksCount = this._tasks.length;
  85640. if (this._waitingTasksCount === 0) {
  85641. this._isLoading = false;
  85642. if (this.onFinish) {
  85643. this.onFinish(this._tasks);
  85644. }
  85645. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85646. return this;
  85647. }
  85648. if (this.useDefaultLoadingScreen) {
  85649. this._scene.getEngine().displayLoadingUI();
  85650. }
  85651. for (var index = 0; index < this._tasks.length; index++) {
  85652. var task = this._tasks[index];
  85653. this._runTask(task);
  85654. }
  85655. return this;
  85656. };
  85657. return AssetsManager;
  85658. }());
  85659. BABYLON.AssetsManager = AssetsManager;
  85660. })(BABYLON || (BABYLON = {}));
  85661. //# sourceMappingURL=babylon.assetsManager.js.map
  85662. var BABYLON;
  85663. (function (BABYLON) {
  85664. var serializedGeometries = [];
  85665. var serializeGeometry = function (geometry, serializationGeometries) {
  85666. if (serializedGeometries[geometry.id]) {
  85667. return;
  85668. }
  85669. if (geometry.doNotSerialize) {
  85670. return;
  85671. }
  85672. if (geometry instanceof BABYLON.BoxGeometry) {
  85673. serializationGeometries.boxes.push(geometry.serialize());
  85674. }
  85675. else if (geometry instanceof BABYLON.SphereGeometry) {
  85676. serializationGeometries.spheres.push(geometry.serialize());
  85677. }
  85678. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85679. serializationGeometries.cylinders.push(geometry.serialize());
  85680. }
  85681. else if (geometry instanceof BABYLON.TorusGeometry) {
  85682. serializationGeometries.toruses.push(geometry.serialize());
  85683. }
  85684. else if (geometry instanceof BABYLON.GroundGeometry) {
  85685. serializationGeometries.grounds.push(geometry.serialize());
  85686. }
  85687. else if (geometry instanceof BABYLON.Plane) {
  85688. serializationGeometries.planes.push(geometry.serialize());
  85689. }
  85690. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85691. serializationGeometries.torusKnots.push(geometry.serialize());
  85692. }
  85693. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85694. throw new Error("Unknown primitive type");
  85695. }
  85696. else {
  85697. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85698. }
  85699. serializedGeometries[geometry.id] = true;
  85700. };
  85701. var serializeMesh = function (mesh, serializationScene) {
  85702. var serializationObject = {};
  85703. // Geometry
  85704. var geometry = mesh._geometry;
  85705. if (geometry) {
  85706. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85707. // 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
  85708. serializeGeometry(geometry, serializationScene.geometries);
  85709. }
  85710. }
  85711. // Custom
  85712. if (mesh.serialize) {
  85713. mesh.serialize(serializationObject);
  85714. }
  85715. return serializationObject;
  85716. };
  85717. var finalizeSingleMesh = function (mesh, serializationObject) {
  85718. //only works if the mesh is already loaded
  85719. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85720. //serialize material
  85721. if (mesh.material) {
  85722. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85723. serializationObject.materials = serializationObject.materials || [];
  85724. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85725. serializationObject.materials.push(mesh.material.serialize());
  85726. }
  85727. }
  85728. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85729. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85730. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85731. serializationObject.multiMaterials.push(mesh.material.serialize());
  85732. }
  85733. }
  85734. }
  85735. //serialize geometry
  85736. var geometry = mesh._geometry;
  85737. if (geometry) {
  85738. if (!serializationObject.geometries) {
  85739. serializationObject.geometries = {};
  85740. serializationObject.geometries.boxes = [];
  85741. serializationObject.geometries.spheres = [];
  85742. serializationObject.geometries.cylinders = [];
  85743. serializationObject.geometries.toruses = [];
  85744. serializationObject.geometries.grounds = [];
  85745. serializationObject.geometries.planes = [];
  85746. serializationObject.geometries.torusKnots = [];
  85747. serializationObject.geometries.vertexData = [];
  85748. }
  85749. serializeGeometry(geometry, serializationObject.geometries);
  85750. }
  85751. // Skeletons
  85752. if (mesh.skeleton) {
  85753. serializationObject.skeletons = serializationObject.skeletons || [];
  85754. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85755. }
  85756. //serialize the actual mesh
  85757. serializationObject.meshes = serializationObject.meshes || [];
  85758. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85759. }
  85760. };
  85761. var SceneSerializer = /** @class */ (function () {
  85762. function SceneSerializer() {
  85763. }
  85764. SceneSerializer.ClearCache = function () {
  85765. serializedGeometries = [];
  85766. };
  85767. SceneSerializer.Serialize = function (scene) {
  85768. var serializationObject = {};
  85769. SceneSerializer.ClearCache();
  85770. // Scene
  85771. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85772. serializationObject.autoClear = scene.autoClear;
  85773. serializationObject.clearColor = scene.clearColor.asArray();
  85774. serializationObject.ambientColor = scene.ambientColor.asArray();
  85775. serializationObject.gravity = scene.gravity.asArray();
  85776. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85777. serializationObject.workerCollisions = scene.workerCollisions;
  85778. // Fog
  85779. if (scene.fogMode && scene.fogMode !== 0) {
  85780. serializationObject.fogMode = scene.fogMode;
  85781. serializationObject.fogColor = scene.fogColor.asArray();
  85782. serializationObject.fogStart = scene.fogStart;
  85783. serializationObject.fogEnd = scene.fogEnd;
  85784. serializationObject.fogDensity = scene.fogDensity;
  85785. }
  85786. //Physics
  85787. if (scene.isPhysicsEnabled()) {
  85788. var physicEngine = scene.getPhysicsEngine();
  85789. if (physicEngine) {
  85790. serializationObject.physicsEnabled = true;
  85791. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85792. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85793. }
  85794. }
  85795. // Metadata
  85796. if (scene.metadata) {
  85797. serializationObject.metadata = scene.metadata;
  85798. }
  85799. // Morph targets
  85800. serializationObject.morphTargetManagers = [];
  85801. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85802. var abstractMesh = _a[_i];
  85803. var manager = abstractMesh.morphTargetManager;
  85804. if (manager) {
  85805. serializationObject.morphTargetManagers.push(manager.serialize());
  85806. }
  85807. }
  85808. // Lights
  85809. serializationObject.lights = [];
  85810. var index;
  85811. var light;
  85812. for (index = 0; index < scene.lights.length; index++) {
  85813. light = scene.lights[index];
  85814. if (!light.doNotSerialize) {
  85815. serializationObject.lights.push(light.serialize());
  85816. }
  85817. }
  85818. // Cameras
  85819. serializationObject.cameras = [];
  85820. for (index = 0; index < scene.cameras.length; index++) {
  85821. var camera = scene.cameras[index];
  85822. if (!camera.doNotSerialize) {
  85823. serializationObject.cameras.push(camera.serialize());
  85824. }
  85825. }
  85826. if (scene.activeCamera) {
  85827. serializationObject.activeCameraID = scene.activeCamera.id;
  85828. }
  85829. // Animations
  85830. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85831. // Materials
  85832. serializationObject.materials = [];
  85833. serializationObject.multiMaterials = [];
  85834. var material;
  85835. for (index = 0; index < scene.materials.length; index++) {
  85836. material = scene.materials[index];
  85837. if (!material.doNotSerialize) {
  85838. serializationObject.materials.push(material.serialize());
  85839. }
  85840. }
  85841. // MultiMaterials
  85842. serializationObject.multiMaterials = [];
  85843. for (index = 0; index < scene.multiMaterials.length; index++) {
  85844. var multiMaterial = scene.multiMaterials[index];
  85845. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85846. }
  85847. // Environment texture
  85848. if (scene.environmentTexture) {
  85849. serializationObject.environmentTexture = scene.environmentTexture.name;
  85850. }
  85851. // Skeletons
  85852. serializationObject.skeletons = [];
  85853. for (index = 0; index < scene.skeletons.length; index++) {
  85854. var skeleton = scene.skeletons[index];
  85855. if (!skeleton.doNotSerialize) {
  85856. serializationObject.skeletons.push(skeleton.serialize());
  85857. }
  85858. }
  85859. // Transform nodes
  85860. serializationObject.transformNodes = [];
  85861. for (index = 0; index < scene.transformNodes.length; index++) {
  85862. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85863. }
  85864. // Geometries
  85865. serializationObject.geometries = {};
  85866. serializationObject.geometries.boxes = [];
  85867. serializationObject.geometries.spheres = [];
  85868. serializationObject.geometries.cylinders = [];
  85869. serializationObject.geometries.toruses = [];
  85870. serializationObject.geometries.grounds = [];
  85871. serializationObject.geometries.planes = [];
  85872. serializationObject.geometries.torusKnots = [];
  85873. serializationObject.geometries.vertexData = [];
  85874. serializedGeometries = [];
  85875. var geometries = scene.getGeometries();
  85876. for (index = 0; index < geometries.length; index++) {
  85877. var geometry = geometries[index];
  85878. if (geometry.isReady()) {
  85879. serializeGeometry(geometry, serializationObject.geometries);
  85880. }
  85881. }
  85882. // Meshes
  85883. serializationObject.meshes = [];
  85884. for (index = 0; index < scene.meshes.length; index++) {
  85885. var abstractMesh = scene.meshes[index];
  85886. if (abstractMesh instanceof BABYLON.Mesh) {
  85887. var mesh = abstractMesh;
  85888. if (!mesh.doNotSerialize) {
  85889. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85890. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85891. }
  85892. }
  85893. }
  85894. }
  85895. // Particles Systems
  85896. serializationObject.particleSystems = [];
  85897. for (index = 0; index < scene.particleSystems.length; index++) {
  85898. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85899. }
  85900. // Lens flares
  85901. serializationObject.lensFlareSystems = [];
  85902. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85903. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85904. }
  85905. // Shadows
  85906. serializationObject.shadowGenerators = [];
  85907. for (index = 0; index < scene.lights.length; index++) {
  85908. light = scene.lights[index];
  85909. var shadowGenerator = light.getShadowGenerator();
  85910. if (shadowGenerator) {
  85911. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85912. }
  85913. }
  85914. // Action Manager
  85915. if (scene.actionManager) {
  85916. serializationObject.actions = scene.actionManager.serialize("scene");
  85917. }
  85918. // Audio
  85919. serializationObject.sounds = [];
  85920. for (index = 0; index < scene.soundTracks.length; index++) {
  85921. var soundtrack = scene.soundTracks[index];
  85922. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85923. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85924. }
  85925. }
  85926. return serializationObject;
  85927. };
  85928. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85929. if (withParents === void 0) { withParents = false; }
  85930. if (withChildren === void 0) { withChildren = false; }
  85931. var serializationObject = {};
  85932. SceneSerializer.ClearCache();
  85933. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85934. if (withParents || withChildren) {
  85935. //deliberate for loop! not for each, appended should be processed as well.
  85936. for (var i = 0; i < toSerialize.length; ++i) {
  85937. if (withChildren) {
  85938. toSerialize[i].getDescendants().forEach(function (node) {
  85939. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85940. toSerialize.push(node);
  85941. }
  85942. });
  85943. }
  85944. //make sure the array doesn't contain the object already
  85945. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85946. toSerialize.push(toSerialize[i].parent);
  85947. }
  85948. }
  85949. }
  85950. toSerialize.forEach(function (mesh) {
  85951. finalizeSingleMesh(mesh, serializationObject);
  85952. });
  85953. return serializationObject;
  85954. };
  85955. return SceneSerializer;
  85956. }());
  85957. BABYLON.SceneSerializer = SceneSerializer;
  85958. })(BABYLON || (BABYLON = {}));
  85959. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85960. var BABYLON;
  85961. (function (BABYLON) {
  85962. var ReflectionProbe = /** @class */ (function () {
  85963. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85964. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85965. var _this = this;
  85966. this.name = name;
  85967. this._viewMatrix = BABYLON.Matrix.Identity();
  85968. this._target = BABYLON.Vector3.Zero();
  85969. this._add = BABYLON.Vector3.Zero();
  85970. this._invertYAxis = false;
  85971. this.position = BABYLON.Vector3.Zero();
  85972. this._scene = scene;
  85973. this._scene.reflectionProbes.push(this);
  85974. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  85975. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  85976. switch (faceIndex) {
  85977. case 0:
  85978. _this._add.copyFromFloats(1, 0, 0);
  85979. break;
  85980. case 1:
  85981. _this._add.copyFromFloats(-1, 0, 0);
  85982. break;
  85983. case 2:
  85984. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  85985. break;
  85986. case 3:
  85987. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  85988. break;
  85989. case 4:
  85990. _this._add.copyFromFloats(0, 0, 1);
  85991. break;
  85992. case 5:
  85993. _this._add.copyFromFloats(0, 0, -1);
  85994. break;
  85995. }
  85996. if (_this._attachedMesh) {
  85997. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  85998. }
  85999. _this.position.addToRef(_this._add, _this._target);
  86000. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  86001. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  86002. scene._forcedViewPosition = _this.position;
  86003. });
  86004. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  86005. scene._forcedViewPosition = null;
  86006. scene.updateTransformMatrix(true);
  86007. });
  86008. if (scene.activeCamera) {
  86009. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86010. }
  86011. }
  86012. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  86013. get: function () {
  86014. return this._renderTargetTexture.samples;
  86015. },
  86016. set: function (value) {
  86017. this._renderTargetTexture.samples = value;
  86018. },
  86019. enumerable: true,
  86020. configurable: true
  86021. });
  86022. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  86023. get: function () {
  86024. return this._renderTargetTexture.refreshRate;
  86025. },
  86026. set: function (value) {
  86027. this._renderTargetTexture.refreshRate = value;
  86028. },
  86029. enumerable: true,
  86030. configurable: true
  86031. });
  86032. ReflectionProbe.prototype.getScene = function () {
  86033. return this._scene;
  86034. };
  86035. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  86036. get: function () {
  86037. return this._renderTargetTexture;
  86038. },
  86039. enumerable: true,
  86040. configurable: true
  86041. });
  86042. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  86043. get: function () {
  86044. return this._renderTargetTexture.renderList;
  86045. },
  86046. enumerable: true,
  86047. configurable: true
  86048. });
  86049. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  86050. this._attachedMesh = mesh;
  86051. };
  86052. /**
  86053. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  86054. *
  86055. * @param renderingGroupId The rendering group id corresponding to its index
  86056. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  86057. */
  86058. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  86059. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  86060. };
  86061. ReflectionProbe.prototype.dispose = function () {
  86062. var index = this._scene.reflectionProbes.indexOf(this);
  86063. if (index !== -1) {
  86064. // Remove from the scene if found
  86065. this._scene.reflectionProbes.splice(index, 1);
  86066. }
  86067. if (this._renderTargetTexture) {
  86068. this._renderTargetTexture.dispose();
  86069. this._renderTargetTexture = null;
  86070. }
  86071. };
  86072. return ReflectionProbe;
  86073. }());
  86074. BABYLON.ReflectionProbe = ReflectionProbe;
  86075. })(BABYLON || (BABYLON = {}));
  86076. //# sourceMappingURL=babylon.reflectionProbe.js.map
  86077. var BABYLON;
  86078. (function (BABYLON) {
  86079. var Layer = /** @class */ (function () {
  86080. function Layer(name, imgUrl, scene, isBackground, color) {
  86081. this.name = name;
  86082. this.scale = new BABYLON.Vector2(1, 1);
  86083. this.offset = new BABYLON.Vector2(0, 0);
  86084. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  86085. this.layerMask = 0x0FFFFFFF;
  86086. this._vertexBuffers = {};
  86087. // Events
  86088. /**
  86089. * An event triggered when the layer is disposed.
  86090. * @type {BABYLON.Observable}
  86091. */
  86092. this.onDisposeObservable = new BABYLON.Observable();
  86093. /**
  86094. * An event triggered before rendering the scene
  86095. * @type {BABYLON.Observable}
  86096. */
  86097. this.onBeforeRenderObservable = new BABYLON.Observable();
  86098. /**
  86099. * An event triggered after rendering the scene
  86100. * @type {BABYLON.Observable}
  86101. */
  86102. this.onAfterRenderObservable = new BABYLON.Observable();
  86103. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  86104. this.isBackground = isBackground === undefined ? true : isBackground;
  86105. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  86106. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  86107. this._scene.layers.push(this);
  86108. var engine = this._scene.getEngine();
  86109. // VBO
  86110. var vertices = [];
  86111. vertices.push(1, 1);
  86112. vertices.push(-1, 1);
  86113. vertices.push(-1, -1);
  86114. vertices.push(1, -1);
  86115. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86116. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86117. this._createIndexBuffer();
  86118. // Effects
  86119. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86120. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86121. }
  86122. Object.defineProperty(Layer.prototype, "onDispose", {
  86123. set: function (callback) {
  86124. if (this._onDisposeObserver) {
  86125. this.onDisposeObservable.remove(this._onDisposeObserver);
  86126. }
  86127. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86128. },
  86129. enumerable: true,
  86130. configurable: true
  86131. });
  86132. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86133. set: function (callback) {
  86134. if (this._onBeforeRenderObserver) {
  86135. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86136. }
  86137. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86138. },
  86139. enumerable: true,
  86140. configurable: true
  86141. });
  86142. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86143. set: function (callback) {
  86144. if (this._onAfterRenderObserver) {
  86145. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86146. }
  86147. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86148. },
  86149. enumerable: true,
  86150. configurable: true
  86151. });
  86152. Layer.prototype._createIndexBuffer = function () {
  86153. var engine = this._scene.getEngine();
  86154. // Indices
  86155. var indices = [];
  86156. indices.push(0);
  86157. indices.push(1);
  86158. indices.push(2);
  86159. indices.push(0);
  86160. indices.push(2);
  86161. indices.push(3);
  86162. this._indexBuffer = engine.createIndexBuffer(indices);
  86163. };
  86164. Layer.prototype._rebuild = function () {
  86165. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86166. if (vb) {
  86167. vb._rebuild();
  86168. }
  86169. this._createIndexBuffer();
  86170. };
  86171. Layer.prototype.render = function () {
  86172. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86173. // Check
  86174. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86175. return;
  86176. var engine = this._scene.getEngine();
  86177. this.onBeforeRenderObservable.notifyObservers(this);
  86178. // Render
  86179. engine.enableEffect(currentEffect);
  86180. engine.setState(false);
  86181. // Texture
  86182. currentEffect.setTexture("textureSampler", this.texture);
  86183. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86184. // Color
  86185. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86186. // Scale / offset
  86187. currentEffect.setVector2("offset", this.offset);
  86188. currentEffect.setVector2("scale", this.scale);
  86189. // VBOs
  86190. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86191. // Draw order
  86192. if (!this.alphaTest) {
  86193. engine.setAlphaMode(this.alphaBlendingMode);
  86194. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86195. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86196. }
  86197. else {
  86198. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86199. }
  86200. this.onAfterRenderObservable.notifyObservers(this);
  86201. };
  86202. Layer.prototype.dispose = function () {
  86203. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86204. if (vertexBuffer) {
  86205. vertexBuffer.dispose();
  86206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86207. }
  86208. if (this._indexBuffer) {
  86209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86210. this._indexBuffer = null;
  86211. }
  86212. if (this.texture) {
  86213. this.texture.dispose();
  86214. this.texture = null;
  86215. }
  86216. // Remove from scene
  86217. var index = this._scene.layers.indexOf(this);
  86218. this._scene.layers.splice(index, 1);
  86219. // Callback
  86220. this.onDisposeObservable.notifyObservers(this);
  86221. this.onDisposeObservable.clear();
  86222. this.onAfterRenderObservable.clear();
  86223. this.onBeforeRenderObservable.clear();
  86224. };
  86225. return Layer;
  86226. }());
  86227. BABYLON.Layer = Layer;
  86228. })(BABYLON || (BABYLON = {}));
  86229. //# sourceMappingURL=babylon.layer.js.map
  86230. var BABYLON;
  86231. (function (BABYLON) {
  86232. var TextureTools = /** @class */ (function () {
  86233. function TextureTools() {
  86234. }
  86235. /**
  86236. * Uses the GPU to create a copy texture rescaled at a given size
  86237. * @param texture Texture to copy from
  86238. * @param width Desired width
  86239. * @param height Desired height
  86240. * @return Generated texture
  86241. */
  86242. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86243. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86244. var scene = texture.getScene();
  86245. var engine = scene.getEngine();
  86246. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86247. rtt.wrapU = texture.wrapU;
  86248. rtt.wrapV = texture.wrapV;
  86249. rtt.uOffset = texture.uOffset;
  86250. rtt.vOffset = texture.vOffset;
  86251. rtt.uScale = texture.uScale;
  86252. rtt.vScale = texture.vScale;
  86253. rtt.uAng = texture.uAng;
  86254. rtt.vAng = texture.vAng;
  86255. rtt.wAng = texture.wAng;
  86256. rtt.coordinatesIndex = texture.coordinatesIndex;
  86257. rtt.level = texture.level;
  86258. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86259. rtt._texture.isReady = false;
  86260. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86261. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86262. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86263. passPostProcess.getEffect().executeWhenCompiled(function () {
  86264. passPostProcess.onApply = function (effect) {
  86265. effect.setTexture("textureSampler", texture);
  86266. };
  86267. var internalTexture = rtt.getInternalTexture();
  86268. if (internalTexture) {
  86269. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86270. engine.unBindFramebuffer(internalTexture);
  86271. rtt.disposeFramebufferObjects();
  86272. passPostProcess.dispose();
  86273. internalTexture.isReady = true;
  86274. }
  86275. });
  86276. return rtt;
  86277. };
  86278. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86279. if (!scene._environmentBRDFTexture) {
  86280. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86281. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86282. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86283. scene._environmentBRDFTexture = texture;
  86284. }
  86285. return scene._environmentBRDFTexture;
  86286. };
  86287. 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=";
  86288. return TextureTools;
  86289. }());
  86290. BABYLON.TextureTools = TextureTools;
  86291. })(BABYLON || (BABYLON = {}));
  86292. //# sourceMappingURL=babylon.textureTools.js.map
  86293. var BABYLON;
  86294. (function (BABYLON) {
  86295. var FramingBehavior = /** @class */ (function () {
  86296. function FramingBehavior() {
  86297. this._mode = FramingBehavior.FitFrustumSidesMode;
  86298. this._radiusScale = 1.0;
  86299. this._positionScale = 0.5;
  86300. this._defaultElevation = 0.3;
  86301. this._elevationReturnTime = 1500;
  86302. this._elevationReturnWaitTime = 1000;
  86303. this._zoomStopsAnimation = false;
  86304. this._framingTime = 1500;
  86305. this._isPointerDown = false;
  86306. this._lastInteractionTime = -Infinity;
  86307. // Framing control
  86308. this._animatables = new Array();
  86309. this._betaIsAnimating = false;
  86310. }
  86311. Object.defineProperty(FramingBehavior.prototype, "name", {
  86312. get: function () {
  86313. return "Framing";
  86314. },
  86315. enumerable: true,
  86316. configurable: true
  86317. });
  86318. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86319. /**
  86320. * Gets current mode used by the behavior.
  86321. */
  86322. get: function () {
  86323. return this._mode;
  86324. },
  86325. /**
  86326. * Sets the current mode used by the behavior
  86327. */
  86328. set: function (mode) {
  86329. this._mode = mode;
  86330. },
  86331. enumerable: true,
  86332. configurable: true
  86333. });
  86334. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86335. /**
  86336. * Gets the scale applied to the radius
  86337. */
  86338. get: function () {
  86339. return this._radiusScale;
  86340. },
  86341. /**
  86342. * Sets the scale applied to the radius (1 by default)
  86343. */
  86344. set: function (radius) {
  86345. this._radiusScale = radius;
  86346. },
  86347. enumerable: true,
  86348. configurable: true
  86349. });
  86350. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86351. /**
  86352. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86353. */
  86354. get: function () {
  86355. return this._positionScale;
  86356. },
  86357. /**
  86358. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86359. */
  86360. set: function (scale) {
  86361. this._positionScale = scale;
  86362. },
  86363. enumerable: true,
  86364. configurable: true
  86365. });
  86366. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86367. /**
  86368. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86369. * behaviour is triggered, in radians.
  86370. */
  86371. get: function () {
  86372. return this._defaultElevation;
  86373. },
  86374. /**
  86375. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86376. * behaviour is triggered, in radians.
  86377. */
  86378. set: function (elevation) {
  86379. this._defaultElevation = elevation;
  86380. },
  86381. enumerable: true,
  86382. configurable: true
  86383. });
  86384. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86385. /**
  86386. * Gets the time (in milliseconds) taken to return to the default beta position.
  86387. * Negative value indicates camera should not return to default.
  86388. */
  86389. get: function () {
  86390. return this._elevationReturnTime;
  86391. },
  86392. /**
  86393. * Sets the time (in milliseconds) taken to return to the default beta position.
  86394. * Negative value indicates camera should not return to default.
  86395. */
  86396. set: function (speed) {
  86397. this._elevationReturnTime = speed;
  86398. },
  86399. enumerable: true,
  86400. configurable: true
  86401. });
  86402. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86403. /**
  86404. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86405. */
  86406. get: function () {
  86407. return this._elevationReturnWaitTime;
  86408. },
  86409. /**
  86410. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86411. */
  86412. set: function (time) {
  86413. this._elevationReturnWaitTime = time;
  86414. },
  86415. enumerable: true,
  86416. configurable: true
  86417. });
  86418. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86419. /**
  86420. * Gets the flag that indicates if user zooming should stop animation.
  86421. */
  86422. get: function () {
  86423. return this._zoomStopsAnimation;
  86424. },
  86425. /**
  86426. * Sets the flag that indicates if user zooming should stop animation.
  86427. */
  86428. set: function (flag) {
  86429. this._zoomStopsAnimation = flag;
  86430. },
  86431. enumerable: true,
  86432. configurable: true
  86433. });
  86434. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86435. /**
  86436. * Gets the transition time when framing the mesh, in milliseconds
  86437. */
  86438. get: function () {
  86439. return this._framingTime;
  86440. },
  86441. /**
  86442. * Sets the transition time when framing the mesh, in milliseconds
  86443. */
  86444. set: function (time) {
  86445. this._framingTime = time;
  86446. },
  86447. enumerable: true,
  86448. configurable: true
  86449. });
  86450. FramingBehavior.prototype.init = function () {
  86451. // Do notihng
  86452. };
  86453. FramingBehavior.prototype.attach = function (camera) {
  86454. var _this = this;
  86455. this._attachedCamera = camera;
  86456. var scene = this._attachedCamera.getScene();
  86457. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86458. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86459. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86460. _this._isPointerDown = true;
  86461. return;
  86462. }
  86463. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86464. _this._isPointerDown = false;
  86465. }
  86466. });
  86467. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86468. if (mesh) {
  86469. _this.zoomOnMesh(mesh);
  86470. }
  86471. });
  86472. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86473. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86474. _this._applyUserInteraction();
  86475. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86476. // back to the default position after a given timeout
  86477. _this._maintainCameraAboveGround();
  86478. });
  86479. };
  86480. FramingBehavior.prototype.detach = function () {
  86481. if (!this._attachedCamera) {
  86482. return;
  86483. }
  86484. var scene = this._attachedCamera.getScene();
  86485. if (this._onPrePointerObservableObserver) {
  86486. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86487. }
  86488. if (this._onAfterCheckInputsObserver) {
  86489. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86490. }
  86491. if (this._onMeshTargetChangedObserver) {
  86492. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86493. }
  86494. this._attachedCamera = null;
  86495. };
  86496. /**
  86497. * Targets the given mesh and updates zoom level accordingly.
  86498. * @param mesh The mesh to target.
  86499. * @param radius Optional. If a cached radius position already exists, overrides default.
  86500. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86501. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86502. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86503. */
  86504. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86505. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86506. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86507. mesh.computeWorldMatrix(true);
  86508. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86509. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86510. };
  86511. /**
  86512. * Targets the given mesh with its children and updates zoom level accordingly.
  86513. * @param mesh The mesh to target.
  86514. * @param radius Optional. If a cached radius position already exists, overrides default.
  86515. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86516. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86517. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86518. */
  86519. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86520. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86521. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86522. mesh.computeWorldMatrix(true);
  86523. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86524. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86525. };
  86526. /**
  86527. * Targets the given meshes with their children and updates zoom level accordingly.
  86528. * @param meshes The mesh to target.
  86529. * @param radius Optional. If a cached radius position already exists, overrides default.
  86530. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86531. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86532. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86533. */
  86534. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86535. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86536. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86537. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86538. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86539. for (var i = 0; i < meshes.length; i++) {
  86540. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86541. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86542. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86543. }
  86544. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86545. };
  86546. /**
  86547. * Targets the given mesh and updates zoom level accordingly.
  86548. * @param mesh The mesh to target.
  86549. * @param radius Optional. If a cached radius position already exists, overrides default.
  86550. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86551. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86552. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86553. */
  86554. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86555. var _this = this;
  86556. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86557. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86558. var zoomTarget;
  86559. if (!this._attachedCamera) {
  86560. return;
  86561. }
  86562. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86563. var bottom = minimumWorld.y;
  86564. var top = maximumWorld.y;
  86565. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86566. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86567. if (focusOnOriginXZ) {
  86568. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86569. }
  86570. else {
  86571. var centerWorld = minimumWorld.add(radiusWorld);
  86572. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86573. }
  86574. if (!this._vectorTransition) {
  86575. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86576. }
  86577. this._betaIsAnimating = true;
  86578. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86579. if (animatable) {
  86580. this._animatables.push(animatable);
  86581. }
  86582. // sets the radius and lower radius bounds
  86583. // Small delta ensures camera is not always at lower zoom limit.
  86584. var radius = 0;
  86585. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86586. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86587. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86588. radius = position;
  86589. }
  86590. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86591. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86592. if (this._attachedCamera.lowerRadiusLimit === null) {
  86593. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86594. }
  86595. }
  86596. // Set sensibilities
  86597. var extend = maximumWorld.subtract(minimumWorld).length();
  86598. this._attachedCamera.panningSensibility = 5000 / extend;
  86599. this._attachedCamera.wheelPrecision = 100 / radius;
  86600. // transition to new radius
  86601. if (!this._radiusTransition) {
  86602. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86603. }
  86604. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86605. if (onAnimationEnd) {
  86606. onAnimationEnd();
  86607. }
  86608. if (_this._attachedCamera) {
  86609. _this._attachedCamera.storeState();
  86610. }
  86611. });
  86612. if (animatable) {
  86613. this._animatables.push(animatable);
  86614. }
  86615. };
  86616. /**
  86617. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86618. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86619. * frustum width.
  86620. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86621. * to fully enclose the mesh in the viewing frustum.
  86622. */
  86623. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86624. var size = maximumWorld.subtract(minimumWorld);
  86625. var boxVectorGlobalDiagonal = size.length();
  86626. var frustumSlope = this._getFrustumSlope();
  86627. // Formula for setting distance
  86628. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86629. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86630. // Horizon distance
  86631. var radius = radiusWithoutFraming * this._radiusScale;
  86632. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86633. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86634. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86635. var camera = this._attachedCamera;
  86636. if (!camera) {
  86637. return 0;
  86638. }
  86639. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86640. // Don't exceed the requested limit
  86641. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86642. }
  86643. // Don't exceed the upper radius limit
  86644. if (camera.upperRadiusLimit) {
  86645. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86646. }
  86647. return distance;
  86648. };
  86649. /**
  86650. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86651. * is automatically returned to its default position (expected to be above ground plane).
  86652. */
  86653. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86654. var _this = this;
  86655. if (this._elevationReturnTime < 0) {
  86656. return;
  86657. }
  86658. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86659. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86660. var limitBeta = Math.PI * 0.5;
  86661. // Bring the camera back up if below the ground plane
  86662. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86663. this._betaIsAnimating = true;
  86664. //Transition to new position
  86665. this.stopAllAnimations();
  86666. if (!this._betaTransition) {
  86667. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86668. }
  86669. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86670. _this._clearAnimationLocks();
  86671. _this.stopAllAnimations();
  86672. });
  86673. if (animatabe) {
  86674. this._animatables.push(animatabe);
  86675. }
  86676. }
  86677. };
  86678. /**
  86679. * Returns the frustum slope based on the canvas ratio and camera FOV
  86680. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86681. */
  86682. FramingBehavior.prototype._getFrustumSlope = function () {
  86683. // Calculate the viewport ratio
  86684. // Aspect Ratio is Height/Width.
  86685. var camera = this._attachedCamera;
  86686. if (!camera) {
  86687. return BABYLON.Vector2.Zero();
  86688. }
  86689. var engine = camera.getScene().getEngine();
  86690. var aspectRatio = engine.getAspectRatio(camera);
  86691. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86692. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86693. var frustumSlopeY = Math.tan(camera.fov / 2);
  86694. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86695. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86696. // along the forward vector.
  86697. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86698. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86699. };
  86700. /**
  86701. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86702. */
  86703. FramingBehavior.prototype._clearAnimationLocks = function () {
  86704. this._betaIsAnimating = false;
  86705. };
  86706. /**
  86707. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86708. */
  86709. FramingBehavior.prototype._applyUserInteraction = function () {
  86710. if (this.isUserIsMoving) {
  86711. this._lastInteractionTime = BABYLON.Tools.Now;
  86712. this.stopAllAnimations();
  86713. this._clearAnimationLocks();
  86714. }
  86715. };
  86716. /**
  86717. * Stops and removes all animations that have been applied to the camera
  86718. */
  86719. FramingBehavior.prototype.stopAllAnimations = function () {
  86720. if (this._attachedCamera) {
  86721. this._attachedCamera.animations = [];
  86722. }
  86723. while (this._animatables.length) {
  86724. if (this._animatables[0]) {
  86725. this._animatables[0].onAnimationEnd = null;
  86726. this._animatables[0].stop();
  86727. }
  86728. this._animatables.shift();
  86729. }
  86730. };
  86731. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86732. /**
  86733. * Gets a value indicating if the user is moving the camera
  86734. */
  86735. get: function () {
  86736. if (!this._attachedCamera) {
  86737. return false;
  86738. }
  86739. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86740. this._attachedCamera.inertialBetaOffset !== 0 ||
  86741. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86742. this._attachedCamera.inertialPanningX !== 0 ||
  86743. this._attachedCamera.inertialPanningY !== 0 ||
  86744. this._isPointerDown;
  86745. },
  86746. enumerable: true,
  86747. configurable: true
  86748. });
  86749. /**
  86750. * The easing function used by animations
  86751. */
  86752. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86753. /**
  86754. * The easing mode used by animations
  86755. */
  86756. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86757. // Statics
  86758. /**
  86759. * The camera can move all the way towards the mesh.
  86760. */
  86761. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86762. /**
  86763. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86764. */
  86765. FramingBehavior.FitFrustumSidesMode = 1;
  86766. return FramingBehavior;
  86767. }());
  86768. BABYLON.FramingBehavior = FramingBehavior;
  86769. })(BABYLON || (BABYLON = {}));
  86770. //# sourceMappingURL=babylon.framingBehavior.js.map
  86771. var BABYLON;
  86772. (function (BABYLON) {
  86773. /**
  86774. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86775. */
  86776. var BouncingBehavior = /** @class */ (function () {
  86777. function BouncingBehavior() {
  86778. /**
  86779. * The duration of the animation, in milliseconds
  86780. */
  86781. this.transitionDuration = 450;
  86782. /**
  86783. * Length of the distance animated by the transition when lower radius is reached
  86784. */
  86785. this.lowerRadiusTransitionRange = 2;
  86786. /**
  86787. * Length of the distance animated by the transition when upper radius is reached
  86788. */
  86789. this.upperRadiusTransitionRange = -2;
  86790. this._autoTransitionRange = false;
  86791. // Animations
  86792. this._radiusIsAnimating = false;
  86793. this._radiusBounceTransition = null;
  86794. this._animatables = new Array();
  86795. }
  86796. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86797. get: function () {
  86798. return "Bouncing";
  86799. },
  86800. enumerable: true,
  86801. configurable: true
  86802. });
  86803. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86804. /**
  86805. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86806. */
  86807. get: function () {
  86808. return this._autoTransitionRange;
  86809. },
  86810. /**
  86811. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86812. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86813. */
  86814. set: function (value) {
  86815. var _this = this;
  86816. if (this._autoTransitionRange === value) {
  86817. return;
  86818. }
  86819. this._autoTransitionRange = value;
  86820. var camera = this._attachedCamera;
  86821. if (!camera) {
  86822. return;
  86823. }
  86824. if (value) {
  86825. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86826. if (!mesh) {
  86827. return;
  86828. }
  86829. mesh.computeWorldMatrix(true);
  86830. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86831. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86832. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86833. });
  86834. }
  86835. else if (this._onMeshTargetChangedObserver) {
  86836. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86837. }
  86838. },
  86839. enumerable: true,
  86840. configurable: true
  86841. });
  86842. BouncingBehavior.prototype.init = function () {
  86843. // Do notihng
  86844. };
  86845. BouncingBehavior.prototype.attach = function (camera) {
  86846. var _this = this;
  86847. this._attachedCamera = camera;
  86848. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86849. if (!_this._attachedCamera) {
  86850. return;
  86851. }
  86852. // Add the bounce animation to the lower radius limit
  86853. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86854. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86855. }
  86856. // Add the bounce animation to the upper radius limit
  86857. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86858. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86859. }
  86860. });
  86861. };
  86862. BouncingBehavior.prototype.detach = function () {
  86863. if (!this._attachedCamera) {
  86864. return;
  86865. }
  86866. if (this._onAfterCheckInputsObserver) {
  86867. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86868. }
  86869. if (this._onMeshTargetChangedObserver) {
  86870. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86871. }
  86872. this._attachedCamera = null;
  86873. };
  86874. /**
  86875. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86876. * @param radiusLimit The limit to check against.
  86877. * @return Bool to indicate if at limit.
  86878. */
  86879. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86880. if (!this._attachedCamera) {
  86881. return false;
  86882. }
  86883. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86884. return true;
  86885. }
  86886. return false;
  86887. };
  86888. /**
  86889. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86890. * @param radiusDelta The delta by which to animate to. Can be negative.
  86891. */
  86892. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86893. var _this = this;
  86894. if (!this._attachedCamera) {
  86895. return;
  86896. }
  86897. if (!this._radiusBounceTransition) {
  86898. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86899. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86900. }
  86901. // Prevent zoom until bounce has completed
  86902. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86903. this._attachedCamera.wheelPrecision = Infinity;
  86904. this._attachedCamera.inertialRadiusOffset = 0;
  86905. // Animate to the radius limit
  86906. this.stopAllAnimations();
  86907. this._radiusIsAnimating = true;
  86908. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86909. if (animatable) {
  86910. this._animatables.push(animatable);
  86911. }
  86912. };
  86913. /**
  86914. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86915. */
  86916. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86917. this._radiusIsAnimating = false;
  86918. if (this._attachedCamera) {
  86919. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86920. }
  86921. };
  86922. /**
  86923. * Stops and removes all animations that have been applied to the camera
  86924. */
  86925. BouncingBehavior.prototype.stopAllAnimations = function () {
  86926. if (this._attachedCamera) {
  86927. this._attachedCamera.animations = [];
  86928. }
  86929. while (this._animatables.length) {
  86930. this._animatables[0].onAnimationEnd = null;
  86931. this._animatables[0].stop();
  86932. this._animatables.shift();
  86933. }
  86934. };
  86935. /**
  86936. * The easing function used by animations
  86937. */
  86938. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86939. /**
  86940. * The easing mode used by animations
  86941. */
  86942. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86943. return BouncingBehavior;
  86944. }());
  86945. BABYLON.BouncingBehavior = BouncingBehavior;
  86946. })(BABYLON || (BABYLON = {}));
  86947. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86948. var BABYLON;
  86949. (function (BABYLON) {
  86950. var AutoRotationBehavior = /** @class */ (function () {
  86951. function AutoRotationBehavior() {
  86952. this._zoomStopsAnimation = false;
  86953. this._idleRotationSpeed = 0.05;
  86954. this._idleRotationWaitTime = 2000;
  86955. this._idleRotationSpinupTime = 2000;
  86956. this._isPointerDown = false;
  86957. this._lastFrameTime = null;
  86958. this._lastInteractionTime = -Infinity;
  86959. this._cameraRotationSpeed = 0;
  86960. this._lastFrameRadius = 0;
  86961. }
  86962. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86963. get: function () {
  86964. return "AutoRotation";
  86965. },
  86966. enumerable: true,
  86967. configurable: true
  86968. });
  86969. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86970. /**
  86971. * Gets the flag that indicates if user zooming should stop animation.
  86972. */
  86973. get: function () {
  86974. return this._zoomStopsAnimation;
  86975. },
  86976. /**
  86977. * Sets the flag that indicates if user zooming should stop animation.
  86978. */
  86979. set: function (flag) {
  86980. this._zoomStopsAnimation = flag;
  86981. },
  86982. enumerable: true,
  86983. configurable: true
  86984. });
  86985. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  86986. /**
  86987. * Gets the default speed at which the camera rotates around the model.
  86988. */
  86989. get: function () {
  86990. return this._idleRotationSpeed;
  86991. },
  86992. /**
  86993. * Sets the default speed at which the camera rotates around the model.
  86994. */
  86995. set: function (speed) {
  86996. this._idleRotationSpeed = speed;
  86997. },
  86998. enumerable: true,
  86999. configurable: true
  87000. });
  87001. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  87002. /**
  87003. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  87004. */
  87005. get: function () {
  87006. return this._idleRotationWaitTime;
  87007. },
  87008. /**
  87009. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  87010. */
  87011. set: function (time) {
  87012. this._idleRotationWaitTime = time;
  87013. },
  87014. enumerable: true,
  87015. configurable: true
  87016. });
  87017. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  87018. /**
  87019. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87020. */
  87021. get: function () {
  87022. return this._idleRotationSpinupTime;
  87023. },
  87024. /**
  87025. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  87026. */
  87027. set: function (time) {
  87028. this._idleRotationSpinupTime = time;
  87029. },
  87030. enumerable: true,
  87031. configurable: true
  87032. });
  87033. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  87034. /**
  87035. * Gets a value indicating if the camera is currently rotating because of this behavior
  87036. */
  87037. get: function () {
  87038. return Math.abs(this._cameraRotationSpeed) > 0;
  87039. },
  87040. enumerable: true,
  87041. configurable: true
  87042. });
  87043. AutoRotationBehavior.prototype.init = function () {
  87044. // Do notihng
  87045. };
  87046. AutoRotationBehavior.prototype.attach = function (camera) {
  87047. var _this = this;
  87048. this._attachedCamera = camera;
  87049. var scene = this._attachedCamera.getScene();
  87050. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  87051. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87052. _this._isPointerDown = true;
  87053. return;
  87054. }
  87055. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  87056. _this._isPointerDown = false;
  87057. }
  87058. });
  87059. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  87060. var now = BABYLON.Tools.Now;
  87061. var dt = 0;
  87062. if (_this._lastFrameTime != null) {
  87063. dt = now - _this._lastFrameTime;
  87064. }
  87065. _this._lastFrameTime = now;
  87066. // Stop the animation if there is user interaction and the animation should stop for this interaction
  87067. _this._applyUserInteraction();
  87068. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  87069. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  87070. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  87071. // Step camera rotation by rotation speed
  87072. if (_this._attachedCamera) {
  87073. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  87074. }
  87075. });
  87076. };
  87077. AutoRotationBehavior.prototype.detach = function () {
  87078. if (!this._attachedCamera) {
  87079. return;
  87080. }
  87081. var scene = this._attachedCamera.getScene();
  87082. if (this._onPrePointerObservableObserver) {
  87083. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  87084. }
  87085. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  87086. this._attachedCamera = null;
  87087. };
  87088. /**
  87089. * Returns true if user is scrolling.
  87090. * @return true if user is scrolling.
  87091. */
  87092. AutoRotationBehavior.prototype._userIsZooming = function () {
  87093. if (!this._attachedCamera) {
  87094. return false;
  87095. }
  87096. return this._attachedCamera.inertialRadiusOffset !== 0;
  87097. };
  87098. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  87099. if (!this._attachedCamera) {
  87100. return false;
  87101. }
  87102. var zoomHasHitLimit = false;
  87103. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  87104. zoomHasHitLimit = true;
  87105. }
  87106. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  87107. this._lastFrameRadius = this._attachedCamera.radius;
  87108. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  87109. };
  87110. /**
  87111. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  87112. */
  87113. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  87114. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  87115. this._lastInteractionTime = BABYLON.Tools.Now;
  87116. }
  87117. };
  87118. // Tools
  87119. AutoRotationBehavior.prototype._userIsMoving = function () {
  87120. if (!this._attachedCamera) {
  87121. return false;
  87122. }
  87123. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87124. this._attachedCamera.inertialBetaOffset !== 0 ||
  87125. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87126. this._attachedCamera.inertialPanningX !== 0 ||
  87127. this._attachedCamera.inertialPanningY !== 0 ||
  87128. this._isPointerDown;
  87129. };
  87130. return AutoRotationBehavior;
  87131. }());
  87132. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87133. })(BABYLON || (BABYLON = {}));
  87134. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87135. var BABYLON;
  87136. (function (BABYLON) {
  87137. /**
  87138. * This class can be used to get instrumentation data from a Babylon engine
  87139. */
  87140. var EngineInstrumentation = /** @class */ (function () {
  87141. function EngineInstrumentation(engine) {
  87142. this.engine = engine;
  87143. this._captureGPUFrameTime = false;
  87144. this._gpuFrameTime = new BABYLON.PerfCounter();
  87145. this._captureShaderCompilationTime = false;
  87146. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87147. // Observers
  87148. this._onBeginFrameObserver = null;
  87149. this._onEndFrameObserver = null;
  87150. this._onBeforeShaderCompilationObserver = null;
  87151. this._onAfterShaderCompilationObserver = null;
  87152. }
  87153. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87154. // Properties
  87155. /**
  87156. * Gets the perf counter used for GPU frame time
  87157. */
  87158. get: function () {
  87159. return this._gpuFrameTime;
  87160. },
  87161. enumerable: true,
  87162. configurable: true
  87163. });
  87164. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87165. /**
  87166. * Gets the GPU frame time capture status
  87167. */
  87168. get: function () {
  87169. return this._captureGPUFrameTime;
  87170. },
  87171. /**
  87172. * Enable or disable the GPU frame time capture
  87173. */
  87174. set: function (value) {
  87175. var _this = this;
  87176. if (value === this._captureGPUFrameTime) {
  87177. return;
  87178. }
  87179. this._captureGPUFrameTime = value;
  87180. if (value) {
  87181. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87182. if (!_this._gpuFrameTimeToken) {
  87183. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87184. }
  87185. });
  87186. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87187. if (!_this._gpuFrameTimeToken) {
  87188. return;
  87189. }
  87190. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87191. if (time > -1) {
  87192. _this._gpuFrameTimeToken = null;
  87193. _this._gpuFrameTime.fetchNewFrame();
  87194. _this._gpuFrameTime.addCount(time, true);
  87195. }
  87196. });
  87197. }
  87198. else {
  87199. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87200. this._onBeginFrameObserver = null;
  87201. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87202. this._onEndFrameObserver = null;
  87203. }
  87204. },
  87205. enumerable: true,
  87206. configurable: true
  87207. });
  87208. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87209. /**
  87210. * Gets the perf counter used for shader compilation time
  87211. */
  87212. get: function () {
  87213. return this._shaderCompilationTime;
  87214. },
  87215. enumerable: true,
  87216. configurable: true
  87217. });
  87218. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87219. /**
  87220. * Gets the shader compilation time capture status
  87221. */
  87222. get: function () {
  87223. return this._captureShaderCompilationTime;
  87224. },
  87225. /**
  87226. * Enable or disable the shader compilation time capture
  87227. */
  87228. set: function (value) {
  87229. var _this = this;
  87230. if (value === this._captureShaderCompilationTime) {
  87231. return;
  87232. }
  87233. this._captureShaderCompilationTime = value;
  87234. if (value) {
  87235. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87236. _this._shaderCompilationTime.fetchNewFrame();
  87237. _this._shaderCompilationTime.beginMonitoring();
  87238. });
  87239. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87240. _this._shaderCompilationTime.endMonitoring();
  87241. });
  87242. }
  87243. else {
  87244. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87245. this._onBeforeShaderCompilationObserver = null;
  87246. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87247. this._onAfterShaderCompilationObserver = null;
  87248. }
  87249. },
  87250. enumerable: true,
  87251. configurable: true
  87252. });
  87253. EngineInstrumentation.prototype.dispose = function () {
  87254. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87255. this._onBeginFrameObserver = null;
  87256. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87257. this._onEndFrameObserver = null;
  87258. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87259. this._onBeforeShaderCompilationObserver = null;
  87260. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87261. this._onAfterShaderCompilationObserver = null;
  87262. this.engine = null;
  87263. };
  87264. return EngineInstrumentation;
  87265. }());
  87266. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87267. })(BABYLON || (BABYLON = {}));
  87268. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87269. var BABYLON;
  87270. (function (BABYLON) {
  87271. /**
  87272. * This class can be used to get instrumentation data from a Babylon engine
  87273. */
  87274. var SceneInstrumentation = /** @class */ (function () {
  87275. function SceneInstrumentation(scene) {
  87276. var _this = this;
  87277. this.scene = scene;
  87278. this._captureActiveMeshesEvaluationTime = false;
  87279. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87280. this._captureRenderTargetsRenderTime = false;
  87281. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87282. this._captureFrameTime = false;
  87283. this._frameTime = new BABYLON.PerfCounter();
  87284. this._captureRenderTime = false;
  87285. this._renderTime = new BABYLON.PerfCounter();
  87286. this._captureInterFrameTime = false;
  87287. this._interFrameTime = new BABYLON.PerfCounter();
  87288. this._captureParticlesRenderTime = false;
  87289. this._particlesRenderTime = new BABYLON.PerfCounter();
  87290. this._captureSpritesRenderTime = false;
  87291. this._spritesRenderTime = new BABYLON.PerfCounter();
  87292. this._capturePhysicsTime = false;
  87293. this._physicsTime = new BABYLON.PerfCounter();
  87294. this._captureAnimationsTime = false;
  87295. this._animationsTime = new BABYLON.PerfCounter();
  87296. // Observers
  87297. this._onBeforeActiveMeshesEvaluationObserver = null;
  87298. this._onAfterActiveMeshesEvaluationObserver = null;
  87299. this._onBeforeRenderTargetsRenderObserver = null;
  87300. this._onAfterRenderTargetsRenderObserver = null;
  87301. this._onAfterRenderObserver = null;
  87302. this._onBeforeDrawPhaseObserver = null;
  87303. this._onAfterDrawPhaseObserver = null;
  87304. this._onBeforeAnimationsObserver = null;
  87305. this._onBeforeParticlesRenderingObserver = null;
  87306. this._onAfterParticlesRenderingObserver = null;
  87307. this._onBeforeSpritesRenderingObserver = null;
  87308. this._onAfterSpritesRenderingObserver = null;
  87309. this._onBeforePhysicsObserver = null;
  87310. this._onAfterPhysicsObserver = null;
  87311. this._onAfterAnimationsObserver = null;
  87312. // Before render
  87313. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87314. if (_this._captureActiveMeshesEvaluationTime) {
  87315. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87316. }
  87317. if (_this._captureRenderTargetsRenderTime) {
  87318. _this._renderTargetsRenderTime.fetchNewFrame();
  87319. }
  87320. if (_this._captureFrameTime) {
  87321. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87322. _this._frameTime.beginMonitoring();
  87323. }
  87324. if (_this._captureInterFrameTime) {
  87325. _this._interFrameTime.endMonitoring();
  87326. }
  87327. if (_this._captureParticlesRenderTime) {
  87328. _this._particlesRenderTime.fetchNewFrame();
  87329. }
  87330. if (_this._captureSpritesRenderTime) {
  87331. _this._spritesRenderTime.fetchNewFrame();
  87332. }
  87333. if (_this._captureAnimationsTime) {
  87334. _this._animationsTime.beginMonitoring();
  87335. }
  87336. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87337. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87338. });
  87339. // After render
  87340. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87341. if (_this._captureFrameTime) {
  87342. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87343. _this._frameTime.endMonitoring();
  87344. }
  87345. if (_this._captureRenderTime) {
  87346. _this._renderTime.endMonitoring(false);
  87347. }
  87348. if (_this._captureInterFrameTime) {
  87349. _this._interFrameTime.beginMonitoring();
  87350. }
  87351. });
  87352. }
  87353. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87354. // Properties
  87355. /**
  87356. * Gets the perf counter used for active meshes evaluation time
  87357. */
  87358. get: function () {
  87359. return this._activeMeshesEvaluationTime;
  87360. },
  87361. enumerable: true,
  87362. configurable: true
  87363. });
  87364. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87365. /**
  87366. * Gets the active meshes evaluation time capture status
  87367. */
  87368. get: function () {
  87369. return this._captureActiveMeshesEvaluationTime;
  87370. },
  87371. /**
  87372. * Enable or disable the active meshes evaluation time capture
  87373. */
  87374. set: function (value) {
  87375. var _this = this;
  87376. if (value === this._captureActiveMeshesEvaluationTime) {
  87377. return;
  87378. }
  87379. this._captureActiveMeshesEvaluationTime = value;
  87380. if (value) {
  87381. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87382. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87383. _this._activeMeshesEvaluationTime.beginMonitoring();
  87384. });
  87385. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87386. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87387. _this._activeMeshesEvaluationTime.endMonitoring();
  87388. });
  87389. }
  87390. else {
  87391. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87392. this._onBeforeActiveMeshesEvaluationObserver = null;
  87393. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87394. this._onAfterActiveMeshesEvaluationObserver = null;
  87395. }
  87396. },
  87397. enumerable: true,
  87398. configurable: true
  87399. });
  87400. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87401. /**
  87402. * Gets the perf counter used for render targets render time
  87403. */
  87404. get: function () {
  87405. return this._renderTargetsRenderTime;
  87406. },
  87407. enumerable: true,
  87408. configurable: true
  87409. });
  87410. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87411. /**
  87412. * Gets the render targets render time capture status
  87413. */
  87414. get: function () {
  87415. return this._captureRenderTargetsRenderTime;
  87416. },
  87417. /**
  87418. * Enable or disable the render targets render time capture
  87419. */
  87420. set: function (value) {
  87421. var _this = this;
  87422. if (value === this._captureRenderTargetsRenderTime) {
  87423. return;
  87424. }
  87425. this._captureRenderTargetsRenderTime = value;
  87426. if (value) {
  87427. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87428. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87429. _this._renderTargetsRenderTime.beginMonitoring();
  87430. });
  87431. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87432. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87433. _this._renderTargetsRenderTime.endMonitoring(false);
  87434. });
  87435. }
  87436. else {
  87437. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87438. this._onBeforeRenderTargetsRenderObserver = null;
  87439. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87440. this._onAfterRenderTargetsRenderObserver = null;
  87441. }
  87442. },
  87443. enumerable: true,
  87444. configurable: true
  87445. });
  87446. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87447. /**
  87448. * Gets the perf counter used for particles render time
  87449. */
  87450. get: function () {
  87451. return this._particlesRenderTime;
  87452. },
  87453. enumerable: true,
  87454. configurable: true
  87455. });
  87456. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87457. /**
  87458. * Gets the particles render time capture status
  87459. */
  87460. get: function () {
  87461. return this._captureParticlesRenderTime;
  87462. },
  87463. /**
  87464. * Enable or disable the particles render time capture
  87465. */
  87466. set: function (value) {
  87467. var _this = this;
  87468. if (value === this._captureParticlesRenderTime) {
  87469. return;
  87470. }
  87471. this._captureParticlesRenderTime = value;
  87472. if (value) {
  87473. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87474. BABYLON.Tools.StartPerformanceCounter("Particles");
  87475. _this._particlesRenderTime.beginMonitoring();
  87476. });
  87477. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87478. BABYLON.Tools.EndPerformanceCounter("Particles");
  87479. _this._particlesRenderTime.endMonitoring(false);
  87480. });
  87481. }
  87482. else {
  87483. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87484. this._onBeforeParticlesRenderingObserver = null;
  87485. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87486. this._onAfterParticlesRenderingObserver = null;
  87487. }
  87488. },
  87489. enumerable: true,
  87490. configurable: true
  87491. });
  87492. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87493. /**
  87494. * Gets the perf counter used for sprites render time
  87495. */
  87496. get: function () {
  87497. return this._spritesRenderTime;
  87498. },
  87499. enumerable: true,
  87500. configurable: true
  87501. });
  87502. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87503. /**
  87504. * Gets the sprites render time capture status
  87505. */
  87506. get: function () {
  87507. return this._captureSpritesRenderTime;
  87508. },
  87509. /**
  87510. * Enable or disable the sprites render time capture
  87511. */
  87512. set: function (value) {
  87513. var _this = this;
  87514. if (value === this._captureSpritesRenderTime) {
  87515. return;
  87516. }
  87517. this._captureSpritesRenderTime = value;
  87518. if (value) {
  87519. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87520. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87521. _this._spritesRenderTime.beginMonitoring();
  87522. });
  87523. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87524. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87525. _this._spritesRenderTime.endMonitoring(false);
  87526. });
  87527. }
  87528. else {
  87529. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87530. this._onBeforeSpritesRenderingObserver = null;
  87531. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87532. this._onAfterSpritesRenderingObserver = null;
  87533. }
  87534. },
  87535. enumerable: true,
  87536. configurable: true
  87537. });
  87538. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87539. /**
  87540. * Gets the perf counter used for physics time
  87541. */
  87542. get: function () {
  87543. return this._physicsTime;
  87544. },
  87545. enumerable: true,
  87546. configurable: true
  87547. });
  87548. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87549. /**
  87550. * Gets the physics time capture status
  87551. */
  87552. get: function () {
  87553. return this._capturePhysicsTime;
  87554. },
  87555. /**
  87556. * Enable or disable the physics time capture
  87557. */
  87558. set: function (value) {
  87559. var _this = this;
  87560. if (value === this._capturePhysicsTime) {
  87561. return;
  87562. }
  87563. this._capturePhysicsTime = value;
  87564. if (value) {
  87565. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87566. BABYLON.Tools.StartPerformanceCounter("Physics");
  87567. _this._physicsTime.beginMonitoring();
  87568. });
  87569. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87570. BABYLON.Tools.EndPerformanceCounter("Physics");
  87571. _this._physicsTime.endMonitoring();
  87572. });
  87573. }
  87574. else {
  87575. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87576. this._onBeforePhysicsObserver = null;
  87577. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87578. this._onAfterPhysicsObserver = null;
  87579. }
  87580. },
  87581. enumerable: true,
  87582. configurable: true
  87583. });
  87584. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87585. /**
  87586. * Gets the perf counter used for animations time
  87587. */
  87588. get: function () {
  87589. return this._animationsTime;
  87590. },
  87591. enumerable: true,
  87592. configurable: true
  87593. });
  87594. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87595. /**
  87596. * Gets the animations time capture status
  87597. */
  87598. get: function () {
  87599. return this._captureAnimationsTime;
  87600. },
  87601. /**
  87602. * Enable or disable the animations time capture
  87603. */
  87604. set: function (value) {
  87605. var _this = this;
  87606. if (value === this._captureAnimationsTime) {
  87607. return;
  87608. }
  87609. this._captureAnimationsTime = value;
  87610. if (value) {
  87611. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87612. _this._animationsTime.endMonitoring();
  87613. });
  87614. }
  87615. else {
  87616. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87617. this._onAfterAnimationsObserver = null;
  87618. }
  87619. },
  87620. enumerable: true,
  87621. configurable: true
  87622. });
  87623. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87624. /**
  87625. * Gets the perf counter used for frame time capture
  87626. */
  87627. get: function () {
  87628. return this._frameTime;
  87629. },
  87630. enumerable: true,
  87631. configurable: true
  87632. });
  87633. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87634. /**
  87635. * Gets the frame time capture status
  87636. */
  87637. get: function () {
  87638. return this._captureFrameTime;
  87639. },
  87640. /**
  87641. * Enable or disable the frame time capture
  87642. */
  87643. set: function (value) {
  87644. this._captureFrameTime = value;
  87645. },
  87646. enumerable: true,
  87647. configurable: true
  87648. });
  87649. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87650. /**
  87651. * Gets the perf counter used for inter-frames time capture
  87652. */
  87653. get: function () {
  87654. return this._interFrameTime;
  87655. },
  87656. enumerable: true,
  87657. configurable: true
  87658. });
  87659. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87660. /**
  87661. * Gets the inter-frames time capture status
  87662. */
  87663. get: function () {
  87664. return this._captureInterFrameTime;
  87665. },
  87666. /**
  87667. * Enable or disable the inter-frames time capture
  87668. */
  87669. set: function (value) {
  87670. this._captureInterFrameTime = value;
  87671. },
  87672. enumerable: true,
  87673. configurable: true
  87674. });
  87675. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87676. /**
  87677. * Gets the perf counter used for render time capture
  87678. */
  87679. get: function () {
  87680. return this._renderTime;
  87681. },
  87682. enumerable: true,
  87683. configurable: true
  87684. });
  87685. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87686. /**
  87687. * Gets the render time capture status
  87688. */
  87689. get: function () {
  87690. return this._captureRenderTime;
  87691. },
  87692. /**
  87693. * Enable or disable the render time capture
  87694. */
  87695. set: function (value) {
  87696. var _this = this;
  87697. if (value === this._captureRenderTime) {
  87698. return;
  87699. }
  87700. this._captureRenderTime = value;
  87701. if (value) {
  87702. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87703. _this._renderTime.beginMonitoring();
  87704. BABYLON.Tools.StartPerformanceCounter("Main render");
  87705. });
  87706. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87707. _this._renderTime.endMonitoring(false);
  87708. BABYLON.Tools.EndPerformanceCounter("Main render");
  87709. });
  87710. }
  87711. else {
  87712. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87713. this._onBeforeDrawPhaseObserver = null;
  87714. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87715. this._onAfterDrawPhaseObserver = null;
  87716. }
  87717. },
  87718. enumerable: true,
  87719. configurable: true
  87720. });
  87721. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87722. /**
  87723. * Gets the perf counter used for draw calls
  87724. */
  87725. get: function () {
  87726. return this.scene.getEngine()._drawCalls;
  87727. },
  87728. enumerable: true,
  87729. configurable: true
  87730. });
  87731. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87732. /**
  87733. * Gets the perf counter used for texture collisions
  87734. */
  87735. get: function () {
  87736. return this.scene.getEngine()._textureCollisions;
  87737. },
  87738. enumerable: true,
  87739. configurable: true
  87740. });
  87741. SceneInstrumentation.prototype.dispose = function () {
  87742. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87743. this._onAfterRenderObserver = null;
  87744. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87745. this._onBeforeActiveMeshesEvaluationObserver = null;
  87746. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87747. this._onAfterActiveMeshesEvaluationObserver = null;
  87748. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87749. this._onBeforeRenderTargetsRenderObserver = null;
  87750. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87751. this._onAfterRenderTargetsRenderObserver = null;
  87752. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87753. this._onBeforeAnimationsObserver = null;
  87754. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87755. this._onBeforeParticlesRenderingObserver = null;
  87756. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87757. this._onAfterParticlesRenderingObserver = null;
  87758. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87759. this._onBeforeSpritesRenderingObserver = null;
  87760. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87761. this._onAfterSpritesRenderingObserver = null;
  87762. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87763. this._onBeforeDrawPhaseObserver = null;
  87764. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87765. this._onAfterDrawPhaseObserver = null;
  87766. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87767. this._onBeforePhysicsObserver = null;
  87768. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87769. this._onAfterPhysicsObserver = null;
  87770. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87771. this._onAfterAnimationsObserver = null;
  87772. this.scene = null;
  87773. };
  87774. return SceneInstrumentation;
  87775. }());
  87776. BABYLON.SceneInstrumentation = SceneInstrumentation;
  87777. })(BABYLON || (BABYLON = {}));
  87778. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  87779. var BABYLON;
  87780. (function (BABYLON) {
  87781. var _TimeToken = /** @class */ (function () {
  87782. function _TimeToken() {
  87783. this._timeElapsedQueryEnded = false;
  87784. }
  87785. return _TimeToken;
  87786. }());
  87787. BABYLON._TimeToken = _TimeToken;
  87788. })(BABYLON || (BABYLON = {}));
  87789. //# sourceMappingURL=babylon.timeToken.js.map
  87790. var BABYLON;
  87791. (function (BABYLON) {
  87792. /**
  87793. * Background material defines definition.
  87794. * @ignore Mainly internal Use
  87795. */
  87796. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  87797. __extends(BackgroundMaterialDefines, _super);
  87798. /**
  87799. * Constructor of the defines.
  87800. */
  87801. function BackgroundMaterialDefines() {
  87802. var _this = _super.call(this) || this;
  87803. /**
  87804. * True if the diffuse texture is in use.
  87805. */
  87806. _this.DIFFUSE = false;
  87807. /**
  87808. * The direct UV channel to use.
  87809. */
  87810. _this.DIFFUSEDIRECTUV = 0;
  87811. /**
  87812. * True if the diffuse texture is in gamma space.
  87813. */
  87814. _this.GAMMADIFFUSE = false;
  87815. /**
  87816. * True if the diffuse texture has opacity in the alpha channel.
  87817. */
  87818. _this.DIFFUSEHASALPHA = false;
  87819. /**
  87820. * True if you want the material to fade to transparent at grazing angle.
  87821. */
  87822. _this.OPACITYFRESNEL = false;
  87823. /**
  87824. * True if an extra blur needs to be added in the reflection.
  87825. */
  87826. _this.REFLECTIONBLUR = false;
  87827. /**
  87828. * True if you want the material to fade to reflection at grazing angle.
  87829. */
  87830. _this.REFLECTIONFRESNEL = false;
  87831. /**
  87832. * True if you want the material to falloff as far as you move away from the scene center.
  87833. */
  87834. _this.REFLECTIONFALLOFF = false;
  87835. /**
  87836. * False if the current Webgl implementation does not support the texture lod extension.
  87837. */
  87838. _this.TEXTURELODSUPPORT = false;
  87839. /**
  87840. * True to ensure the data are premultiplied.
  87841. */
  87842. _this.PREMULTIPLYALPHA = false;
  87843. /**
  87844. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  87845. */
  87846. _this.USERGBCOLOR = false;
  87847. /**
  87848. * True to add noise in order to reduce the banding effect.
  87849. */
  87850. _this.NOISE = false;
  87851. /**
  87852. * is the reflection texture in BGR color scheme?
  87853. * Mainly used to solve a bug in ios10 video tag
  87854. */
  87855. _this.REFLECTIONBGR = false;
  87856. _this.IMAGEPROCESSING = false;
  87857. _this.VIGNETTE = false;
  87858. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87859. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87860. _this.TONEMAPPING = false;
  87861. _this.CONTRAST = false;
  87862. _this.COLORCURVES = false;
  87863. _this.COLORGRADING = false;
  87864. _this.COLORGRADING3D = false;
  87865. _this.SAMPLER3DGREENDEPTH = false;
  87866. _this.SAMPLER3DBGRMAP = false;
  87867. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87868. _this.EXPOSURE = false;
  87869. // Reflection.
  87870. _this.REFLECTION = false;
  87871. _this.REFLECTIONMAP_3D = false;
  87872. _this.REFLECTIONMAP_SPHERICAL = false;
  87873. _this.REFLECTIONMAP_PLANAR = false;
  87874. _this.REFLECTIONMAP_CUBIC = false;
  87875. _this.REFLECTIONMAP_PROJECTION = false;
  87876. _this.REFLECTIONMAP_SKYBOX = false;
  87877. _this.REFLECTIONMAP_EXPLICIT = false;
  87878. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87879. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87880. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87881. _this.INVERTCUBICMAP = false;
  87882. _this.REFLECTIONMAP_OPPOSITEZ = false;
  87883. _this.LODINREFLECTIONALPHA = false;
  87884. _this.GAMMAREFLECTION = false;
  87885. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  87886. // Default BJS.
  87887. _this.MAINUV1 = false;
  87888. _this.MAINUV2 = false;
  87889. _this.UV1 = false;
  87890. _this.UV2 = false;
  87891. _this.CLIPPLANE = false;
  87892. _this.POINTSIZE = false;
  87893. _this.FOG = false;
  87894. _this.NORMAL = false;
  87895. _this.NUM_BONE_INFLUENCERS = 0;
  87896. _this.BonesPerMesh = 0;
  87897. _this.INSTANCES = false;
  87898. _this.SHADOWFLOAT = false;
  87899. _this.rebuild();
  87900. return _this;
  87901. }
  87902. return BackgroundMaterialDefines;
  87903. }(BABYLON.MaterialDefines));
  87904. /**
  87905. * Background material used to create an efficient environement around your scene.
  87906. */
  87907. var BackgroundMaterial = /** @class */ (function (_super) {
  87908. __extends(BackgroundMaterial, _super);
  87909. /**
  87910. * Instantiates a Background Material in the given scene
  87911. * @param name The friendly name of the material
  87912. * @param scene The scene to add the material to
  87913. */
  87914. function BackgroundMaterial(name, scene) {
  87915. var _this = _super.call(this, name, scene) || this;
  87916. /**
  87917. * Key light Color (multiply against the R channel of the environement texture)
  87918. */
  87919. _this.primaryColor = BABYLON.Color3.White();
  87920. /**
  87921. * Key light Level (allowing HDR output of the background)
  87922. */
  87923. _this.primaryLevel = 1;
  87924. /**
  87925. * Secondary light Color (multiply against the G channel of the environement texture)
  87926. */
  87927. _this.secondaryColor = BABYLON.Color3.Gray();
  87928. /**
  87929. * Secondary light Level (allowing HDR output of the background)
  87930. */
  87931. _this.secondaryLevel = 1;
  87932. /**
  87933. * Tertiary light Color (multiply against the B channel of the environement texture)
  87934. */
  87935. _this.tertiaryColor = BABYLON.Color3.Black();
  87936. /**
  87937. * Tertiary light Level (allowing HDR output of the background)
  87938. */
  87939. _this.tertiaryLevel = 1;
  87940. /**
  87941. * Reflection Texture used in the material.
  87942. * Should be author in a specific way for the best result (refer to the documentation).
  87943. */
  87944. _this.reflectionTexture = null;
  87945. /**
  87946. * Reflection Texture level of blur.
  87947. *
  87948. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  87949. * texture twice.
  87950. */
  87951. _this.reflectionBlur = 0;
  87952. /**
  87953. * Diffuse Texture used in the material.
  87954. * Should be author in a specific way for the best result (refer to the documentation).
  87955. */
  87956. _this.diffuseTexture = null;
  87957. _this._shadowLights = null;
  87958. /**
  87959. * Specify the list of lights casting shadow on the material.
  87960. * All scene shadow lights will be included if null.
  87961. */
  87962. _this.shadowLights = null;
  87963. /**
  87964. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  87965. * soft lighting on the background.
  87966. */
  87967. _this.shadowBlurScale = 1;
  87968. /**
  87969. * Helps adjusting the shadow to a softer level if required.
  87970. * 0 means black shadows and 1 means no shadows.
  87971. */
  87972. _this.shadowLevel = 0;
  87973. /**
  87974. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  87975. * It is usually zero but might be interesting to modify according to your setup.
  87976. */
  87977. _this.sceneCenter = BABYLON.Vector3.Zero();
  87978. /**
  87979. * This helps specifying that the material is falling off to the sky box at grazing angle.
  87980. * This helps ensuring a nice transition when the camera goes under the ground.
  87981. */
  87982. _this.opacityFresnel = true;
  87983. /**
  87984. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  87985. * This helps adding a mirror texture on the ground.
  87986. */
  87987. _this.reflectionFresnel = false;
  87988. /**
  87989. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  87990. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  87991. */
  87992. _this.reflectionFalloffDistance = 0.0;
  87993. /**
  87994. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  87995. */
  87996. _this.reflectionAmount = 1.0;
  87997. /**
  87998. * This specifies the weight of the reflection at grazing angle.
  87999. */
  88000. _this.reflectionReflectance0 = 0.05;
  88001. /**
  88002. * This specifies the weight of the reflection at a perpendicular point of view.
  88003. */
  88004. _this.reflectionReflectance90 = 0.5;
  88005. /**
  88006. * Helps to directly use the maps channels instead of their level.
  88007. */
  88008. _this.useRGBColor = true;
  88009. /**
  88010. * This helps reducing the banding effect that could occur on the background.
  88011. */
  88012. _this.enableNoise = false;
  88013. _this._fovMultiplier = 1.0;
  88014. /**
  88015. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88016. * @type {boolean}
  88017. */
  88018. _this.useEquirectangularFOV = false;
  88019. _this._maxSimultaneousLights = 4;
  88020. /**
  88021. * Number of Simultaneous lights allowed on the material.
  88022. */
  88023. _this.maxSimultaneousLights = 4;
  88024. /**
  88025. * Keep track of the image processing observer to allow dispose and replace.
  88026. */
  88027. _this._imageProcessingObserver = null;
  88028. /**
  88029. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  88030. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  88031. */
  88032. _this.switchToBGR = false;
  88033. // Temp values kept as cache in the material.
  88034. _this._renderTargets = new BABYLON.SmartArray(16);
  88035. _this._reflectionControls = BABYLON.Vector4.Zero();
  88036. // Setup the default processing configuration to the scene.
  88037. _this._attachImageProcessingConfiguration(null);
  88038. _this.getRenderTargetTextures = function () {
  88039. _this._renderTargets.reset();
  88040. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88041. _this._renderTargets.push(_this._diffuseTexture);
  88042. }
  88043. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88044. _this._renderTargets.push(_this._reflectionTexture);
  88045. }
  88046. return _this._renderTargets;
  88047. };
  88048. return _this;
  88049. }
  88050. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88051. /**
  88052. * Sets the reflection reflectance fresnel values according to the default standard
  88053. * empirically know to work well :-)
  88054. */
  88055. set: function (value) {
  88056. var reflectionWeight = value;
  88057. if (reflectionWeight < 0.5) {
  88058. reflectionWeight = reflectionWeight * 2.0;
  88059. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88060. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88061. }
  88062. else {
  88063. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88064. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88065. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88066. }
  88067. },
  88068. enumerable: true,
  88069. configurable: true
  88070. });
  88071. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88072. /**
  88073. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88074. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88075. * Recommended to be keep at 1.0 except for special cases.
  88076. */
  88077. get: function () {
  88078. return this._fovMultiplier;
  88079. },
  88080. set: function (value) {
  88081. if (isNaN(value)) {
  88082. value = 1.0;
  88083. }
  88084. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88085. },
  88086. enumerable: true,
  88087. configurable: true
  88088. });
  88089. /**
  88090. * Attaches a new image processing configuration to the PBR Material.
  88091. * @param configuration (if null the scene configuration will be use)
  88092. */
  88093. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88094. var _this = this;
  88095. if (configuration === this._imageProcessingConfiguration) {
  88096. return;
  88097. }
  88098. // Detaches observer.
  88099. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88100. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88101. }
  88102. // Pick the scene configuration if needed.
  88103. if (!configuration) {
  88104. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88105. }
  88106. else {
  88107. this._imageProcessingConfiguration = configuration;
  88108. }
  88109. // Attaches observer.
  88110. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88111. _this._markAllSubMeshesAsImageProcessingDirty();
  88112. });
  88113. };
  88114. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88115. /**
  88116. * Gets the image processing configuration used either in this material.
  88117. */
  88118. get: function () {
  88119. return this._imageProcessingConfiguration;
  88120. },
  88121. /**
  88122. * Sets the Default image processing configuration used either in the this material.
  88123. *
  88124. * If sets to null, the scene one is in use.
  88125. */
  88126. set: function (value) {
  88127. this._attachImageProcessingConfiguration(value);
  88128. // Ensure the effect will be rebuilt.
  88129. this._markAllSubMeshesAsTexturesDirty();
  88130. },
  88131. enumerable: true,
  88132. configurable: true
  88133. });
  88134. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88135. /**
  88136. * Gets wether the color curves effect is enabled.
  88137. */
  88138. get: function () {
  88139. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88140. },
  88141. /**
  88142. * Sets wether the color curves effect is enabled.
  88143. */
  88144. set: function (value) {
  88145. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88146. },
  88147. enumerable: true,
  88148. configurable: true
  88149. });
  88150. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88151. /**
  88152. * Gets wether the color grading effect is enabled.
  88153. */
  88154. get: function () {
  88155. return this.imageProcessingConfiguration.colorGradingEnabled;
  88156. },
  88157. /**
  88158. * Gets wether the color grading effect is enabled.
  88159. */
  88160. set: function (value) {
  88161. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88162. },
  88163. enumerable: true,
  88164. configurable: true
  88165. });
  88166. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88167. /**
  88168. * Gets wether tonemapping is enabled or not.
  88169. */
  88170. get: function () {
  88171. return this._imageProcessingConfiguration.toneMappingEnabled;
  88172. },
  88173. /**
  88174. * Sets wether tonemapping is enabled or not
  88175. */
  88176. set: function (value) {
  88177. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88178. },
  88179. enumerable: true,
  88180. configurable: true
  88181. });
  88182. ;
  88183. ;
  88184. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88185. /**
  88186. * The camera exposure used on this material.
  88187. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88188. * This corresponds to a photographic exposure.
  88189. */
  88190. get: function () {
  88191. return this._imageProcessingConfiguration.exposure;
  88192. },
  88193. /**
  88194. * The camera exposure used on this material.
  88195. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88196. * This corresponds to a photographic exposure.
  88197. */
  88198. set: function (value) {
  88199. this._imageProcessingConfiguration.exposure = value;
  88200. },
  88201. enumerable: true,
  88202. configurable: true
  88203. });
  88204. ;
  88205. ;
  88206. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88207. /**
  88208. * Gets The camera contrast used on this material.
  88209. */
  88210. get: function () {
  88211. return this._imageProcessingConfiguration.contrast;
  88212. },
  88213. /**
  88214. * Sets The camera contrast used on this material.
  88215. */
  88216. set: function (value) {
  88217. this._imageProcessingConfiguration.contrast = value;
  88218. },
  88219. enumerable: true,
  88220. configurable: true
  88221. });
  88222. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88223. /**
  88224. * Gets the Color Grading 2D Lookup Texture.
  88225. */
  88226. get: function () {
  88227. return this._imageProcessingConfiguration.colorGradingTexture;
  88228. },
  88229. /**
  88230. * Sets the Color Grading 2D Lookup Texture.
  88231. */
  88232. set: function (value) {
  88233. this.imageProcessingConfiguration.colorGradingTexture = value;
  88234. },
  88235. enumerable: true,
  88236. configurable: true
  88237. });
  88238. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88239. /**
  88240. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88241. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88242. * 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;
  88243. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88244. */
  88245. get: function () {
  88246. return this.imageProcessingConfiguration.colorCurves;
  88247. },
  88248. /**
  88249. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88250. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88251. * 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;
  88252. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88253. */
  88254. set: function (value) {
  88255. this.imageProcessingConfiguration.colorCurves = value;
  88256. },
  88257. enumerable: true,
  88258. configurable: true
  88259. });
  88260. /**
  88261. * The entire material has been created in order to prevent overdraw.
  88262. * @returns false
  88263. */
  88264. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88265. return true;
  88266. };
  88267. /**
  88268. * The entire material has been created in order to prevent overdraw.
  88269. * @returns true if blending is enable
  88270. */
  88271. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88272. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88273. };
  88274. /**
  88275. * Checks wether the material is ready to be rendered for a given mesh.
  88276. * @param mesh The mesh to render
  88277. * @param subMesh The submesh to check against
  88278. * @param useInstances Specify wether or not the material is used with instances
  88279. * @returns true if all the dependencies are ready (Textures, Effects...)
  88280. */
  88281. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88282. var _this = this;
  88283. if (useInstances === void 0) { useInstances = false; }
  88284. if (subMesh.effect && this.isFrozen) {
  88285. if (this._wasPreviouslyReady) {
  88286. return true;
  88287. }
  88288. }
  88289. if (!subMesh._materialDefines) {
  88290. subMesh._materialDefines = new BackgroundMaterialDefines();
  88291. }
  88292. var scene = this.getScene();
  88293. var defines = subMesh._materialDefines;
  88294. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88295. if (defines._renderId === scene.getRenderId()) {
  88296. return true;
  88297. }
  88298. }
  88299. var engine = scene.getEngine();
  88300. // Lights
  88301. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88302. defines._needNormals = true;
  88303. // Textures
  88304. if (defines._areTexturesDirty) {
  88305. defines._needUVs = false;
  88306. if (scene.texturesEnabled) {
  88307. if (scene.getEngine().getCaps().textureLOD) {
  88308. defines.TEXTURELODSUPPORT = true;
  88309. }
  88310. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88311. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88312. return false;
  88313. }
  88314. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88315. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88316. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88317. defines.OPACITYFRESNEL = this._opacityFresnel;
  88318. }
  88319. else {
  88320. defines.DIFFUSE = false;
  88321. defines.DIFFUSEHASALPHA = false;
  88322. defines.GAMMADIFFUSE = false;
  88323. defines.OPACITYFRESNEL = false;
  88324. }
  88325. var reflectionTexture = this._reflectionTexture;
  88326. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88327. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88328. return false;
  88329. }
  88330. defines.REFLECTION = true;
  88331. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88332. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88333. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88334. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88335. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88336. defines.REFLECTIONBGR = this.switchToBGR;
  88337. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88338. defines.INVERTCUBICMAP = true;
  88339. }
  88340. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88341. switch (reflectionTexture.coordinatesMode) {
  88342. case BABYLON.Texture.CUBIC_MODE:
  88343. case BABYLON.Texture.INVCUBIC_MODE:
  88344. defines.REFLECTIONMAP_CUBIC = true;
  88345. break;
  88346. case BABYLON.Texture.EXPLICIT_MODE:
  88347. defines.REFLECTIONMAP_EXPLICIT = true;
  88348. break;
  88349. case BABYLON.Texture.PLANAR_MODE:
  88350. defines.REFLECTIONMAP_PLANAR = true;
  88351. break;
  88352. case BABYLON.Texture.PROJECTION_MODE:
  88353. defines.REFLECTIONMAP_PROJECTION = true;
  88354. break;
  88355. case BABYLON.Texture.SKYBOX_MODE:
  88356. defines.REFLECTIONMAP_SKYBOX = true;
  88357. break;
  88358. case BABYLON.Texture.SPHERICAL_MODE:
  88359. defines.REFLECTIONMAP_SPHERICAL = true;
  88360. break;
  88361. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88362. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88363. break;
  88364. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88365. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88366. break;
  88367. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88368. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88369. break;
  88370. }
  88371. if (this.reflectionFresnel) {
  88372. defines.REFLECTIONFRESNEL = true;
  88373. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88374. this._reflectionControls.x = this.reflectionAmount;
  88375. this._reflectionControls.y = this.reflectionReflectance0;
  88376. this._reflectionControls.z = this.reflectionReflectance90;
  88377. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88378. }
  88379. else {
  88380. defines.REFLECTIONFRESNEL = false;
  88381. defines.REFLECTIONFALLOFF = false;
  88382. }
  88383. }
  88384. else {
  88385. defines.REFLECTION = false;
  88386. defines.REFLECTIONFALLOFF = false;
  88387. defines.REFLECTIONBLUR = false;
  88388. defines.REFLECTIONMAP_3D = false;
  88389. defines.REFLECTIONMAP_SPHERICAL = false;
  88390. defines.REFLECTIONMAP_PLANAR = false;
  88391. defines.REFLECTIONMAP_CUBIC = false;
  88392. defines.REFLECTIONMAP_PROJECTION = false;
  88393. defines.REFLECTIONMAP_SKYBOX = false;
  88394. defines.REFLECTIONMAP_EXPLICIT = false;
  88395. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88396. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88397. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88398. defines.INVERTCUBICMAP = false;
  88399. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88400. defines.LODINREFLECTIONALPHA = false;
  88401. defines.GAMMAREFLECTION = false;
  88402. }
  88403. }
  88404. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88405. defines.USERGBCOLOR = this._useRGBColor;
  88406. defines.NOISE = this._enableNoise;
  88407. }
  88408. if (defines._areImageProcessingDirty) {
  88409. if (!this._imageProcessingConfiguration.isReady()) {
  88410. return false;
  88411. }
  88412. this._imageProcessingConfiguration.prepareDefines(defines);
  88413. }
  88414. // Misc.
  88415. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88416. // Values that need to be evaluated on every frame
  88417. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88418. // Attribs
  88419. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88420. if (mesh) {
  88421. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88422. mesh.createNormals(true);
  88423. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88424. }
  88425. }
  88426. }
  88427. // Get correct effect
  88428. if (defines.isDirty) {
  88429. defines.markAsProcessed();
  88430. scene.resetCachedMaterial();
  88431. // Fallbacks
  88432. var fallbacks = new BABYLON.EffectFallbacks();
  88433. if (defines.FOG) {
  88434. fallbacks.addFallback(0, "FOG");
  88435. }
  88436. if (defines.POINTSIZE) {
  88437. fallbacks.addFallback(1, "POINTSIZE");
  88438. }
  88439. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88440. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88441. fallbacks.addCPUSkinningFallback(0, mesh);
  88442. }
  88443. //Attributes
  88444. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88445. if (defines.NORMAL) {
  88446. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88447. }
  88448. if (defines.UV1) {
  88449. attribs.push(BABYLON.VertexBuffer.UVKind);
  88450. }
  88451. if (defines.UV2) {
  88452. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88453. }
  88454. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88455. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88456. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88457. "vFogInfos", "vFogColor", "pointSize",
  88458. "vClipPlane", "mBones",
  88459. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88460. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88461. "shadowLevel", "alpha",
  88462. "vBackgroundCenter", "vReflectionControl",
  88463. "vDiffuseInfos", "diffuseMatrix",
  88464. ];
  88465. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88466. var uniformBuffers = ["Material", "Scene"];
  88467. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88468. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88469. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88470. uniformsNames: uniforms,
  88471. uniformBuffersNames: uniformBuffers,
  88472. samplers: samplers,
  88473. defines: defines,
  88474. maxSimultaneousLights: this._maxSimultaneousLights
  88475. });
  88476. var onCompiled = function (effect) {
  88477. if (_this.onCompiled) {
  88478. _this.onCompiled(effect);
  88479. }
  88480. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88481. };
  88482. var join = defines.toString();
  88483. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88484. attributes: attribs,
  88485. uniformsNames: uniforms,
  88486. uniformBuffersNames: uniformBuffers,
  88487. samplers: samplers,
  88488. defines: join,
  88489. fallbacks: fallbacks,
  88490. onCompiled: onCompiled,
  88491. onError: this.onError,
  88492. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88493. }, engine), defines);
  88494. this.buildUniformLayout();
  88495. }
  88496. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88497. return false;
  88498. }
  88499. defines._renderId = scene.getRenderId();
  88500. this._wasPreviouslyReady = true;
  88501. return true;
  88502. };
  88503. /**
  88504. * Build the uniform buffer used in the material.
  88505. */
  88506. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88507. // Order is important !
  88508. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88509. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88510. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88511. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88512. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88513. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88514. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88515. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88516. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88517. this._uniformBuffer.addUniform("pointSize", 1);
  88518. this._uniformBuffer.addUniform("shadowLevel", 1);
  88519. this._uniformBuffer.addUniform("alpha", 1);
  88520. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88521. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88522. this._uniformBuffer.create();
  88523. };
  88524. /**
  88525. * Unbind the material.
  88526. */
  88527. BackgroundMaterial.prototype.unbind = function () {
  88528. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88529. this._uniformBuffer.setTexture("diffuseSampler", null);
  88530. }
  88531. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88532. this._uniformBuffer.setTexture("reflectionSampler", null);
  88533. }
  88534. _super.prototype.unbind.call(this);
  88535. };
  88536. /**
  88537. * Bind only the world matrix to the material.
  88538. * @param world The world matrix to bind.
  88539. */
  88540. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88541. this._activeEffect.setMatrix("world", world);
  88542. };
  88543. /**
  88544. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88545. * @param world The world matrix to bind.
  88546. * @param subMesh The submesh to bind for.
  88547. */
  88548. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88549. var scene = this.getScene();
  88550. var defines = subMesh._materialDefines;
  88551. if (!defines) {
  88552. return;
  88553. }
  88554. var effect = subMesh.effect;
  88555. if (!effect) {
  88556. return;
  88557. }
  88558. this._activeEffect = effect;
  88559. // Matrices
  88560. this.bindOnlyWorldMatrix(world);
  88561. // Bones
  88562. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88563. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88564. if (mustRebind) {
  88565. this._uniformBuffer.bindToEffect(effect, "Material");
  88566. this.bindViewProjection(effect);
  88567. var reflectionTexture = this._reflectionTexture;
  88568. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88569. // Texture uniforms
  88570. if (scene.texturesEnabled) {
  88571. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88572. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88573. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88574. }
  88575. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88576. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88577. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88578. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88579. }
  88580. }
  88581. if (this.shadowLevel > 0) {
  88582. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88583. }
  88584. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88585. // Point size
  88586. if (this.pointsCloud) {
  88587. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88588. }
  88589. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88590. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88591. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88592. }
  88593. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88594. // Textures
  88595. if (scene.texturesEnabled) {
  88596. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88597. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88598. }
  88599. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88600. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88601. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88602. }
  88603. else if (!defines.REFLECTIONBLUR) {
  88604. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88605. }
  88606. else {
  88607. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88608. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88609. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88610. }
  88611. if (defines.REFLECTIONFRESNEL) {
  88612. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88613. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88614. }
  88615. }
  88616. }
  88617. // Clip plane
  88618. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88619. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88620. }
  88621. if (mustRebind || !this.isFrozen) {
  88622. if (scene.lightsEnabled) {
  88623. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88624. }
  88625. // View
  88626. this.bindView(effect);
  88627. // Fog
  88628. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88629. // image processing
  88630. this._imageProcessingConfiguration.bind(this._activeEffect);
  88631. }
  88632. this._uniformBuffer.update();
  88633. this._afterBind(mesh);
  88634. };
  88635. /**
  88636. * Dispose the material.
  88637. * @param forceDisposeEffect Force disposal of the associated effect.
  88638. * @param forceDisposeTextures Force disposal of the associated textures.
  88639. */
  88640. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88641. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88642. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88643. if (forceDisposeTextures) {
  88644. if (this.diffuseTexture) {
  88645. this.diffuseTexture.dispose();
  88646. }
  88647. if (this.reflectionTexture) {
  88648. this.reflectionTexture.dispose();
  88649. }
  88650. }
  88651. this._renderTargets.dispose();
  88652. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88653. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88654. }
  88655. _super.prototype.dispose.call(this, forceDisposeEffect);
  88656. };
  88657. /**
  88658. * Clones the material.
  88659. * @param name The cloned name.
  88660. * @returns The cloned material.
  88661. */
  88662. BackgroundMaterial.prototype.clone = function (name) {
  88663. var _this = this;
  88664. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88665. };
  88666. /**
  88667. * Serializes the current material to its JSON representation.
  88668. * @returns The JSON representation.
  88669. */
  88670. BackgroundMaterial.prototype.serialize = function () {
  88671. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88672. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88673. return serializationObject;
  88674. };
  88675. /**
  88676. * Gets the class name of the material
  88677. * @returns "BackgroundMaterial"
  88678. */
  88679. BackgroundMaterial.prototype.getClassName = function () {
  88680. return "BackgroundMaterial";
  88681. };
  88682. /**
  88683. * Parse a JSON input to create back a background material.
  88684. * @param source The JSON data to parse
  88685. * @param scene The scene to create the parsed material in
  88686. * @param rootUrl The root url of the assets the material depends upon
  88687. * @returns the instantiated BackgroundMaterial.
  88688. */
  88689. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88690. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88691. };
  88692. /**
  88693. * Standard reflectance value at parallel view angle.
  88694. */
  88695. BackgroundMaterial.StandardReflectance0 = 0.05;
  88696. /**
  88697. * Standard reflectance value at grazing angle.
  88698. */
  88699. BackgroundMaterial.StandardReflectance90 = 0.5;
  88700. __decorate([
  88701. BABYLON.serializeAsColor3()
  88702. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88703. __decorate([
  88704. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88705. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88706. __decorate([
  88707. BABYLON.serialize()
  88708. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88709. __decorate([
  88710. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88711. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88712. __decorate([
  88713. BABYLON.serializeAsColor3()
  88714. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88715. __decorate([
  88716. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88717. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88718. __decorate([
  88719. BABYLON.serialize()
  88720. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88721. __decorate([
  88722. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88723. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88724. __decorate([
  88725. BABYLON.serializeAsColor3()
  88726. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88727. __decorate([
  88728. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88729. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88730. __decorate([
  88731. BABYLON.serialize()
  88732. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88733. __decorate([
  88734. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88735. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88736. __decorate([
  88737. BABYLON.serializeAsTexture()
  88738. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88739. __decorate([
  88740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88741. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88742. __decorate([
  88743. BABYLON.serialize()
  88744. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88745. __decorate([
  88746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88747. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88748. __decorate([
  88749. BABYLON.serializeAsTexture()
  88750. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88751. __decorate([
  88752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88753. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88754. __decorate([
  88755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88756. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88757. __decorate([
  88758. BABYLON.serialize()
  88759. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88760. __decorate([
  88761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88762. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88763. __decorate([
  88764. BABYLON.serialize()
  88765. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88766. __decorate([
  88767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88768. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88769. __decorate([
  88770. BABYLON.serializeAsVector3()
  88771. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88772. __decorate([
  88773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88774. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88775. __decorate([
  88776. BABYLON.serialize()
  88777. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  88778. __decorate([
  88779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88780. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  88781. __decorate([
  88782. BABYLON.serialize()
  88783. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  88784. __decorate([
  88785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88786. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  88787. __decorate([
  88788. BABYLON.serialize()
  88789. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  88790. __decorate([
  88791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88792. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  88793. __decorate([
  88794. BABYLON.serialize()
  88795. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  88796. __decorate([
  88797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88798. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  88799. __decorate([
  88800. BABYLON.serialize()
  88801. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  88802. __decorate([
  88803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88804. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  88805. __decorate([
  88806. BABYLON.serialize()
  88807. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  88808. __decorate([
  88809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88810. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  88811. __decorate([
  88812. BABYLON.serialize()
  88813. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  88814. __decorate([
  88815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88816. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  88817. __decorate([
  88818. BABYLON.serialize()
  88819. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  88820. __decorate([
  88821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88822. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  88823. __decorate([
  88824. BABYLON.serialize()
  88825. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  88826. __decorate([
  88827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88828. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  88829. __decorate([
  88830. BABYLON.serializeAsImageProcessingConfiguration()
  88831. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  88832. return BackgroundMaterial;
  88833. }(BABYLON.PushMaterial));
  88834. BABYLON.BackgroundMaterial = BackgroundMaterial;
  88835. })(BABYLON || (BABYLON = {}));
  88836. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  88837. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88838. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88839. s = arguments[i];
  88840. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88841. t[p] = s[p];
  88842. }
  88843. return t;
  88844. };
  88845. var BABYLON;
  88846. (function (BABYLON) {
  88847. /**
  88848. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  88849. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  88850. * It also helps with the default setup of your imageProcessing configuration.
  88851. */
  88852. var EnvironmentHelper = /** @class */ (function () {
  88853. /**
  88854. * constructor
  88855. * @param options
  88856. * @param scene The scene to add the material to
  88857. */
  88858. function EnvironmentHelper(options, scene) {
  88859. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  88860. this._scene = scene;
  88861. this._setupBackground();
  88862. this._setupImageProcessing();
  88863. }
  88864. /**
  88865. * Creates the default options for the helper.
  88866. */
  88867. EnvironmentHelper._getDefaultOptions = function () {
  88868. return {
  88869. createGround: true,
  88870. groundSize: 15,
  88871. groundTexture: this._groundTextureCDNUrl,
  88872. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88873. groundOpacity: 0.9,
  88874. enableGroundShadow: true,
  88875. groundShadowLevel: 0.5,
  88876. enableGroundMirror: false,
  88877. groundMirrorSizeRatio: 0.3,
  88878. groundMirrorBlurKernel: 64,
  88879. groundMirrorAmount: 1,
  88880. groundMirrorFresnelWeight: 1,
  88881. groundMirrorFallOffDistance: 0,
  88882. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  88883. groundYBias: 0.00001,
  88884. createSkybox: true,
  88885. skyboxSize: 20,
  88886. skyboxTexture: this._skyboxTextureCDNUrl,
  88887. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88888. backgroundYRotation: 0,
  88889. sizeAuto: true,
  88890. rootPosition: BABYLON.Vector3.Zero(),
  88891. setupImageProcessing: true,
  88892. environmentTexture: this._environmentTextureCDNUrl,
  88893. cameraExposure: 0.8,
  88894. cameraContrast: 1.2,
  88895. toneMappingEnabled: true,
  88896. };
  88897. };
  88898. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  88899. /**
  88900. * Gets the root mesh created by the helper.
  88901. */
  88902. get: function () {
  88903. return this._rootMesh;
  88904. },
  88905. enumerable: true,
  88906. configurable: true
  88907. });
  88908. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  88909. /**
  88910. * Gets the skybox created by the helper.
  88911. */
  88912. get: function () {
  88913. return this._skybox;
  88914. },
  88915. enumerable: true,
  88916. configurable: true
  88917. });
  88918. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  88919. /**
  88920. * Gets the skybox texture created by the helper.
  88921. */
  88922. get: function () {
  88923. return this._skyboxTexture;
  88924. },
  88925. enumerable: true,
  88926. configurable: true
  88927. });
  88928. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  88929. /**
  88930. * Gets the skybox material created by the helper.
  88931. */
  88932. get: function () {
  88933. return this._skyboxMaterial;
  88934. },
  88935. enumerable: true,
  88936. configurable: true
  88937. });
  88938. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  88939. /**
  88940. * Gets the ground mesh created by the helper.
  88941. */
  88942. get: function () {
  88943. return this._ground;
  88944. },
  88945. enumerable: true,
  88946. configurable: true
  88947. });
  88948. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  88949. /**
  88950. * Gets the ground texture created by the helper.
  88951. */
  88952. get: function () {
  88953. return this._groundTexture;
  88954. },
  88955. enumerable: true,
  88956. configurable: true
  88957. });
  88958. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  88959. /**
  88960. * Gets the ground mirror created by the helper.
  88961. */
  88962. get: function () {
  88963. return this._groundMirror;
  88964. },
  88965. enumerable: true,
  88966. configurable: true
  88967. });
  88968. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  88969. /**
  88970. * Gets the ground mirror render list to helps pushing the meshes
  88971. * you wish in the ground reflection.
  88972. */
  88973. get: function () {
  88974. if (this._groundMirror) {
  88975. return this._groundMirror.renderList;
  88976. }
  88977. return null;
  88978. },
  88979. enumerable: true,
  88980. configurable: true
  88981. });
  88982. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  88983. /**
  88984. * Gets the ground material created by the helper.
  88985. */
  88986. get: function () {
  88987. return this._groundMaterial;
  88988. },
  88989. enumerable: true,
  88990. configurable: true
  88991. });
  88992. /**
  88993. * Updates the background according to the new options
  88994. * @param options
  88995. */
  88996. EnvironmentHelper.prototype.updateOptions = function (options) {
  88997. var newOptions = __assign({}, this._options, options);
  88998. if (this._ground && !newOptions.createGround) {
  88999. this._ground.dispose();
  89000. this._ground = null;
  89001. }
  89002. if (this._groundMaterial && !newOptions.createGround) {
  89003. this._groundMaterial.dispose();
  89004. this._groundMaterial = null;
  89005. }
  89006. if (this._groundTexture) {
  89007. if (this._options.groundTexture != newOptions.groundTexture) {
  89008. this._groundTexture.dispose();
  89009. this._groundTexture = null;
  89010. }
  89011. }
  89012. if (this._skybox && !newOptions.createSkybox) {
  89013. this._skybox.dispose();
  89014. this._skybox = null;
  89015. }
  89016. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89017. this._skyboxMaterial.dispose();
  89018. this._skyboxMaterial = null;
  89019. }
  89020. if (this._skyboxTexture) {
  89021. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89022. this._skyboxTexture.dispose();
  89023. this._skyboxTexture = null;
  89024. }
  89025. }
  89026. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89027. this._groundMirror.dispose();
  89028. this._groundMirror = null;
  89029. }
  89030. if (this._scene.environmentTexture) {
  89031. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89032. this._scene.environmentTexture.dispose();
  89033. }
  89034. }
  89035. this._options = newOptions;
  89036. this._setupBackground();
  89037. this._setupImageProcessing();
  89038. };
  89039. /**
  89040. * Sets the primary color of all the available elements.
  89041. * @param color
  89042. */
  89043. EnvironmentHelper.prototype.setMainColor = function (color) {
  89044. if (this.groundMaterial) {
  89045. this.groundMaterial.primaryColor = color;
  89046. }
  89047. if (this.skyboxMaterial) {
  89048. this.skyboxMaterial.primaryColor = color;
  89049. }
  89050. if (this.groundMirror) {
  89051. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89052. }
  89053. };
  89054. /**
  89055. * Setup the image processing according to the specified options.
  89056. */
  89057. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89058. if (this._options.setupImageProcessing) {
  89059. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89060. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89061. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89062. this._setupEnvironmentTexture();
  89063. }
  89064. };
  89065. /**
  89066. * Setup the environment texture according to the specified options.
  89067. */
  89068. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89069. if (this._scene.environmentTexture) {
  89070. return;
  89071. }
  89072. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89073. this._scene.environmentTexture = this._options.environmentTexture;
  89074. return;
  89075. }
  89076. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89077. this._scene.environmentTexture = environmentTexture;
  89078. };
  89079. /**
  89080. * Setup the background according to the specified options.
  89081. */
  89082. EnvironmentHelper.prototype._setupBackground = function () {
  89083. if (!this._rootMesh) {
  89084. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89085. }
  89086. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89087. var sceneSize = this._getSceneSize();
  89088. if (this._options.createGround) {
  89089. this._setupGround(sceneSize);
  89090. this._setupGroundMaterial();
  89091. this._setupGroundDiffuseTexture();
  89092. if (this._options.enableGroundMirror) {
  89093. this._setupGroundMirrorTexture(sceneSize);
  89094. }
  89095. this._setupMirrorInGroundMaterial();
  89096. }
  89097. if (this._options.createSkybox) {
  89098. this._setupSkybox(sceneSize);
  89099. this._setupSkyboxMaterial();
  89100. this._setupSkyboxReflectionTexture();
  89101. }
  89102. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89103. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89104. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89105. };
  89106. /**
  89107. * Get the scene sizes according to the setup.
  89108. */
  89109. EnvironmentHelper.prototype._getSceneSize = function () {
  89110. var _this = this;
  89111. var groundSize = this._options.groundSize;
  89112. var skyboxSize = this._options.skyboxSize;
  89113. var rootPosition = this._options.rootPosition;
  89114. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89115. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89116. }
  89117. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89118. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89119. });
  89120. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89121. if (this._options.sizeAuto) {
  89122. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89123. this._scene.activeCamera.upperRadiusLimit) {
  89124. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89125. skyboxSize = groundSize;
  89126. }
  89127. var sceneDiagonalLenght = sceneDiagonal.length();
  89128. if (sceneDiagonalLenght > groundSize) {
  89129. groundSize = sceneDiagonalLenght * 2;
  89130. skyboxSize = groundSize;
  89131. }
  89132. // 10 % bigger.
  89133. groundSize *= 1.1;
  89134. skyboxSize *= 1.5;
  89135. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89136. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89137. }
  89138. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89139. };
  89140. /**
  89141. * Setup the ground according to the specified options.
  89142. */
  89143. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89144. var _this = this;
  89145. if (!this._ground) {
  89146. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89147. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89148. this._ground.parent = this._rootMesh;
  89149. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89150. }
  89151. this._ground.receiveShadows = this._options.enableGroundShadow;
  89152. };
  89153. /**
  89154. * Setup the ground material according to the specified options.
  89155. */
  89156. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89157. if (!this._groundMaterial) {
  89158. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89159. }
  89160. this._groundMaterial.alpha = this._options.groundOpacity;
  89161. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89162. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89163. this._groundMaterial.primaryLevel = 1;
  89164. this._groundMaterial.primaryColor = this._options.groundColor;
  89165. this._groundMaterial.secondaryLevel = 0;
  89166. this._groundMaterial.tertiaryLevel = 0;
  89167. this._groundMaterial.useRGBColor = false;
  89168. this._groundMaterial.enableNoise = true;
  89169. if (this._ground) {
  89170. this._ground.material = this._groundMaterial;
  89171. }
  89172. };
  89173. /**
  89174. * Setup the ground diffuse texture according to the specified options.
  89175. */
  89176. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89177. if (!this._groundMaterial) {
  89178. return;
  89179. }
  89180. if (this._groundTexture) {
  89181. return;
  89182. }
  89183. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89184. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89185. return;
  89186. }
  89187. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  89188. diffuseTexture.gammaSpace = false;
  89189. diffuseTexture.hasAlpha = true;
  89190. this._groundMaterial.diffuseTexture = diffuseTexture;
  89191. };
  89192. /**
  89193. * Setup the ground mirror texture according to the specified options.
  89194. */
  89195. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89196. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89197. if (!this._groundMirror) {
  89198. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89199. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89200. this._groundMirror.anisotropicFilteringLevel = 1;
  89201. this._groundMirror.wrapU = wrapping;
  89202. this._groundMirror.wrapV = wrapping;
  89203. this._groundMirror.gammaSpace = false;
  89204. if (this._groundMirror.renderList) {
  89205. for (var i = 0; i < this._scene.meshes.length; i++) {
  89206. var mesh = this._scene.meshes[i];
  89207. if (mesh !== this._ground &&
  89208. mesh !== this._skybox &&
  89209. mesh !== this._rootMesh) {
  89210. this._groundMirror.renderList.push(mesh);
  89211. }
  89212. }
  89213. }
  89214. }
  89215. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89216. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89217. };
  89218. /**
  89219. * Setup the ground to receive the mirror texture.
  89220. */
  89221. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89222. if (this._groundMaterial) {
  89223. this._groundMaterial.reflectionTexture = this._groundMirror;
  89224. this._groundMaterial.reflectionFresnel = true;
  89225. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89226. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89227. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89228. }
  89229. };
  89230. /**
  89231. * Setup the skybox according to the specified options.
  89232. */
  89233. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89234. var _this = this;
  89235. if (!this._skybox) {
  89236. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89237. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89238. }
  89239. this._skybox.parent = this._rootMesh;
  89240. };
  89241. /**
  89242. * Setup the skybox material according to the specified options.
  89243. */
  89244. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89245. if (!this._skybox) {
  89246. return;
  89247. }
  89248. if (!this._skyboxMaterial) {
  89249. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89250. }
  89251. this._skyboxMaterial.useRGBColor = false;
  89252. this._skyboxMaterial.primaryLevel = 1;
  89253. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89254. this._skyboxMaterial.secondaryLevel = 0;
  89255. this._skyboxMaterial.tertiaryLevel = 0;
  89256. this._skyboxMaterial.enableNoise = true;
  89257. this._skybox.material = this._skyboxMaterial;
  89258. };
  89259. /**
  89260. * Setup the skybox reflection texture according to the specified options.
  89261. */
  89262. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89263. if (!this._skyboxMaterial) {
  89264. return;
  89265. }
  89266. if (this._skyboxTexture) {
  89267. return;
  89268. }
  89269. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89270. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89271. return;
  89272. }
  89273. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  89274. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89275. this._skyboxTexture.gammaSpace = false;
  89276. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89277. };
  89278. /**
  89279. * Dispose all the elements created by the Helper.
  89280. */
  89281. EnvironmentHelper.prototype.dispose = function () {
  89282. if (this._groundMaterial) {
  89283. this._groundMaterial.dispose(true, true);
  89284. }
  89285. if (this._skyboxMaterial) {
  89286. this._skyboxMaterial.dispose(true, true);
  89287. }
  89288. this._rootMesh.dispose(false);
  89289. };
  89290. /**
  89291. * Default ground texture URL.
  89292. */
  89293. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89294. /**
  89295. * Default skybox texture URL.
  89296. */
  89297. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89298. /**
  89299. * Default environment texture URL.
  89300. */
  89301. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89302. return EnvironmentHelper;
  89303. }());
  89304. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89305. })(BABYLON || (BABYLON = {}));
  89306. //# sourceMappingURL=babylon.environmentHelper.js.map
  89307. 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 screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\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\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#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  89308. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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","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};"};
  89309. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89310. var BABYLON;
  89311. (function (BABYLON) {
  89312. var GridMaterialDefines = /** @class */ (function (_super) {
  89313. __extends(GridMaterialDefines, _super);
  89314. function GridMaterialDefines() {
  89315. var _this = _super.call(this) || this;
  89316. _this.TRANSPARENT = false;
  89317. _this.FOG = false;
  89318. _this.PREMULTIPLYALPHA = false;
  89319. _this.rebuild();
  89320. return _this;
  89321. }
  89322. return GridMaterialDefines;
  89323. }(BABYLON.MaterialDefines));
  89324. /**
  89325. * The grid materials allows you to wrap any shape with a grid.
  89326. * Colors are customizable.
  89327. */
  89328. var GridMaterial = /** @class */ (function (_super) {
  89329. __extends(GridMaterial, _super);
  89330. /**
  89331. * constructor
  89332. * @param name The name given to the material in order to identify it afterwards.
  89333. * @param scene The scene the material is used in.
  89334. */
  89335. function GridMaterial(name, scene) {
  89336. var _this = _super.call(this, name, scene) || this;
  89337. /**
  89338. * Main color of the grid (e.g. between lines)
  89339. */
  89340. _this.mainColor = BABYLON.Color3.Black();
  89341. /**
  89342. * Color of the grid lines.
  89343. */
  89344. _this.lineColor = BABYLON.Color3.Teal();
  89345. /**
  89346. * The scale of the grid compared to unit.
  89347. */
  89348. _this.gridRatio = 1.0;
  89349. /**
  89350. * Allows setting an offset for the grid lines.
  89351. */
  89352. _this.gridOffset = BABYLON.Vector3.Zero();
  89353. /**
  89354. * The frequency of thicker lines.
  89355. */
  89356. _this.majorUnitFrequency = 10;
  89357. /**
  89358. * The visibility of minor units in the grid.
  89359. */
  89360. _this.minorUnitVisibility = 0.33;
  89361. /**
  89362. * The grid opacity outside of the lines.
  89363. */
  89364. _this.opacity = 1.0;
  89365. /**
  89366. * Determine RBG output is premultiplied by alpha value.
  89367. */
  89368. _this.preMultiplyAlpha = false;
  89369. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  89370. return _this;
  89371. }
  89372. /**
  89373. * Returns wehter or not the grid requires alpha blending.
  89374. */
  89375. GridMaterial.prototype.needAlphaBlending = function () {
  89376. return this.opacity < 1.0;
  89377. };
  89378. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  89379. return this.needAlphaBlending();
  89380. };
  89381. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  89382. if (this.isFrozen) {
  89383. if (this._wasPreviouslyReady && subMesh.effect) {
  89384. return true;
  89385. }
  89386. }
  89387. if (!subMesh._materialDefines) {
  89388. subMesh._materialDefines = new GridMaterialDefines();
  89389. }
  89390. var defines = subMesh._materialDefines;
  89391. var scene = this.getScene();
  89392. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  89393. if (this._renderId === scene.getRenderId()) {
  89394. return true;
  89395. }
  89396. }
  89397. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  89398. defines.TRANSPARENT = !defines.TRANSPARENT;
  89399. defines.markAsUnprocessed();
  89400. }
  89401. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  89402. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  89403. defines.markAsUnprocessed();
  89404. }
  89405. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  89406. // Get correct effect
  89407. if (defines.isDirty) {
  89408. defines.markAsProcessed();
  89409. scene.resetCachedMaterial();
  89410. // Attributes
  89411. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89412. // Defines
  89413. var join = defines.toString();
  89414. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  89415. }
  89416. if (!subMesh.effect || !subMesh.effect.isReady()) {
  89417. return false;
  89418. }
  89419. this._renderId = scene.getRenderId();
  89420. this._wasPreviouslyReady = true;
  89421. return true;
  89422. };
  89423. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  89424. var scene = this.getScene();
  89425. var defines = subMesh._materialDefines;
  89426. if (!defines) {
  89427. return;
  89428. }
  89429. var effect = subMesh.effect;
  89430. if (!effect) {
  89431. return;
  89432. }
  89433. this._activeEffect = effect;
  89434. // Matrices
  89435. this.bindOnlyWorldMatrix(world);
  89436. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  89437. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  89438. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  89439. // Uniforms
  89440. if (this._mustRebind(scene, effect)) {
  89441. this._activeEffect.setColor3("mainColor", this.mainColor);
  89442. this._activeEffect.setColor3("lineColor", this.lineColor);
  89443. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  89444. this._gridControl.x = this.gridRatio;
  89445. this._gridControl.y = Math.round(this.majorUnitFrequency);
  89446. this._gridControl.z = this.minorUnitVisibility;
  89447. this._gridControl.w = this.opacity;
  89448. this._activeEffect.setVector4("gridControl", this._gridControl);
  89449. }
  89450. // Fog
  89451. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  89452. this._afterBind(mesh, this._activeEffect);
  89453. };
  89454. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  89455. _super.prototype.dispose.call(this, forceDisposeEffect);
  89456. };
  89457. GridMaterial.prototype.clone = function (name) {
  89458. var _this = this;
  89459. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  89460. };
  89461. GridMaterial.prototype.serialize = function () {
  89462. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  89463. serializationObject.customType = "BABYLON.GridMaterial";
  89464. return serializationObject;
  89465. };
  89466. GridMaterial.prototype.getClassName = function () {
  89467. return "GridMaterial";
  89468. };
  89469. GridMaterial.Parse = function (source, scene, rootUrl) {
  89470. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  89471. };
  89472. __decorate([
  89473. BABYLON.serializeAsColor3()
  89474. ], GridMaterial.prototype, "mainColor", void 0);
  89475. __decorate([
  89476. BABYLON.serializeAsColor3()
  89477. ], GridMaterial.prototype, "lineColor", void 0);
  89478. __decorate([
  89479. BABYLON.serialize()
  89480. ], GridMaterial.prototype, "gridRatio", void 0);
  89481. __decorate([
  89482. BABYLON.serializeAsColor3()
  89483. ], GridMaterial.prototype, "gridOffset", void 0);
  89484. __decorate([
  89485. BABYLON.serialize()
  89486. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  89487. __decorate([
  89488. BABYLON.serialize()
  89489. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  89490. __decorate([
  89491. BABYLON.serialize()
  89492. ], GridMaterial.prototype, "opacity", void 0);
  89493. __decorate([
  89494. BABYLON.serialize()
  89495. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  89496. return GridMaterial;
  89497. }(BABYLON.PushMaterial));
  89498. BABYLON.GridMaterial = GridMaterial;
  89499. })(BABYLON || (BABYLON = {}));
  89500. //# sourceMappingURL=babylon.gridmaterial.js.map
  89501. 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}";
  89502. 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}";
  89503. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  89504. var BABYLON;
  89505. (function (BABYLON) {
  89506. var GLTFLoaderCoordinateSystemMode;
  89507. (function (GLTFLoaderCoordinateSystemMode) {
  89508. /**
  89509. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  89510. */
  89511. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  89512. /**
  89513. * Sets the useRightHandedSystem flag on the scene.
  89514. */
  89515. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  89516. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  89517. var GLTFLoaderAnimationStartMode;
  89518. (function (GLTFLoaderAnimationStartMode) {
  89519. /**
  89520. * No animation will start.
  89521. */
  89522. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  89523. /**
  89524. * The first animation will start.
  89525. */
  89526. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  89527. /**
  89528. * All animations will start.
  89529. */
  89530. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  89531. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  89532. var GLTFLoaderState;
  89533. (function (GLTFLoaderState) {
  89534. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  89535. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  89536. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  89537. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  89538. var GLTFFileLoader = /** @class */ (function () {
  89539. function GLTFFileLoader() {
  89540. // #region Common options
  89541. /**
  89542. * Raised when the asset has been parsed.
  89543. * The data.json property stores the glTF JSON.
  89544. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  89545. */
  89546. this.onParsedObservable = new BABYLON.Observable();
  89547. // #endregion
  89548. // #region V2 options
  89549. /**
  89550. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  89551. */
  89552. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  89553. /**
  89554. * The animation start mode (NONE, FIRST, ALL).
  89555. */
  89556. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  89557. /**
  89558. * Set to true to compile materials before raising the success callback.
  89559. */
  89560. this.compileMaterials = false;
  89561. /**
  89562. * Set to true to also compile materials with clip planes.
  89563. */
  89564. this.useClipPlane = false;
  89565. /**
  89566. * Set to true to compile shadow generators before raising the success callback.
  89567. */
  89568. this.compileShadowGenerators = false;
  89569. /**
  89570. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  89571. */
  89572. this.onMeshLoadedObservable = new BABYLON.Observable();
  89573. /**
  89574. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  89575. */
  89576. this.onTextureLoadedObservable = new BABYLON.Observable();
  89577. /**
  89578. * Raised when the loader creates a material after parsing the glTF properties of the material.
  89579. */
  89580. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89581. /**
  89582. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  89583. * For assets with LODs, raised when all of the LODs are complete.
  89584. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  89585. */
  89586. this.onCompleteObservable = new BABYLON.Observable();
  89587. /**
  89588. * Raised when the loader is disposed.
  89589. */
  89590. this.onDisposeObservable = new BABYLON.Observable();
  89591. /**
  89592. * Raised after a loader extension is created.
  89593. * Set additional options for a loader extension in this event.
  89594. */
  89595. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89596. // #endregion
  89597. this._loader = null;
  89598. this.name = "gltf";
  89599. this.extensions = {
  89600. ".gltf": { isBinary: false },
  89601. ".glb": { isBinary: true }
  89602. };
  89603. }
  89604. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  89605. set: function (callback) {
  89606. if (this._onParsedObserver) {
  89607. this.onParsedObservable.remove(this._onParsedObserver);
  89608. }
  89609. this._onParsedObserver = this.onParsedObservable.add(callback);
  89610. },
  89611. enumerable: true,
  89612. configurable: true
  89613. });
  89614. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  89615. set: function (callback) {
  89616. if (this._onMeshLoadedObserver) {
  89617. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  89618. }
  89619. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  89620. },
  89621. enumerable: true,
  89622. configurable: true
  89623. });
  89624. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  89625. set: function (callback) {
  89626. if (this._onTextureLoadedObserver) {
  89627. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  89628. }
  89629. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  89630. },
  89631. enumerable: true,
  89632. configurable: true
  89633. });
  89634. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  89635. set: function (callback) {
  89636. if (this._onMaterialLoadedObserver) {
  89637. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  89638. }
  89639. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  89640. },
  89641. enumerable: true,
  89642. configurable: true
  89643. });
  89644. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  89645. set: function (callback) {
  89646. if (this._onCompleteObserver) {
  89647. this.onCompleteObservable.remove(this._onCompleteObserver);
  89648. }
  89649. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  89650. },
  89651. enumerable: true,
  89652. configurable: true
  89653. });
  89654. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  89655. set: function (callback) {
  89656. if (this._onDisposeObserver) {
  89657. this.onDisposeObservable.remove(this._onDisposeObserver);
  89658. }
  89659. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89660. },
  89661. enumerable: true,
  89662. configurable: true
  89663. });
  89664. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  89665. set: function (callback) {
  89666. if (this._onExtensionLoadedObserver) {
  89667. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  89668. }
  89669. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  89670. },
  89671. enumerable: true,
  89672. configurable: true
  89673. });
  89674. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  89675. /**
  89676. * The loader state or null if not active.
  89677. */
  89678. get: function () {
  89679. return this._loader ? this._loader.state : null;
  89680. },
  89681. enumerable: true,
  89682. configurable: true
  89683. });
  89684. /**
  89685. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  89686. */
  89687. GLTFFileLoader.prototype.dispose = function () {
  89688. if (this._loader) {
  89689. this._loader.dispose();
  89690. this._loader = null;
  89691. }
  89692. this.onMeshLoadedObservable.clear();
  89693. this.onTextureLoadedObservable.clear();
  89694. this.onMaterialLoadedObservable.clear();
  89695. this.onDisposeObservable.notifyObservers(this);
  89696. this.onDisposeObservable.clear();
  89697. };
  89698. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89699. var _this = this;
  89700. return Promise.resolve().then(function () {
  89701. var loaderData = _this._parse(data);
  89702. _this._loader = _this._getLoader(loaderData);
  89703. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  89704. });
  89705. };
  89706. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89707. var _this = this;
  89708. return Promise.resolve().then(function () {
  89709. var loaderData = _this._parse(data);
  89710. _this._loader = _this._getLoader(loaderData);
  89711. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  89712. });
  89713. };
  89714. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  89715. var _this = this;
  89716. return Promise.resolve().then(function () {
  89717. var loaderData = _this._parse(data);
  89718. _this._loader = _this._getLoader(loaderData);
  89719. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  89720. var container = new BABYLON.AssetContainer(scene);
  89721. Array.prototype.push.apply(container.meshes, result.meshes);
  89722. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  89723. Array.prototype.push.apply(container.skeletons, result.skeletons);
  89724. container.removeAllFromScene();
  89725. return container;
  89726. });
  89727. });
  89728. };
  89729. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  89730. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  89731. };
  89732. GLTFFileLoader.prototype.createPlugin = function () {
  89733. return new GLTFFileLoader();
  89734. };
  89735. GLTFFileLoader.prototype._parse = function (data) {
  89736. var parsedData;
  89737. if (data instanceof ArrayBuffer) {
  89738. parsedData = GLTFFileLoader._parseBinary(data);
  89739. }
  89740. else {
  89741. parsedData = {
  89742. json: JSON.parse(data),
  89743. bin: null
  89744. };
  89745. }
  89746. this.onParsedObservable.notifyObservers(parsedData);
  89747. this.onParsedObservable.clear();
  89748. return parsedData;
  89749. };
  89750. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  89751. var _this = this;
  89752. var loaderVersion = { major: 2, minor: 0 };
  89753. var asset = loaderData.json.asset || {};
  89754. var version = GLTFFileLoader._parseVersion(asset.version);
  89755. if (!version) {
  89756. throw new Error("Invalid version: " + asset.version);
  89757. }
  89758. if (asset.minVersion !== undefined) {
  89759. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  89760. if (!minVersion) {
  89761. throw new Error("Invalid minimum version: " + asset.minVersion);
  89762. }
  89763. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  89764. throw new Error("Incompatible minimum version: " + asset.minVersion);
  89765. }
  89766. }
  89767. var createLoaders = {
  89768. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  89769. 2: GLTFFileLoader.CreateGLTFLoaderV2
  89770. };
  89771. var createLoader = createLoaders[version.major];
  89772. if (!createLoader) {
  89773. throw new Error("Unsupported version: " + asset.version);
  89774. }
  89775. var loader = createLoader();
  89776. loader.coordinateSystemMode = this.coordinateSystemMode;
  89777. loader.animationStartMode = this.animationStartMode;
  89778. loader.compileMaterials = this.compileMaterials;
  89779. loader.useClipPlane = this.useClipPlane;
  89780. loader.compileShadowGenerators = this.compileShadowGenerators;
  89781. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  89782. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  89783. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  89784. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  89785. loader.onCompleteObservable.add(function () {
  89786. _this.onMeshLoadedObservable.clear();
  89787. _this.onTextureLoadedObservable.clear();
  89788. _this.onMaterialLoadedObservable.clear();
  89789. _this.onCompleteObservable.notifyObservers(_this);
  89790. _this.onCompleteObservable.clear();
  89791. });
  89792. return loader;
  89793. };
  89794. GLTFFileLoader._parseBinary = function (data) {
  89795. var Binary = {
  89796. Magic: 0x46546C67
  89797. };
  89798. var binaryReader = new BinaryReader(data);
  89799. var magic = binaryReader.readUint32();
  89800. if (magic !== Binary.Magic) {
  89801. throw new Error("Unexpected magic: " + magic);
  89802. }
  89803. var version = binaryReader.readUint32();
  89804. switch (version) {
  89805. case 1: return GLTFFileLoader._parseV1(binaryReader);
  89806. case 2: return GLTFFileLoader._parseV2(binaryReader);
  89807. }
  89808. throw new Error("Unsupported version: " + version);
  89809. };
  89810. GLTFFileLoader._parseV1 = function (binaryReader) {
  89811. var ContentFormat = {
  89812. JSON: 0
  89813. };
  89814. var length = binaryReader.readUint32();
  89815. if (length != binaryReader.getLength()) {
  89816. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89817. }
  89818. var contentLength = binaryReader.readUint32();
  89819. var contentFormat = binaryReader.readUint32();
  89820. var content;
  89821. switch (contentFormat) {
  89822. case ContentFormat.JSON: {
  89823. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  89824. break;
  89825. }
  89826. default: {
  89827. throw new Error("Unexpected content format: " + contentFormat);
  89828. }
  89829. }
  89830. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  89831. var body = binaryReader.readUint8Array(bytesRemaining);
  89832. return {
  89833. json: content,
  89834. bin: body
  89835. };
  89836. };
  89837. GLTFFileLoader._parseV2 = function (binaryReader) {
  89838. var ChunkFormat = {
  89839. JSON: 0x4E4F534A,
  89840. BIN: 0x004E4942
  89841. };
  89842. var length = binaryReader.readUint32();
  89843. if (length !== binaryReader.getLength()) {
  89844. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  89845. }
  89846. // JSON chunk
  89847. var chunkLength = binaryReader.readUint32();
  89848. var chunkFormat = binaryReader.readUint32();
  89849. if (chunkFormat !== ChunkFormat.JSON) {
  89850. throw new Error("First chunk format is not JSON");
  89851. }
  89852. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  89853. // Look for BIN chunk
  89854. var bin = null;
  89855. while (binaryReader.getPosition() < binaryReader.getLength()) {
  89856. var chunkLength_1 = binaryReader.readUint32();
  89857. var chunkFormat_1 = binaryReader.readUint32();
  89858. switch (chunkFormat_1) {
  89859. case ChunkFormat.JSON: {
  89860. throw new Error("Unexpected JSON chunk");
  89861. }
  89862. case ChunkFormat.BIN: {
  89863. bin = binaryReader.readUint8Array(chunkLength_1);
  89864. break;
  89865. }
  89866. default: {
  89867. // ignore unrecognized chunkFormat
  89868. binaryReader.skipBytes(chunkLength_1);
  89869. break;
  89870. }
  89871. }
  89872. }
  89873. return {
  89874. json: json,
  89875. bin: bin
  89876. };
  89877. };
  89878. GLTFFileLoader._parseVersion = function (version) {
  89879. if (version === "1.0" || version === "1.0.1") {
  89880. return {
  89881. major: 1,
  89882. minor: 0
  89883. };
  89884. }
  89885. var match = (version + "").match(/^(\d+)\.(\d+)/);
  89886. if (!match) {
  89887. return null;
  89888. }
  89889. return {
  89890. major: parseInt(match[1]),
  89891. minor: parseInt(match[2])
  89892. };
  89893. };
  89894. GLTFFileLoader._compareVersion = function (a, b) {
  89895. if (a.major > b.major)
  89896. return 1;
  89897. if (a.major < b.major)
  89898. return -1;
  89899. if (a.minor > b.minor)
  89900. return 1;
  89901. if (a.minor < b.minor)
  89902. return -1;
  89903. return 0;
  89904. };
  89905. GLTFFileLoader._decodeBufferToText = function (buffer) {
  89906. var result = "";
  89907. var length = buffer.byteLength;
  89908. for (var i = 0; i < length; i++) {
  89909. result += String.fromCharCode(buffer[i]);
  89910. }
  89911. return result;
  89912. };
  89913. // #endregion
  89914. // #region V1 options
  89915. GLTFFileLoader.IncrementalLoading = true;
  89916. GLTFFileLoader.HomogeneousCoordinates = false;
  89917. return GLTFFileLoader;
  89918. }());
  89919. BABYLON.GLTFFileLoader = GLTFFileLoader;
  89920. var BinaryReader = /** @class */ (function () {
  89921. function BinaryReader(arrayBuffer) {
  89922. this._arrayBuffer = arrayBuffer;
  89923. this._dataView = new DataView(arrayBuffer);
  89924. this._byteOffset = 0;
  89925. }
  89926. BinaryReader.prototype.getPosition = function () {
  89927. return this._byteOffset;
  89928. };
  89929. BinaryReader.prototype.getLength = function () {
  89930. return this._arrayBuffer.byteLength;
  89931. };
  89932. BinaryReader.prototype.readUint32 = function () {
  89933. var value = this._dataView.getUint32(this._byteOffset, true);
  89934. this._byteOffset += 4;
  89935. return value;
  89936. };
  89937. BinaryReader.prototype.readUint8Array = function (length) {
  89938. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  89939. this._byteOffset += length;
  89940. return value;
  89941. };
  89942. BinaryReader.prototype.skipBytes = function (length) {
  89943. this._byteOffset += length;
  89944. };
  89945. return BinaryReader;
  89946. }());
  89947. if (BABYLON.SceneLoader) {
  89948. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  89949. }
  89950. })(BABYLON || (BABYLON = {}));
  89951. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  89952. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89953. var BABYLON;
  89954. (function (BABYLON) {
  89955. var GLTF1;
  89956. (function (GLTF1) {
  89957. /**
  89958. * Enums
  89959. */
  89960. var EComponentType;
  89961. (function (EComponentType) {
  89962. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  89963. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89964. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  89965. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89966. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  89967. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  89968. var EShaderType;
  89969. (function (EShaderType) {
  89970. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  89971. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  89972. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  89973. var EParameterType;
  89974. (function (EParameterType) {
  89975. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  89976. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  89977. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  89978. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  89979. EParameterType[EParameterType["INT"] = 5124] = "INT";
  89980. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  89981. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  89982. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  89983. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  89984. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  89985. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  89986. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  89987. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  89988. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  89989. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  89990. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  89991. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  89992. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  89993. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  89994. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  89995. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  89996. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  89997. var ETextureWrapMode;
  89998. (function (ETextureWrapMode) {
  89999. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  90000. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  90001. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  90002. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  90003. var ETextureFilterType;
  90004. (function (ETextureFilterType) {
  90005. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  90006. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  90007. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  90008. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  90009. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  90010. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  90011. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  90012. var ETextureFormat;
  90013. (function (ETextureFormat) {
  90014. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  90015. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  90016. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  90017. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  90018. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  90019. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  90020. var ECullingType;
  90021. (function (ECullingType) {
  90022. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  90023. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  90024. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  90025. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  90026. var EBlendingFunction;
  90027. (function (EBlendingFunction) {
  90028. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  90029. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  90030. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  90031. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  90032. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  90033. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  90034. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  90035. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  90036. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  90037. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  90038. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  90039. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  90040. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  90041. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  90042. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90043. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  90044. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90045. })(BABYLON || (BABYLON = {}));
  90046. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90047. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90048. var BABYLON;
  90049. (function (BABYLON) {
  90050. var GLTF1;
  90051. (function (GLTF1) {
  90052. /**
  90053. * Tokenizer. Used for shaders compatibility
  90054. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  90055. */
  90056. var ETokenType;
  90057. (function (ETokenType) {
  90058. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  90059. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  90060. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  90061. })(ETokenType || (ETokenType = {}));
  90062. var Tokenizer = /** @class */ (function () {
  90063. function Tokenizer(toParse) {
  90064. this._pos = 0;
  90065. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  90066. this._toParse = toParse;
  90067. this._maxPos = toParse.length;
  90068. }
  90069. Tokenizer.prototype.getNextToken = function () {
  90070. if (this.isEnd())
  90071. return ETokenType.END_OF_INPUT;
  90072. this.currentString = this.read();
  90073. this.currentToken = ETokenType.UNKNOWN;
  90074. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  90075. this.currentToken = ETokenType.IDENTIFIER;
  90076. this.currentIdentifier = this.currentString;
  90077. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  90078. this.currentIdentifier += this.currentString;
  90079. this.forward();
  90080. }
  90081. }
  90082. return this.currentToken;
  90083. };
  90084. Tokenizer.prototype.peek = function () {
  90085. return this._toParse[this._pos];
  90086. };
  90087. Tokenizer.prototype.read = function () {
  90088. return this._toParse[this._pos++];
  90089. };
  90090. Tokenizer.prototype.forward = function () {
  90091. this._pos++;
  90092. };
  90093. Tokenizer.prototype.isEnd = function () {
  90094. return this._pos >= this._maxPos;
  90095. };
  90096. return Tokenizer;
  90097. }());
  90098. /**
  90099. * Values
  90100. */
  90101. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  90102. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  90103. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  90104. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  90105. /**
  90106. * Parse
  90107. */
  90108. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  90109. for (var buf in parsedBuffers) {
  90110. var parsedBuffer = parsedBuffers[buf];
  90111. gltfRuntime.buffers[buf] = parsedBuffer;
  90112. gltfRuntime.buffersCount++;
  90113. }
  90114. };
  90115. var parseShaders = function (parsedShaders, gltfRuntime) {
  90116. for (var sha in parsedShaders) {
  90117. var parsedShader = parsedShaders[sha];
  90118. gltfRuntime.shaders[sha] = parsedShader;
  90119. gltfRuntime.shaderscount++;
  90120. }
  90121. };
  90122. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  90123. for (var object in parsedObjects) {
  90124. var parsedObject = parsedObjects[object];
  90125. gltfRuntime[runtimeProperty][object] = parsedObject;
  90126. }
  90127. };
  90128. /**
  90129. * Utils
  90130. */
  90131. var normalizeUVs = function (buffer) {
  90132. if (!buffer) {
  90133. return;
  90134. }
  90135. for (var i = 0; i < buffer.length / 2; i++) {
  90136. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90137. }
  90138. };
  90139. var getAttribute = function (attributeParameter) {
  90140. if (attributeParameter.semantic === "NORMAL") {
  90141. return "normal";
  90142. }
  90143. else if (attributeParameter.semantic === "POSITION") {
  90144. return "position";
  90145. }
  90146. else if (attributeParameter.semantic === "JOINT") {
  90147. return "matricesIndices";
  90148. }
  90149. else if (attributeParameter.semantic === "WEIGHT") {
  90150. return "matricesWeights";
  90151. }
  90152. else if (attributeParameter.semantic === "COLOR") {
  90153. return "color";
  90154. }
  90155. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  90156. var channel = Number(attributeParameter.semantic.split("_")[1]);
  90157. return "uv" + (channel === 0 ? "" : channel + 1);
  90158. }
  90159. return null;
  90160. };
  90161. /**
  90162. * Loads and creates animations
  90163. */
  90164. var loadAnimations = function (gltfRuntime) {
  90165. for (var anim in gltfRuntime.animations) {
  90166. var animation = gltfRuntime.animations[anim];
  90167. if (!animation.channels || !animation.samplers) {
  90168. continue;
  90169. }
  90170. var lastAnimation = null;
  90171. for (var i = 0; i < animation.channels.length; i++) {
  90172. // Get parameters and load buffers
  90173. var channel = animation.channels[i];
  90174. var sampler = animation.samplers[channel.sampler];
  90175. if (!sampler) {
  90176. continue;
  90177. }
  90178. var inputData = null;
  90179. var outputData = null;
  90180. if (animation.parameters) {
  90181. inputData = animation.parameters[sampler.input];
  90182. outputData = animation.parameters[sampler.output];
  90183. }
  90184. else {
  90185. inputData = sampler.input;
  90186. outputData = sampler.output;
  90187. }
  90188. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  90189. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  90190. var targetID = channel.target.id;
  90191. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  90192. if (targetNode === null) {
  90193. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  90194. }
  90195. if (targetNode === null) {
  90196. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  90197. continue;
  90198. }
  90199. var isBone = targetNode instanceof BABYLON.Bone;
  90200. // Get target path (position, rotation or scaling)
  90201. var targetPath = channel.target.path;
  90202. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  90203. if (targetPathIndex !== -1) {
  90204. targetPath = babylonAnimationPaths[targetPathIndex];
  90205. }
  90206. // Determine animation type
  90207. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  90208. if (!isBone) {
  90209. if (targetPath === "rotationQuaternion") {
  90210. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  90211. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  90212. }
  90213. else {
  90214. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  90215. }
  90216. }
  90217. // Create animation and key frames
  90218. var babylonAnimation = null;
  90219. var keys = [];
  90220. var arrayOffset = 0;
  90221. var modifyKey = false;
  90222. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  90223. babylonAnimation = lastAnimation;
  90224. modifyKey = true;
  90225. }
  90226. if (!modifyKey) {
  90227. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90228. }
  90229. // For each frame
  90230. for (var j = 0; j < bufferInput.length; j++) {
  90231. var value = null;
  90232. if (targetPath === "rotationQuaternion") {
  90233. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  90234. arrayOffset += 4;
  90235. }
  90236. else {
  90237. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  90238. arrayOffset += 3;
  90239. }
  90240. if (isBone) {
  90241. var bone = targetNode;
  90242. var translation = BABYLON.Vector3.Zero();
  90243. var rotationQuaternion = new BABYLON.Quaternion();
  90244. var scaling = BABYLON.Vector3.Zero();
  90245. // Warning on decompose
  90246. var mat = bone.getBaseMatrix();
  90247. if (modifyKey && lastAnimation) {
  90248. mat = lastAnimation.getKeys()[j].value;
  90249. }
  90250. mat.decompose(scaling, rotationQuaternion, translation);
  90251. if (targetPath === "position") {
  90252. translation = value;
  90253. }
  90254. else if (targetPath === "rotationQuaternion") {
  90255. rotationQuaternion = value;
  90256. }
  90257. else {
  90258. scaling = value;
  90259. }
  90260. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  90261. }
  90262. if (!modifyKey) {
  90263. keys.push({
  90264. frame: bufferInput[j],
  90265. value: value
  90266. });
  90267. }
  90268. else if (lastAnimation) {
  90269. lastAnimation.getKeys()[j].value = value;
  90270. }
  90271. }
  90272. // Finish
  90273. if (!modifyKey && babylonAnimation) {
  90274. babylonAnimation.setKeys(keys);
  90275. targetNode.animations.push(babylonAnimation);
  90276. }
  90277. lastAnimation = babylonAnimation;
  90278. gltfRuntime.scene.stopAnimation(targetNode);
  90279. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  90280. }
  90281. }
  90282. };
  90283. /**
  90284. * Returns the bones transformation matrix
  90285. */
  90286. var configureBoneTransformation = function (node) {
  90287. var mat = null;
  90288. if (node.translation || node.rotation || node.scale) {
  90289. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  90290. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  90291. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  90292. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  90293. }
  90294. else {
  90295. mat = BABYLON.Matrix.FromArray(node.matrix);
  90296. }
  90297. return mat;
  90298. };
  90299. /**
  90300. * Returns the parent bone
  90301. */
  90302. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  90303. // Try to find
  90304. for (var i = 0; i < newSkeleton.bones.length; i++) {
  90305. if (newSkeleton.bones[i].name === jointName) {
  90306. return newSkeleton.bones[i];
  90307. }
  90308. }
  90309. // Not found, search in gltf nodes
  90310. var nodes = gltfRuntime.nodes;
  90311. for (var nde in nodes) {
  90312. var node = nodes[nde];
  90313. if (!node.jointName) {
  90314. continue;
  90315. }
  90316. var children = node.children;
  90317. for (var i = 0; i < children.length; i++) {
  90318. var child = gltfRuntime.nodes[children[i]];
  90319. if (!child.jointName) {
  90320. continue;
  90321. }
  90322. if (child.jointName === jointName) {
  90323. var mat = configureBoneTransformation(node);
  90324. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  90325. bone.id = nde;
  90326. return bone;
  90327. }
  90328. }
  90329. }
  90330. return null;
  90331. };
  90332. /**
  90333. * Returns the appropriate root node
  90334. */
  90335. var getNodeToRoot = function (nodesToRoot, id) {
  90336. for (var i = 0; i < nodesToRoot.length; i++) {
  90337. var nodeToRoot = nodesToRoot[i];
  90338. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  90339. var child = nodeToRoot.node.children[j];
  90340. if (child === id) {
  90341. return nodeToRoot.bone;
  90342. }
  90343. }
  90344. }
  90345. return null;
  90346. };
  90347. /**
  90348. * Returns the node with the joint name
  90349. */
  90350. var getJointNode = function (gltfRuntime, jointName) {
  90351. var nodes = gltfRuntime.nodes;
  90352. var node = nodes[jointName];
  90353. if (node) {
  90354. return {
  90355. node: node,
  90356. id: jointName
  90357. };
  90358. }
  90359. for (var nde in nodes) {
  90360. node = nodes[nde];
  90361. if (node.jointName === jointName) {
  90362. return {
  90363. node: node,
  90364. id: nde
  90365. };
  90366. }
  90367. }
  90368. return null;
  90369. };
  90370. /**
  90371. * Checks if a nodes is in joints
  90372. */
  90373. var nodeIsInJoints = function (skins, id) {
  90374. for (var i = 0; i < skins.jointNames.length; i++) {
  90375. if (skins.jointNames[i] === id) {
  90376. return true;
  90377. }
  90378. }
  90379. return false;
  90380. };
  90381. /**
  90382. * Fills the nodes to root for bones and builds hierarchy
  90383. */
  90384. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  90385. // Creates nodes for root
  90386. for (var nde in gltfRuntime.nodes) {
  90387. var node = gltfRuntime.nodes[nde];
  90388. var id = nde;
  90389. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  90390. continue;
  90391. }
  90392. // Create node to root bone
  90393. var mat = configureBoneTransformation(node);
  90394. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  90395. bone.id = id;
  90396. nodesToRoot.push({ bone: bone, node: node, id: id });
  90397. }
  90398. // Parenting
  90399. for (var i = 0; i < nodesToRoot.length; i++) {
  90400. var nodeToRoot = nodesToRoot[i];
  90401. var children = nodeToRoot.node.children;
  90402. for (var j = 0; j < children.length; j++) {
  90403. var child = null;
  90404. for (var k = 0; k < nodesToRoot.length; k++) {
  90405. if (nodesToRoot[k].id === children[j]) {
  90406. child = nodesToRoot[k];
  90407. break;
  90408. }
  90409. }
  90410. if (child) {
  90411. child.bone._parent = nodeToRoot.bone;
  90412. nodeToRoot.bone.children.push(child.bone);
  90413. }
  90414. }
  90415. }
  90416. };
  90417. /**
  90418. * Imports a skeleton
  90419. */
  90420. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  90421. if (!newSkeleton) {
  90422. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  90423. }
  90424. if (!skins.babylonSkeleton) {
  90425. return newSkeleton;
  90426. }
  90427. // Find the root bones
  90428. var nodesToRoot = [];
  90429. var nodesToRootToAdd = [];
  90430. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  90431. newSkeleton.bones = [];
  90432. // Joints
  90433. for (var i = 0; i < skins.jointNames.length; i++) {
  90434. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90435. if (!jointNode) {
  90436. continue;
  90437. }
  90438. var node = jointNode.node;
  90439. if (!node) {
  90440. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  90441. continue;
  90442. }
  90443. var id = jointNode.id;
  90444. // Optimize, if the bone already exists...
  90445. var existingBone = gltfRuntime.scene.getBoneByID(id);
  90446. if (existingBone) {
  90447. newSkeleton.bones.push(existingBone);
  90448. continue;
  90449. }
  90450. // Search for parent bone
  90451. var foundBone = false;
  90452. var parentBone = null;
  90453. for (var j = 0; j < i; j++) {
  90454. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  90455. if (!jointNode_1) {
  90456. continue;
  90457. }
  90458. var joint = jointNode_1.node;
  90459. if (!joint) {
  90460. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  90461. continue;
  90462. }
  90463. var children = joint.children;
  90464. if (!children) {
  90465. continue;
  90466. }
  90467. foundBone = false;
  90468. for (var k = 0; k < children.length; k++) {
  90469. if (children[k] === id) {
  90470. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  90471. foundBone = true;
  90472. break;
  90473. }
  90474. }
  90475. if (foundBone) {
  90476. break;
  90477. }
  90478. }
  90479. // Create bone
  90480. var mat = configureBoneTransformation(node);
  90481. if (!parentBone && nodesToRoot.length > 0) {
  90482. parentBone = getNodeToRoot(nodesToRoot, id);
  90483. if (parentBone) {
  90484. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  90485. nodesToRootToAdd.push(parentBone);
  90486. }
  90487. }
  90488. }
  90489. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  90490. bone.id = id;
  90491. }
  90492. // Polish
  90493. var bones = newSkeleton.bones;
  90494. newSkeleton.bones = [];
  90495. for (var i = 0; i < skins.jointNames.length; i++) {
  90496. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  90497. if (!jointNode) {
  90498. continue;
  90499. }
  90500. for (var j = 0; j < bones.length; j++) {
  90501. if (bones[j].id === jointNode.id) {
  90502. newSkeleton.bones.push(bones[j]);
  90503. break;
  90504. }
  90505. }
  90506. }
  90507. newSkeleton.prepare();
  90508. // Finish
  90509. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  90510. newSkeleton.bones.push(nodesToRootToAdd[i]);
  90511. }
  90512. return newSkeleton;
  90513. };
  90514. /**
  90515. * Imports a mesh and its geometries
  90516. */
  90517. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  90518. if (!newMesh) {
  90519. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90520. newMesh.id = id;
  90521. }
  90522. if (!node.babylonNode) {
  90523. return newMesh;
  90524. }
  90525. var subMaterials = [];
  90526. var vertexData = null;
  90527. var verticesStarts = new Array();
  90528. var verticesCounts = new Array();
  90529. var indexStarts = new Array();
  90530. var indexCounts = new Array();
  90531. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90532. var meshID = meshes[meshIndex];
  90533. var mesh = gltfRuntime.meshes[meshID];
  90534. if (!mesh) {
  90535. continue;
  90536. }
  90537. // Positions, normals and UVs
  90538. for (var i = 0; i < mesh.primitives.length; i++) {
  90539. // Temporary vertex data
  90540. var tempVertexData = new BABYLON.VertexData();
  90541. var primitive = mesh.primitives[i];
  90542. if (primitive.mode !== 4) {
  90543. // continue;
  90544. }
  90545. var attributes = primitive.attributes;
  90546. var accessor = null;
  90547. var buffer = null;
  90548. // Set positions, normal and uvs
  90549. for (var semantic in attributes) {
  90550. // Link accessor and buffer view
  90551. accessor = gltfRuntime.accessors[attributes[semantic]];
  90552. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90553. if (semantic === "NORMAL") {
  90554. tempVertexData.normals = new Float32Array(buffer.length);
  90555. tempVertexData.normals.set(buffer);
  90556. }
  90557. else if (semantic === "POSITION") {
  90558. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  90559. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  90560. for (var j = 0; j < buffer.length; j += 4) {
  90561. tempVertexData.positions[j] = buffer[j];
  90562. tempVertexData.positions[j + 1] = buffer[j + 1];
  90563. tempVertexData.positions[j + 2] = buffer[j + 2];
  90564. }
  90565. }
  90566. else {
  90567. tempVertexData.positions = new Float32Array(buffer.length);
  90568. tempVertexData.positions.set(buffer);
  90569. }
  90570. verticesCounts.push(tempVertexData.positions.length);
  90571. }
  90572. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  90573. var channel = Number(semantic.split("_")[1]);
  90574. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  90575. var uvs = new Float32Array(buffer.length);
  90576. uvs.set(buffer);
  90577. normalizeUVs(uvs);
  90578. tempVertexData.set(uvs, uvKind);
  90579. }
  90580. else if (semantic === "JOINT") {
  90581. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  90582. tempVertexData.matricesIndices.set(buffer);
  90583. }
  90584. else if (semantic === "WEIGHT") {
  90585. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  90586. tempVertexData.matricesWeights.set(buffer);
  90587. }
  90588. else if (semantic === "COLOR") {
  90589. tempVertexData.colors = new Float32Array(buffer.length);
  90590. tempVertexData.colors.set(buffer);
  90591. }
  90592. }
  90593. // Indices
  90594. accessor = gltfRuntime.accessors[primitive.indices];
  90595. if (accessor) {
  90596. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  90597. tempVertexData.indices = new Int32Array(buffer.length);
  90598. tempVertexData.indices.set(buffer);
  90599. indexCounts.push(tempVertexData.indices.length);
  90600. }
  90601. else {
  90602. // Set indices on the fly
  90603. var indices = [];
  90604. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  90605. indices.push(j);
  90606. }
  90607. tempVertexData.indices = new Int32Array(indices);
  90608. indexCounts.push(tempVertexData.indices.length);
  90609. }
  90610. if (!vertexData) {
  90611. vertexData = tempVertexData;
  90612. }
  90613. else {
  90614. vertexData.merge(tempVertexData);
  90615. }
  90616. // Sub material
  90617. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  90618. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  90619. // Update vertices start and index start
  90620. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  90621. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  90622. }
  90623. }
  90624. var material;
  90625. if (subMaterials.length > 1) {
  90626. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  90627. material.subMaterials = subMaterials;
  90628. }
  90629. else {
  90630. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  90631. }
  90632. if (subMaterials.length === 1) {
  90633. material = subMaterials[0];
  90634. }
  90635. if (!newMesh.material) {
  90636. newMesh.material = material;
  90637. }
  90638. // Apply geometry
  90639. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  90640. newMesh.computeWorldMatrix(true);
  90641. // Apply submeshes
  90642. newMesh.subMeshes = [];
  90643. var index = 0;
  90644. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  90645. var meshID = meshes[meshIndex];
  90646. var mesh = gltfRuntime.meshes[meshID];
  90647. if (!mesh) {
  90648. continue;
  90649. }
  90650. for (var i = 0; i < mesh.primitives.length; i++) {
  90651. if (mesh.primitives[i].mode !== 4) {
  90652. //continue;
  90653. }
  90654. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  90655. index++;
  90656. }
  90657. }
  90658. // Finish
  90659. return newMesh;
  90660. };
  90661. /**
  90662. * Configure node transformation from position, rotation and scaling
  90663. */
  90664. var configureNode = function (newNode, position, rotation, scaling) {
  90665. if (newNode.position) {
  90666. newNode.position = position;
  90667. }
  90668. if (newNode.rotationQuaternion || newNode.rotation) {
  90669. newNode.rotationQuaternion = rotation;
  90670. }
  90671. if (newNode.scaling) {
  90672. newNode.scaling = scaling;
  90673. }
  90674. };
  90675. /**
  90676. * Configures node from transformation matrix
  90677. */
  90678. var configureNodeFromMatrix = function (newNode, node, parent) {
  90679. if (node.matrix) {
  90680. var position = new BABYLON.Vector3(0, 0, 0);
  90681. var rotation = new BABYLON.Quaternion();
  90682. var scaling = new BABYLON.Vector3(0, 0, 0);
  90683. var mat = BABYLON.Matrix.FromArray(node.matrix);
  90684. mat.decompose(scaling, rotation, position);
  90685. configureNode(newNode, position, rotation, scaling);
  90686. }
  90687. else if (node.translation && node.rotation && node.scale) {
  90688. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  90689. }
  90690. newNode.computeWorldMatrix(true);
  90691. };
  90692. /**
  90693. * Imports a node
  90694. */
  90695. var importNode = function (gltfRuntime, node, id, parent) {
  90696. var lastNode = null;
  90697. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  90698. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  90699. return null;
  90700. }
  90701. }
  90702. // Meshes
  90703. if (node.skin) {
  90704. if (node.meshes) {
  90705. var skin = gltfRuntime.skins[node.skin];
  90706. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  90707. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  90708. if (newMesh.skeleton === null) {
  90709. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  90710. if (!skin.babylonSkeleton) {
  90711. skin.babylonSkeleton = newMesh.skeleton;
  90712. }
  90713. }
  90714. lastNode = newMesh;
  90715. }
  90716. }
  90717. else if (node.meshes) {
  90718. /**
  90719. * Improve meshes property
  90720. */
  90721. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  90722. lastNode = newMesh;
  90723. }
  90724. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90725. var light = gltfRuntime.lights[node.light];
  90726. if (light) {
  90727. if (light.type === "ambient") {
  90728. var ambienLight = light[light.type];
  90729. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90730. hemiLight.name = node.name || "";
  90731. if (ambienLight.color) {
  90732. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  90733. }
  90734. lastNode = hemiLight;
  90735. }
  90736. else if (light.type === "directional") {
  90737. var directionalLight = light[light.type];
  90738. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90739. dirLight.name = node.name || "";
  90740. if (directionalLight.color) {
  90741. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  90742. }
  90743. lastNode = dirLight;
  90744. }
  90745. else if (light.type === "point") {
  90746. var pointLight = light[light.type];
  90747. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90748. ptLight.name = node.name || "";
  90749. if (pointLight.color) {
  90750. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  90751. }
  90752. lastNode = ptLight;
  90753. }
  90754. else if (light.type === "spot") {
  90755. var spotLight = light[light.type];
  90756. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  90757. spLight.name = node.name || "";
  90758. if (spotLight.color) {
  90759. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  90760. }
  90761. if (spotLight.fallOfAngle) {
  90762. spLight.angle = spotLight.fallOfAngle;
  90763. }
  90764. if (spotLight.fallOffExponent) {
  90765. spLight.exponent = spotLight.fallOffExponent;
  90766. }
  90767. lastNode = spLight;
  90768. }
  90769. }
  90770. }
  90771. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  90772. var camera = gltfRuntime.cameras[node.camera];
  90773. if (camera) {
  90774. if (camera.type === "orthographic") {
  90775. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90776. orthoCamera.name = node.name || "";
  90777. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  90778. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90779. lastNode = orthoCamera;
  90780. }
  90781. else if (camera.type === "perspective") {
  90782. var perspectiveCamera = camera[camera.type];
  90783. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  90784. persCamera.name = node.name || "";
  90785. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  90786. if (!perspectiveCamera.aspectRatio) {
  90787. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  90788. }
  90789. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  90790. persCamera.maxZ = perspectiveCamera.zfar;
  90791. persCamera.minZ = perspectiveCamera.znear;
  90792. }
  90793. lastNode = persCamera;
  90794. }
  90795. }
  90796. }
  90797. // Empty node
  90798. if (!node.jointName) {
  90799. if (node.babylonNode) {
  90800. return node.babylonNode;
  90801. }
  90802. else if (lastNode === null) {
  90803. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  90804. node.babylonNode = dummy;
  90805. lastNode = dummy;
  90806. }
  90807. }
  90808. if (lastNode !== null) {
  90809. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  90810. configureNodeFromMatrix(lastNode, node, parent);
  90811. }
  90812. else {
  90813. var translation = node.translation || [0, 0, 0];
  90814. var rotation = node.rotation || [0, 0, 0, 1];
  90815. var scale = node.scale || [1, 1, 1];
  90816. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  90817. }
  90818. lastNode.updateCache(true);
  90819. node.babylonNode = lastNode;
  90820. }
  90821. return lastNode;
  90822. };
  90823. /**
  90824. * Traverses nodes and creates them
  90825. */
  90826. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  90827. if (meshIncluded === void 0) { meshIncluded = false; }
  90828. var node = gltfRuntime.nodes[id];
  90829. var newNode = null;
  90830. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  90831. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  90832. meshIncluded = true;
  90833. }
  90834. else {
  90835. meshIncluded = false;
  90836. }
  90837. }
  90838. else {
  90839. meshIncluded = true;
  90840. }
  90841. if (!node.jointName && meshIncluded) {
  90842. newNode = importNode(gltfRuntime, node, id, parent);
  90843. if (newNode !== null) {
  90844. newNode.id = id;
  90845. newNode.parent = parent;
  90846. }
  90847. }
  90848. if (node.children) {
  90849. for (var i = 0; i < node.children.length; i++) {
  90850. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  90851. }
  90852. }
  90853. };
  90854. /**
  90855. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  90856. */
  90857. var postLoad = function (gltfRuntime) {
  90858. // Nodes
  90859. var currentScene = gltfRuntime.currentScene;
  90860. if (currentScene) {
  90861. for (var i = 0; i < currentScene.nodes.length; i++) {
  90862. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90863. }
  90864. }
  90865. else {
  90866. for (var thing in gltfRuntime.scenes) {
  90867. currentScene = gltfRuntime.scenes[thing];
  90868. for (var i = 0; i < currentScene.nodes.length; i++) {
  90869. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90870. }
  90871. }
  90872. }
  90873. // Set animations
  90874. loadAnimations(gltfRuntime);
  90875. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  90876. var skeleton = gltfRuntime.scene.skeletons[i];
  90877. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  90878. }
  90879. };
  90880. /**
  90881. * onBind shaderrs callback to set uniforms and matrices
  90882. */
  90883. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  90884. var materialValues = material.values || technique.parameters;
  90885. for (var unif in unTreatedUniforms) {
  90886. var uniform = unTreatedUniforms[unif];
  90887. var type = uniform.type;
  90888. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  90889. if (uniform.semantic && !uniform.source && !uniform.node) {
  90890. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  90891. }
  90892. else if (uniform.semantic && (uniform.source || uniform.node)) {
  90893. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  90894. if (source === null) {
  90895. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  90896. }
  90897. if (source === null) {
  90898. continue;
  90899. }
  90900. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  90901. }
  90902. }
  90903. else {
  90904. var value = materialValues[technique.uniforms[unif]];
  90905. if (!value) {
  90906. continue;
  90907. }
  90908. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90909. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  90910. if (texture === null || texture === undefined) {
  90911. continue;
  90912. }
  90913. shaderMaterial.getEffect().setTexture(unif, texture);
  90914. }
  90915. else {
  90916. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  90917. }
  90918. }
  90919. }
  90920. onSuccess(shaderMaterial);
  90921. };
  90922. /**
  90923. * Prepare uniforms to send the only one time
  90924. * Loads the appropriate textures
  90925. */
  90926. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  90927. var materialValues = material.values || technique.parameters;
  90928. var techniqueUniforms = technique.uniforms;
  90929. /**
  90930. * Prepare values here (not matrices)
  90931. */
  90932. for (var unif in unTreatedUniforms) {
  90933. var uniform = unTreatedUniforms[unif];
  90934. var type = uniform.type;
  90935. var value = materialValues[techniqueUniforms[unif]];
  90936. if (value === undefined) {
  90937. // In case the value is the same for all materials
  90938. value = uniform.value;
  90939. }
  90940. if (!value) {
  90941. continue;
  90942. }
  90943. var onLoadTexture = function (uniformName) {
  90944. return function (texture) {
  90945. if (uniform.value && uniformName) {
  90946. // Static uniform
  90947. shaderMaterial.setTexture(uniformName, texture);
  90948. delete unTreatedUniforms[uniformName];
  90949. }
  90950. };
  90951. };
  90952. // Texture (sampler2D)
  90953. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  90954. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  90955. }
  90956. else {
  90957. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  90958. // Static uniform
  90959. delete unTreatedUniforms[unif];
  90960. }
  90961. }
  90962. }
  90963. };
  90964. /**
  90965. * Shader compilation failed
  90966. */
  90967. var onShaderCompileError = function (program, shaderMaterial, onError) {
  90968. return function (effect, error) {
  90969. shaderMaterial.dispose(true);
  90970. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  90971. };
  90972. };
  90973. /**
  90974. * Shader compilation success
  90975. */
  90976. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  90977. return function (_) {
  90978. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  90979. shaderMaterial.onBind = function (mesh) {
  90980. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  90981. };
  90982. };
  90983. };
  90984. /**
  90985. * Returns the appropriate uniform if already handled by babylon
  90986. */
  90987. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  90988. for (var unif in technique.uniforms) {
  90989. var uniform = technique.uniforms[unif];
  90990. var uniformParameter = technique.parameters[uniform];
  90991. if (tokenizer.currentIdentifier === unif) {
  90992. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  90993. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90994. if (transformIndex !== -1) {
  90995. delete unTreatedUniforms[unif];
  90996. return babylonTransforms[transformIndex];
  90997. }
  90998. }
  90999. }
  91000. }
  91001. return tokenizer.currentIdentifier;
  91002. };
  91003. /**
  91004. * All shaders loaded. Create materials one by one
  91005. */
  91006. var importMaterials = function (gltfRuntime) {
  91007. // Create materials
  91008. for (var mat in gltfRuntime.materials) {
  91009. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  91010. }
  91011. };
  91012. /**
  91013. * Implementation of the base glTF spec
  91014. */
  91015. var GLTFLoaderBase = /** @class */ (function () {
  91016. function GLTFLoaderBase() {
  91017. }
  91018. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  91019. var gltfRuntime = {
  91020. extensions: {},
  91021. accessors: {},
  91022. buffers: {},
  91023. bufferViews: {},
  91024. meshes: {},
  91025. lights: {},
  91026. cameras: {},
  91027. nodes: {},
  91028. images: {},
  91029. textures: {},
  91030. shaders: {},
  91031. programs: {},
  91032. samplers: {},
  91033. techniques: {},
  91034. materials: {},
  91035. animations: {},
  91036. skins: {},
  91037. extensionsUsed: [],
  91038. scenes: {},
  91039. buffersCount: 0,
  91040. shaderscount: 0,
  91041. scene: scene,
  91042. rootUrl: rootUrl,
  91043. loadedBufferCount: 0,
  91044. loadedBufferViews: {},
  91045. loadedShaderCount: 0,
  91046. importOnlyMeshes: false,
  91047. dummyNodes: []
  91048. };
  91049. // Parse
  91050. if (parsedData.extensions) {
  91051. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  91052. }
  91053. if (parsedData.extensionsUsed) {
  91054. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  91055. }
  91056. if (parsedData.buffers) {
  91057. parseBuffers(parsedData.buffers, gltfRuntime);
  91058. }
  91059. if (parsedData.bufferViews) {
  91060. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  91061. }
  91062. if (parsedData.accessors) {
  91063. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  91064. }
  91065. if (parsedData.meshes) {
  91066. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  91067. }
  91068. if (parsedData.lights) {
  91069. parseObject(parsedData.lights, "lights", gltfRuntime);
  91070. }
  91071. if (parsedData.cameras) {
  91072. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  91073. }
  91074. if (parsedData.nodes) {
  91075. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  91076. }
  91077. if (parsedData.images) {
  91078. parseObject(parsedData.images, "images", gltfRuntime);
  91079. }
  91080. if (parsedData.textures) {
  91081. parseObject(parsedData.textures, "textures", gltfRuntime);
  91082. }
  91083. if (parsedData.shaders) {
  91084. parseShaders(parsedData.shaders, gltfRuntime);
  91085. }
  91086. if (parsedData.programs) {
  91087. parseObject(parsedData.programs, "programs", gltfRuntime);
  91088. }
  91089. if (parsedData.samplers) {
  91090. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  91091. }
  91092. if (parsedData.techniques) {
  91093. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  91094. }
  91095. if (parsedData.materials) {
  91096. parseObject(parsedData.materials, "materials", gltfRuntime);
  91097. }
  91098. if (parsedData.animations) {
  91099. parseObject(parsedData.animations, "animations", gltfRuntime);
  91100. }
  91101. if (parsedData.skins) {
  91102. parseObject(parsedData.skins, "skins", gltfRuntime);
  91103. }
  91104. if (parsedData.scenes) {
  91105. gltfRuntime.scenes = parsedData.scenes;
  91106. }
  91107. if (parsedData.scene && parsedData.scenes) {
  91108. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  91109. }
  91110. return gltfRuntime;
  91111. };
  91112. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91113. var buffer = gltfRuntime.buffers[id];
  91114. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  91115. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  91116. }
  91117. else {
  91118. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  91119. if (request) {
  91120. onError(request.status + " " + request.statusText);
  91121. }
  91122. });
  91123. }
  91124. };
  91125. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91126. var texture = gltfRuntime.textures[id];
  91127. if (!texture || !texture.source) {
  91128. onError("");
  91129. return;
  91130. }
  91131. if (texture.babylonTexture) {
  91132. onSuccess(null);
  91133. return;
  91134. }
  91135. var source = gltfRuntime.images[texture.source];
  91136. if (BABYLON.Tools.IsBase64(source.uri)) {
  91137. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  91138. }
  91139. else {
  91140. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  91141. if (request) {
  91142. onError(request.status + " " + request.statusText);
  91143. }
  91144. });
  91145. }
  91146. };
  91147. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91148. var texture = gltfRuntime.textures[id];
  91149. if (texture.babylonTexture) {
  91150. onSuccess(texture.babylonTexture);
  91151. return;
  91152. }
  91153. var sampler = gltfRuntime.samplers[texture.sampler];
  91154. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  91155. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  91156. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  91157. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  91158. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91159. var blob = new Blob([buffer]);
  91160. var blobURL = URL.createObjectURL(blob);
  91161. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  91162. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  91163. if (sampler.wrapS !== undefined) {
  91164. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  91165. }
  91166. if (sampler.wrapT !== undefined) {
  91167. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  91168. }
  91169. newTexture.name = id;
  91170. texture.babylonTexture = newTexture;
  91171. onSuccess(newTexture);
  91172. };
  91173. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91174. var shader = gltfRuntime.shaders[id];
  91175. if (BABYLON.Tools.IsBase64(shader.uri)) {
  91176. var shaderString = atob(shader.uri.split(",")[1]);
  91177. onSuccess(shaderString);
  91178. }
  91179. else {
  91180. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  91181. if (request) {
  91182. onError(request.status + " " + request.statusText);
  91183. }
  91184. });
  91185. }
  91186. };
  91187. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91188. var material = gltfRuntime.materials[id];
  91189. if (!material.technique) {
  91190. if (onError) {
  91191. onError("No technique found.");
  91192. }
  91193. return;
  91194. }
  91195. var technique = gltfRuntime.techniques[material.technique];
  91196. if (!technique) {
  91197. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  91198. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  91199. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91200. onSuccess(defaultMaterial);
  91201. return;
  91202. }
  91203. var program = gltfRuntime.programs[technique.program];
  91204. var states = technique.states;
  91205. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  91206. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  91207. var newVertexShader = "";
  91208. var newPixelShader = "";
  91209. var vertexTokenizer = new Tokenizer(vertexShader);
  91210. var pixelTokenizer = new Tokenizer(pixelShader);
  91211. var unTreatedUniforms = {};
  91212. var uniforms = [];
  91213. var attributes = [];
  91214. var samplers = [];
  91215. // Fill uniform, sampler2D and attributes
  91216. for (var unif in technique.uniforms) {
  91217. var uniform = technique.uniforms[unif];
  91218. var uniformParameter = technique.parameters[uniform];
  91219. unTreatedUniforms[unif] = uniformParameter;
  91220. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  91221. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  91222. if (transformIndex !== -1) {
  91223. uniforms.push(babylonTransforms[transformIndex]);
  91224. delete unTreatedUniforms[unif];
  91225. }
  91226. else {
  91227. uniforms.push(unif);
  91228. }
  91229. }
  91230. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  91231. samplers.push(unif);
  91232. }
  91233. else {
  91234. uniforms.push(unif);
  91235. }
  91236. }
  91237. for (var attr in technique.attributes) {
  91238. var attribute = technique.attributes[attr];
  91239. var attributeParameter = technique.parameters[attribute];
  91240. if (attributeParameter.semantic) {
  91241. attributes.push(getAttribute(attributeParameter));
  91242. }
  91243. }
  91244. // Configure vertex shader
  91245. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  91246. var tokenType = vertexTokenizer.currentToken;
  91247. if (tokenType !== ETokenType.IDENTIFIER) {
  91248. newVertexShader += vertexTokenizer.currentString;
  91249. continue;
  91250. }
  91251. var foundAttribute = false;
  91252. for (var attr in technique.attributes) {
  91253. var attribute = technique.attributes[attr];
  91254. var attributeParameter = technique.parameters[attribute];
  91255. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  91256. newVertexShader += getAttribute(attributeParameter);
  91257. foundAttribute = true;
  91258. break;
  91259. }
  91260. }
  91261. if (foundAttribute) {
  91262. continue;
  91263. }
  91264. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  91265. }
  91266. // Configure pixel shader
  91267. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  91268. var tokenType = pixelTokenizer.currentToken;
  91269. if (tokenType !== ETokenType.IDENTIFIER) {
  91270. newPixelShader += pixelTokenizer.currentString;
  91271. continue;
  91272. }
  91273. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  91274. }
  91275. // Create shader material
  91276. var shaderPath = {
  91277. vertex: program.vertexShader + id,
  91278. fragment: program.fragmentShader + id
  91279. };
  91280. var options = {
  91281. attributes: attributes,
  91282. uniforms: uniforms,
  91283. samplers: samplers,
  91284. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  91285. };
  91286. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  91287. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  91288. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  91289. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  91290. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  91291. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  91292. if (states && states.functions) {
  91293. var functions = states.functions;
  91294. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  91295. shaderMaterial.backFaceCulling = false;
  91296. }
  91297. var blendFunc = functions.blendFuncSeparate;
  91298. if (blendFunc) {
  91299. 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) {
  91300. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  91301. }
  91302. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91303. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  91304. }
  91305. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91306. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  91307. }
  91308. 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) {
  91309. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  91310. }
  91311. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  91312. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  91313. }
  91314. 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) {
  91315. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  91316. }
  91317. }
  91318. }
  91319. };
  91320. return GLTFLoaderBase;
  91321. }());
  91322. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  91323. /**
  91324. * glTF V1 Loader
  91325. */
  91326. var GLTFLoader = /** @class */ (function () {
  91327. function GLTFLoader() {
  91328. // #region Stubs for IGLTFLoader interface
  91329. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  91330. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  91331. this.compileMaterials = false;
  91332. this.useClipPlane = false;
  91333. this.compileShadowGenerators = false;
  91334. this.onDisposeObservable = new BABYLON.Observable();
  91335. this.onMeshLoadedObservable = new BABYLON.Observable();
  91336. this.onTextureLoadedObservable = new BABYLON.Observable();
  91337. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91338. this.onCompleteObservable = new BABYLON.Observable();
  91339. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91340. this.state = null;
  91341. }
  91342. GLTFLoader.RegisterExtension = function (extension) {
  91343. if (GLTFLoader.Extensions[extension.name]) {
  91344. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  91345. return;
  91346. }
  91347. GLTFLoader.Extensions[extension.name] = extension;
  91348. };
  91349. GLTFLoader.prototype.dispose = function () { };
  91350. // #endregion
  91351. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  91352. var _this = this;
  91353. scene.useRightHandedSystem = true;
  91354. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91355. gltfRuntime.importOnlyMeshes = true;
  91356. if (meshesNames === "") {
  91357. gltfRuntime.importMeshesNames = [];
  91358. }
  91359. else if (typeof meshesNames === "string") {
  91360. gltfRuntime.importMeshesNames = [meshesNames];
  91361. }
  91362. else if (meshesNames && !(meshesNames instanceof Array)) {
  91363. gltfRuntime.importMeshesNames = [meshesNames];
  91364. }
  91365. else {
  91366. gltfRuntime.importMeshesNames = [];
  91367. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  91368. }
  91369. // Create nodes
  91370. _this._createNodes(gltfRuntime);
  91371. var meshes = new Array();
  91372. var skeletons = new Array();
  91373. // Fill arrays of meshes and skeletons
  91374. for (var nde in gltfRuntime.nodes) {
  91375. var node = gltfRuntime.nodes[nde];
  91376. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  91377. meshes.push(node.babylonNode);
  91378. }
  91379. }
  91380. for (var skl in gltfRuntime.skins) {
  91381. var skin = gltfRuntime.skins[skl];
  91382. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  91383. skeletons.push(skin.babylonSkeleton);
  91384. }
  91385. }
  91386. // Load buffers, shaders, materials, etc.
  91387. _this._loadBuffersAsync(gltfRuntime, function () {
  91388. _this._loadShadersAsync(gltfRuntime, function () {
  91389. importMaterials(gltfRuntime);
  91390. postLoad(gltfRuntime);
  91391. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91392. onSuccess(meshes, [], skeletons);
  91393. }
  91394. });
  91395. }, onProgress);
  91396. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  91397. onSuccess(meshes, [], skeletons);
  91398. }
  91399. }, onError);
  91400. return true;
  91401. };
  91402. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91403. var _this = this;
  91404. return new Promise(function (resolve, reject) {
  91405. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  91406. resolve({
  91407. meshes: meshes,
  91408. particleSystems: particleSystems,
  91409. skeletons: skeletons
  91410. });
  91411. }, onProgress, function (message) {
  91412. reject(new Error(message));
  91413. });
  91414. });
  91415. };
  91416. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  91417. var _this = this;
  91418. scene.useRightHandedSystem = true;
  91419. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  91420. // Load runtime extensios
  91421. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  91422. // Create nodes
  91423. _this._createNodes(gltfRuntime);
  91424. // Load buffers, shaders, materials, etc.
  91425. _this._loadBuffersAsync(gltfRuntime, function () {
  91426. _this._loadShadersAsync(gltfRuntime, function () {
  91427. importMaterials(gltfRuntime);
  91428. postLoad(gltfRuntime);
  91429. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  91430. onSuccess();
  91431. }
  91432. });
  91433. });
  91434. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  91435. onSuccess();
  91436. }
  91437. }, onError);
  91438. }, onError);
  91439. };
  91440. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91441. var _this = this;
  91442. return new Promise(function (resolve, reject) {
  91443. _this._loadAsync(scene, data, rootUrl, function () {
  91444. resolve();
  91445. }, onProgress, function (message) {
  91446. reject(new Error(message));
  91447. });
  91448. });
  91449. };
  91450. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  91451. var hasShaders = false;
  91452. var processShader = function (sha, shader) {
  91453. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  91454. gltfRuntime.loadedShaderCount++;
  91455. if (shaderString) {
  91456. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  91457. }
  91458. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  91459. onload();
  91460. }
  91461. }, function () {
  91462. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  91463. });
  91464. };
  91465. for (var sha in gltfRuntime.shaders) {
  91466. hasShaders = true;
  91467. var shader = gltfRuntime.shaders[sha];
  91468. if (shader) {
  91469. processShader.bind(this, sha, shader)();
  91470. }
  91471. else {
  91472. BABYLON.Tools.Error("No shader named: " + sha);
  91473. }
  91474. }
  91475. if (!hasShaders) {
  91476. onload();
  91477. }
  91478. };
  91479. ;
  91480. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  91481. var hasBuffers = false;
  91482. var processBuffer = function (buf, buffer) {
  91483. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  91484. gltfRuntime.loadedBufferCount++;
  91485. if (bufferView) {
  91486. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  91487. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  91488. }
  91489. gltfRuntime.loadedBufferViews[buf] = bufferView;
  91490. }
  91491. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  91492. onLoad();
  91493. }
  91494. }, function () {
  91495. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  91496. });
  91497. };
  91498. for (var buf in gltfRuntime.buffers) {
  91499. hasBuffers = true;
  91500. var buffer = gltfRuntime.buffers[buf];
  91501. if (buffer) {
  91502. processBuffer.bind(this, buf, buffer)();
  91503. }
  91504. else {
  91505. BABYLON.Tools.Error("No buffer named: " + buf);
  91506. }
  91507. }
  91508. if (!hasBuffers) {
  91509. onLoad();
  91510. }
  91511. };
  91512. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  91513. var currentScene = gltfRuntime.currentScene;
  91514. if (currentScene) {
  91515. // Only one scene even if multiple scenes are defined
  91516. for (var i = 0; i < currentScene.nodes.length; i++) {
  91517. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91518. }
  91519. }
  91520. else {
  91521. // Load all scenes
  91522. for (var thing in gltfRuntime.scenes) {
  91523. currentScene = gltfRuntime.scenes[thing];
  91524. for (var i = 0; i < currentScene.nodes.length; i++) {
  91525. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  91526. }
  91527. }
  91528. }
  91529. };
  91530. GLTFLoader.Extensions = {};
  91531. return GLTFLoader;
  91532. }());
  91533. GLTF1.GLTFLoader = GLTFLoader;
  91534. ;
  91535. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  91536. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91537. })(BABYLON || (BABYLON = {}));
  91538. //# sourceMappingURL=babylon.glTFLoader.js.map
  91539. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91540. var BABYLON;
  91541. (function (BABYLON) {
  91542. var GLTF1;
  91543. (function (GLTF1) {
  91544. /**
  91545. * Utils functions for GLTF
  91546. */
  91547. var GLTFUtils = /** @class */ (function () {
  91548. function GLTFUtils() {
  91549. }
  91550. /**
  91551. * Sets the given "parameter" matrix
  91552. * @param scene: the {BABYLON.Scene} object
  91553. * @param source: the source node where to pick the matrix
  91554. * @param parameter: the GLTF technique parameter
  91555. * @param uniformName: the name of the shader's uniform
  91556. * @param shaderMaterial: the shader material
  91557. */
  91558. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  91559. var mat = null;
  91560. if (parameter.semantic === "MODEL") {
  91561. mat = source.getWorldMatrix();
  91562. }
  91563. else if (parameter.semantic === "PROJECTION") {
  91564. mat = scene.getProjectionMatrix();
  91565. }
  91566. else if (parameter.semantic === "VIEW") {
  91567. mat = scene.getViewMatrix();
  91568. }
  91569. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  91570. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  91571. }
  91572. else if (parameter.semantic === "MODELVIEW") {
  91573. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  91574. }
  91575. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  91576. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  91577. }
  91578. else if (parameter.semantic === "MODELINVERSE") {
  91579. mat = source.getWorldMatrix().invert();
  91580. }
  91581. else if (parameter.semantic === "VIEWINVERSE") {
  91582. mat = scene.getViewMatrix().invert();
  91583. }
  91584. else if (parameter.semantic === "PROJECTIONINVERSE") {
  91585. mat = scene.getProjectionMatrix().invert();
  91586. }
  91587. else if (parameter.semantic === "MODELVIEWINVERSE") {
  91588. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  91589. }
  91590. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  91591. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  91592. }
  91593. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  91594. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  91595. }
  91596. else {
  91597. debugger;
  91598. }
  91599. if (mat) {
  91600. switch (parameter.type) {
  91601. case GLTF1.EParameterType.FLOAT_MAT2:
  91602. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  91603. break;
  91604. case GLTF1.EParameterType.FLOAT_MAT3:
  91605. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  91606. break;
  91607. case GLTF1.EParameterType.FLOAT_MAT4:
  91608. shaderMaterial.setMatrix(uniformName, mat);
  91609. break;
  91610. default: break;
  91611. }
  91612. }
  91613. };
  91614. /**
  91615. * Sets the given "parameter" matrix
  91616. * @param shaderMaterial: the shader material
  91617. * @param uniform: the name of the shader's uniform
  91618. * @param value: the value of the uniform
  91619. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  91620. */
  91621. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  91622. switch (type) {
  91623. case GLTF1.EParameterType.FLOAT:
  91624. shaderMaterial.setFloat(uniform, value);
  91625. return true;
  91626. case GLTF1.EParameterType.FLOAT_VEC2:
  91627. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  91628. return true;
  91629. case GLTF1.EParameterType.FLOAT_VEC3:
  91630. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  91631. return true;
  91632. case GLTF1.EParameterType.FLOAT_VEC4:
  91633. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  91634. return true;
  91635. default: return false;
  91636. }
  91637. };
  91638. /**
  91639. * Returns the wrap mode of the texture
  91640. * @param mode: the mode value
  91641. */
  91642. GLTFUtils.GetWrapMode = function (mode) {
  91643. switch (mode) {
  91644. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91645. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91646. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91647. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91648. }
  91649. };
  91650. /**
  91651. * Returns the byte stride giving an accessor
  91652. * @param accessor: the GLTF accessor objet
  91653. */
  91654. GLTFUtils.GetByteStrideFromType = function (accessor) {
  91655. // Needs this function since "byteStride" isn't requiered in glTF format
  91656. var type = accessor.type;
  91657. switch (type) {
  91658. case "VEC2": return 2;
  91659. case "VEC3": return 3;
  91660. case "VEC4": return 4;
  91661. case "MAT2": return 4;
  91662. case "MAT3": return 9;
  91663. case "MAT4": return 16;
  91664. default: return 1;
  91665. }
  91666. };
  91667. /**
  91668. * Returns the texture filter mode giving a mode value
  91669. * @param mode: the filter mode value
  91670. */
  91671. GLTFUtils.GetTextureFilterMode = function (mode) {
  91672. switch (mode) {
  91673. case GLTF1.ETextureFilterType.LINEAR:
  91674. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  91675. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  91676. case GLTF1.ETextureFilterType.NEAREST:
  91677. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  91678. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  91679. }
  91680. };
  91681. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  91682. var byteOffset = bufferView.byteOffset + byteOffset;
  91683. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  91684. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  91685. throw new Error("Buffer access is out of range");
  91686. }
  91687. var buffer = loadedBufferView.buffer;
  91688. byteOffset += loadedBufferView.byteOffset;
  91689. switch (componentType) {
  91690. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  91691. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  91692. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  91693. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  91694. default: return new Float32Array(buffer, byteOffset, byteLength);
  91695. }
  91696. };
  91697. /**
  91698. * Returns a buffer from its accessor
  91699. * @param gltfRuntime: the GLTF runtime
  91700. * @param accessor: the GLTF accessor
  91701. */
  91702. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  91703. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  91704. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  91705. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  91706. };
  91707. /**
  91708. * Decodes a buffer view into a string
  91709. * @param view: the buffer view
  91710. */
  91711. GLTFUtils.DecodeBufferToText = function (view) {
  91712. var result = "";
  91713. var length = view.byteLength;
  91714. for (var i = 0; i < length; ++i) {
  91715. result += String.fromCharCode(view[i]);
  91716. }
  91717. return result;
  91718. };
  91719. /**
  91720. * Returns the default material of gltf. Related to
  91721. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  91722. * @param scene: the Babylon.js scene
  91723. */
  91724. GLTFUtils.GetDefaultMaterial = function (scene) {
  91725. if (!GLTFUtils._DefaultMaterial) {
  91726. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  91727. "precision highp float;",
  91728. "",
  91729. "uniform mat4 worldView;",
  91730. "uniform mat4 projection;",
  91731. "",
  91732. "attribute vec3 position;",
  91733. "",
  91734. "void main(void)",
  91735. "{",
  91736. " gl_Position = projection * worldView * vec4(position, 1.0);",
  91737. "}"
  91738. ].join("\n");
  91739. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  91740. "precision highp float;",
  91741. "",
  91742. "uniform vec4 u_emission;",
  91743. "",
  91744. "void main(void)",
  91745. "{",
  91746. " gl_FragColor = u_emission;",
  91747. "}"
  91748. ].join("\n");
  91749. var shaderPath = {
  91750. vertex: "GLTFDefaultMaterial",
  91751. fragment: "GLTFDefaultMaterial"
  91752. };
  91753. var options = {
  91754. attributes: ["position"],
  91755. uniforms: ["worldView", "projection", "u_emission"],
  91756. samplers: new Array(),
  91757. needAlphaBlending: false
  91758. };
  91759. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  91760. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  91761. }
  91762. return GLTFUtils._DefaultMaterial;
  91763. };
  91764. // The GLTF default material
  91765. GLTFUtils._DefaultMaterial = null;
  91766. return GLTFUtils;
  91767. }());
  91768. GLTF1.GLTFUtils = GLTFUtils;
  91769. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91770. })(BABYLON || (BABYLON = {}));
  91771. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  91772. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91773. var BABYLON;
  91774. (function (BABYLON) {
  91775. var GLTF1;
  91776. (function (GLTF1) {
  91777. var GLTFLoaderExtension = /** @class */ (function () {
  91778. function GLTFLoaderExtension(name) {
  91779. this._name = name;
  91780. }
  91781. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  91782. get: function () {
  91783. return this._name;
  91784. },
  91785. enumerable: true,
  91786. configurable: true
  91787. });
  91788. /**
  91789. * Defines an override for loading the runtime
  91790. * Return true to stop further extensions from loading the runtime
  91791. */
  91792. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91793. return false;
  91794. };
  91795. /**
  91796. * Defines an onverride for creating gltf runtime
  91797. * Return true to stop further extensions from creating the runtime
  91798. */
  91799. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91800. return false;
  91801. };
  91802. /**
  91803. * Defines an override for loading buffers
  91804. * Return true to stop further extensions from loading this buffer
  91805. */
  91806. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91807. return false;
  91808. };
  91809. /**
  91810. * Defines an override for loading texture buffers
  91811. * Return true to stop further extensions from loading this texture data
  91812. */
  91813. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91814. return false;
  91815. };
  91816. /**
  91817. * Defines an override for creating textures
  91818. * Return true to stop further extensions from loading this texture
  91819. */
  91820. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91821. return false;
  91822. };
  91823. /**
  91824. * Defines an override for loading shader strings
  91825. * Return true to stop further extensions from loading this shader data
  91826. */
  91827. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91828. return false;
  91829. };
  91830. /**
  91831. * Defines an override for loading materials
  91832. * Return true to stop further extensions from loading this material
  91833. */
  91834. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91835. return false;
  91836. };
  91837. // ---------
  91838. // Utilities
  91839. // ---------
  91840. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91841. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91842. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  91843. }, function () {
  91844. setTimeout(function () {
  91845. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91846. });
  91847. });
  91848. };
  91849. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91850. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91851. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  91852. }, function () {
  91853. setTimeout(function () {
  91854. onSuccess();
  91855. });
  91856. });
  91857. };
  91858. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  91859. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91860. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91861. }, function () {
  91862. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  91863. });
  91864. };
  91865. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  91866. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  91867. };
  91868. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91869. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91870. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91871. }, function () {
  91872. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  91873. });
  91874. };
  91875. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  91876. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91877. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91878. }, function () {
  91879. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  91880. });
  91881. };
  91882. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91883. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91884. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91885. }, function () {
  91886. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  91887. });
  91888. };
  91889. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  91890. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  91891. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91892. }, function () {
  91893. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  91894. });
  91895. };
  91896. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  91897. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  91898. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  91899. if (func(loaderExtension)) {
  91900. return;
  91901. }
  91902. }
  91903. defaultFunc();
  91904. };
  91905. return GLTFLoaderExtension;
  91906. }());
  91907. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  91908. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91909. })(BABYLON || (BABYLON = {}));
  91910. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91911. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91912. var BABYLON;
  91913. (function (BABYLON) {
  91914. var GLTF1;
  91915. (function (GLTF1) {
  91916. var BinaryExtensionBufferName = "binary_glTF";
  91917. ;
  91918. ;
  91919. var GLTFBinaryExtension = /** @class */ (function (_super) {
  91920. __extends(GLTFBinaryExtension, _super);
  91921. function GLTFBinaryExtension() {
  91922. return _super.call(this, "KHR_binary_glTF") || this;
  91923. }
  91924. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  91925. var extensionsUsed = data.json.extensionsUsed;
  91926. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  91927. return false;
  91928. }
  91929. this._bin = data.bin;
  91930. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  91931. return true;
  91932. };
  91933. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91934. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  91935. return false;
  91936. }
  91937. if (id !== BinaryExtensionBufferName) {
  91938. return false;
  91939. }
  91940. onSuccess(this._bin);
  91941. return true;
  91942. };
  91943. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  91944. var texture = gltfRuntime.textures[id];
  91945. var source = gltfRuntime.images[texture.source];
  91946. if (!source.extensions || !(this.name in source.extensions)) {
  91947. return false;
  91948. }
  91949. var sourceExt = source.extensions[this.name];
  91950. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  91951. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91952. onSuccess(buffer);
  91953. return true;
  91954. };
  91955. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  91956. var shader = gltfRuntime.shaders[id];
  91957. if (!shader.extensions || !(this.name in shader.extensions)) {
  91958. return false;
  91959. }
  91960. var binaryExtensionShader = shader.extensions[this.name];
  91961. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  91962. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  91963. setTimeout(function () {
  91964. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  91965. onSuccess(shaderString);
  91966. });
  91967. return true;
  91968. };
  91969. return GLTFBinaryExtension;
  91970. }(GLTF1.GLTFLoaderExtension));
  91971. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  91972. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  91973. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91974. })(BABYLON || (BABYLON = {}));
  91975. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  91976. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91977. var BABYLON;
  91978. (function (BABYLON) {
  91979. var GLTF1;
  91980. (function (GLTF1) {
  91981. ;
  91982. ;
  91983. ;
  91984. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  91985. __extends(GLTFMaterialsCommonExtension, _super);
  91986. function GLTFMaterialsCommonExtension() {
  91987. return _super.call(this, "KHR_materials_common") || this;
  91988. }
  91989. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  91990. if (!gltfRuntime.extensions)
  91991. return false;
  91992. var extension = gltfRuntime.extensions[this.name];
  91993. if (!extension)
  91994. return false;
  91995. // Create lights
  91996. var lights = extension.lights;
  91997. if (lights) {
  91998. for (var thing in lights) {
  91999. var light = lights[thing];
  92000. switch (light.type) {
  92001. case "ambient":
  92002. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  92003. var ambient = light.ambient;
  92004. if (ambient) {
  92005. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  92006. }
  92007. break;
  92008. case "point":
  92009. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  92010. var point = light.point;
  92011. if (point) {
  92012. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  92013. }
  92014. break;
  92015. case "directional":
  92016. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  92017. var directional = light.directional;
  92018. if (directional) {
  92019. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  92020. }
  92021. break;
  92022. case "spot":
  92023. var spot = light.spot;
  92024. if (spot) {
  92025. 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);
  92026. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  92027. }
  92028. break;
  92029. default:
  92030. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  92031. break;
  92032. }
  92033. }
  92034. }
  92035. return false;
  92036. };
  92037. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  92038. var material = gltfRuntime.materials[id];
  92039. if (!material || !material.extensions)
  92040. return false;
  92041. var extension = material.extensions[this.name];
  92042. if (!extension)
  92043. return false;
  92044. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  92045. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  92046. if (extension.technique === "CONSTANT") {
  92047. standardMaterial.disableLighting = true;
  92048. }
  92049. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  92050. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  92051. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  92052. // Ambient
  92053. if (typeof extension.values.ambient === "string") {
  92054. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  92055. }
  92056. else {
  92057. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  92058. }
  92059. // Diffuse
  92060. if (typeof extension.values.diffuse === "string") {
  92061. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  92062. }
  92063. else {
  92064. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  92065. }
  92066. // Emission
  92067. if (typeof extension.values.emission === "string") {
  92068. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  92069. }
  92070. else {
  92071. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  92072. }
  92073. // Specular
  92074. if (typeof extension.values.specular === "string") {
  92075. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  92076. }
  92077. else {
  92078. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  92079. }
  92080. return true;
  92081. };
  92082. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  92083. // Create buffer from texture url
  92084. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  92085. // Create texture from buffer
  92086. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  92087. }, onError);
  92088. };
  92089. return GLTFMaterialsCommonExtension;
  92090. }(GLTF1.GLTFLoaderExtension));
  92091. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  92092. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  92093. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  92094. })(BABYLON || (BABYLON = {}));
  92095. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  92096. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92097. var BABYLON;
  92098. (function (BABYLON) {
  92099. var GLTF2;
  92100. (function (GLTF2) {
  92101. var ArrayItem = /** @class */ (function () {
  92102. function ArrayItem() {
  92103. }
  92104. ArrayItem.Assign = function (values) {
  92105. if (values) {
  92106. for (var index = 0; index < values.length; index++) {
  92107. values[index]._index = index;
  92108. }
  92109. }
  92110. };
  92111. return ArrayItem;
  92112. }());
  92113. GLTF2.ArrayItem = ArrayItem;
  92114. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92115. })(BABYLON || (BABYLON = {}));
  92116. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  92117. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92118. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  92119. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  92120. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92121. var BABYLON;
  92122. (function (BABYLON) {
  92123. var GLTF2;
  92124. (function (GLTF2) {
  92125. var GLTFLoader = /** @class */ (function () {
  92126. function GLTFLoader() {
  92127. this._completePromises = new Array();
  92128. this._disposed = false;
  92129. this._state = null;
  92130. this._extensions = {};
  92131. this._defaultSampler = {};
  92132. this._requests = new Array();
  92133. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  92134. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  92135. this.compileMaterials = false;
  92136. this.useClipPlane = false;
  92137. this.compileShadowGenerators = false;
  92138. this.onDisposeObservable = new BABYLON.Observable();
  92139. this.onMeshLoadedObservable = new BABYLON.Observable();
  92140. this.onTextureLoadedObservable = new BABYLON.Observable();
  92141. this.onMaterialLoadedObservable = new BABYLON.Observable();
  92142. this.onExtensionLoadedObservable = new BABYLON.Observable();
  92143. this.onCompleteObservable = new BABYLON.Observable();
  92144. }
  92145. GLTFLoader._Register = function (name, factory) {
  92146. if (GLTFLoader._Factories[name]) {
  92147. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  92148. return;
  92149. }
  92150. GLTFLoader._Factories[name] = factory;
  92151. // Keep the order of registration so that extensions registered first are called first.
  92152. GLTFLoader._Names.push(name);
  92153. };
  92154. Object.defineProperty(GLTFLoader.prototype, "state", {
  92155. get: function () {
  92156. return this._state;
  92157. },
  92158. enumerable: true,
  92159. configurable: true
  92160. });
  92161. GLTFLoader.prototype.dispose = function () {
  92162. if (this._disposed) {
  92163. return;
  92164. }
  92165. this._disposed = true;
  92166. this.onDisposeObservable.notifyObservers(this);
  92167. this.onDisposeObservable.clear();
  92168. this._clear();
  92169. };
  92170. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  92171. var _this = this;
  92172. return Promise.resolve().then(function () {
  92173. var nodes = null;
  92174. if (meshesNames) {
  92175. var nodeMap_1 = {};
  92176. if (_this._gltf.nodes) {
  92177. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  92178. var node = _a[_i];
  92179. if (node.name) {
  92180. nodeMap_1[node.name] = node;
  92181. }
  92182. }
  92183. }
  92184. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  92185. nodes = names.map(function (name) {
  92186. var node = nodeMap_1[name];
  92187. if (!node) {
  92188. throw new Error("Failed to find node " + name);
  92189. }
  92190. return node;
  92191. });
  92192. }
  92193. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  92194. return {
  92195. meshes: _this._getMeshes(),
  92196. particleSystems: [],
  92197. skeletons: _this._getSkeletons(),
  92198. };
  92199. });
  92200. });
  92201. };
  92202. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  92203. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  92204. };
  92205. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  92206. var _this = this;
  92207. return Promise.resolve().then(function () {
  92208. _this._loadExtensions();
  92209. _this._babylonScene = scene;
  92210. _this._rootUrl = rootUrl;
  92211. _this._progressCallback = onProgress;
  92212. _this._state = BABYLON.GLTFLoaderState.Loading;
  92213. _this._loadData(data);
  92214. _this._checkExtensions();
  92215. var promises = new Array();
  92216. if (nodes) {
  92217. promises.push(_this._loadNodesAsync(nodes));
  92218. }
  92219. else {
  92220. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  92221. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  92222. }
  92223. if (_this.compileMaterials) {
  92224. promises.push(_this._compileMaterialsAsync());
  92225. }
  92226. if (_this.compileShadowGenerators) {
  92227. promises.push(_this._compileShadowGeneratorsAsync());
  92228. }
  92229. return Promise.all(promises).then(function () {
  92230. _this._state = BABYLON.GLTFLoaderState.Ready;
  92231. _this._startAnimations();
  92232. BABYLON.Tools.SetImmediate(function () {
  92233. if (!_this._disposed) {
  92234. Promise.all(_this._completePromises).then(function () {
  92235. _this._state = BABYLON.GLTFLoaderState.Complete;
  92236. _this.onCompleteObservable.notifyObservers(_this);
  92237. _this.onCompleteObservable.clear();
  92238. _this._clear();
  92239. }).catch(function (error) {
  92240. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92241. _this._clear();
  92242. });
  92243. }
  92244. });
  92245. });
  92246. }).catch(function (error) {
  92247. BABYLON.Tools.Error("glTF Loader: " + error.message);
  92248. _this._clear();
  92249. throw error;
  92250. });
  92251. };
  92252. GLTFLoader.prototype._loadExtensions = function () {
  92253. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92254. var name_1 = _a[_i];
  92255. var extension = GLTFLoader._Factories[name_1](this);
  92256. this._extensions[name_1] = extension;
  92257. this.onExtensionLoadedObservable.notifyObservers(extension);
  92258. }
  92259. this.onExtensionLoadedObservable.clear();
  92260. };
  92261. GLTFLoader.prototype._loadData = function (data) {
  92262. this._gltf = data.json;
  92263. this._setupData();
  92264. if (data.bin) {
  92265. var buffers = this._gltf.buffers;
  92266. if (buffers && buffers[0] && !buffers[0].uri) {
  92267. var binaryBuffer = buffers[0];
  92268. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  92269. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  92270. }
  92271. binaryBuffer._data = Promise.resolve(data.bin);
  92272. }
  92273. else {
  92274. BABYLON.Tools.Warn("Unexpected BIN chunk");
  92275. }
  92276. }
  92277. };
  92278. GLTFLoader.prototype._setupData = function () {
  92279. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  92280. GLTF2.ArrayItem.Assign(this._gltf.animations);
  92281. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  92282. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  92283. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  92284. GLTF2.ArrayItem.Assign(this._gltf.images);
  92285. GLTF2.ArrayItem.Assign(this._gltf.materials);
  92286. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  92287. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  92288. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  92289. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  92290. GLTF2.ArrayItem.Assign(this._gltf.skins);
  92291. GLTF2.ArrayItem.Assign(this._gltf.textures);
  92292. if (this._gltf.nodes) {
  92293. var nodeParents = {};
  92294. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  92295. var node = _a[_i];
  92296. if (node.children) {
  92297. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  92298. var index = _c[_b];
  92299. nodeParents[index] = node._index;
  92300. }
  92301. }
  92302. }
  92303. var rootNode = this._createRootNode();
  92304. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  92305. var node = _e[_d];
  92306. var parentIndex = nodeParents[node._index];
  92307. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  92308. }
  92309. }
  92310. };
  92311. GLTFLoader.prototype._checkExtensions = function () {
  92312. if (this._gltf.extensionsRequired) {
  92313. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  92314. var name_2 = _a[_i];
  92315. var extension = this._extensions[name_2];
  92316. if (!extension || !extension.enabled) {
  92317. throw new Error("Require extension " + name_2 + " is not available");
  92318. }
  92319. }
  92320. }
  92321. };
  92322. GLTFLoader.prototype._createRootNode = function () {
  92323. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  92324. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  92325. switch (this.coordinateSystemMode) {
  92326. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  92327. if (!this._babylonScene.useRightHandedSystem) {
  92328. rootNode.rotation = [0, 1, 0, 0];
  92329. rootNode.scale = [1, 1, -1];
  92330. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  92331. }
  92332. break;
  92333. }
  92334. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  92335. this._babylonScene.useRightHandedSystem = true;
  92336. break;
  92337. }
  92338. default: {
  92339. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  92340. }
  92341. }
  92342. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  92343. return rootNode;
  92344. };
  92345. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  92346. var promises = new Array();
  92347. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  92348. var node = nodes_1[_i];
  92349. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92350. }
  92351. promises.push(this._loadAnimationsAsync());
  92352. return Promise.all(promises).then(function () { });
  92353. };
  92354. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  92355. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  92356. if (promise) {
  92357. return promise;
  92358. }
  92359. var promises = new Array();
  92360. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  92361. var index = _a[_i];
  92362. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  92363. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  92364. }
  92365. promises.push(this._loadAnimationsAsync());
  92366. return Promise.all(promises).then(function () { });
  92367. };
  92368. GLTFLoader.prototype._getMeshes = function () {
  92369. var meshes = new Array();
  92370. // Root mesh is always first.
  92371. meshes.push(this._rootBabylonMesh);
  92372. var nodes = this._gltf.nodes;
  92373. if (nodes) {
  92374. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  92375. var node = nodes_2[_i];
  92376. if (node._babylonMesh) {
  92377. meshes.push(node._babylonMesh);
  92378. }
  92379. if (node._primitiveBabylonMeshes) {
  92380. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  92381. var babylonMesh = _b[_a];
  92382. meshes.push(babylonMesh);
  92383. }
  92384. }
  92385. }
  92386. }
  92387. return meshes;
  92388. };
  92389. GLTFLoader.prototype._getSkeletons = function () {
  92390. var skeletons = new Array();
  92391. var skins = this._gltf.skins;
  92392. if (skins) {
  92393. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  92394. var skin = skins_1[_i];
  92395. if (skin._babylonSkeleton) {
  92396. skeletons.push(skin._babylonSkeleton);
  92397. }
  92398. }
  92399. }
  92400. return skeletons;
  92401. };
  92402. GLTFLoader.prototype._startAnimations = function () {
  92403. var animations = this._gltf.animations;
  92404. if (!animations) {
  92405. return;
  92406. }
  92407. switch (this.animationStartMode) {
  92408. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  92409. // do nothing
  92410. break;
  92411. }
  92412. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  92413. var animation = animations[0];
  92414. animation._babylonAnimationGroup.start(true);
  92415. break;
  92416. }
  92417. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  92418. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  92419. var animation = animations_1[_i];
  92420. animation._babylonAnimationGroup.start(true);
  92421. }
  92422. break;
  92423. }
  92424. default: {
  92425. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  92426. return;
  92427. }
  92428. }
  92429. };
  92430. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  92431. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  92432. if (promise) {
  92433. return promise;
  92434. }
  92435. if (node._babylonMesh) {
  92436. throw new Error(context + ": Invalid recursive node hierarchy");
  92437. }
  92438. var promises = new Array();
  92439. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  92440. node._babylonMesh = babylonMesh;
  92441. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92442. node._babylonAnimationTargets.push(babylonMesh);
  92443. GLTFLoader._LoadTransform(node, babylonMesh);
  92444. if (node.mesh != undefined) {
  92445. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  92446. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  92447. }
  92448. if (node.children) {
  92449. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  92450. var index = _a[_i];
  92451. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  92452. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  92453. }
  92454. }
  92455. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92456. return Promise.all(promises).then(function () { });
  92457. };
  92458. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  92459. // TODO: instancing
  92460. var promises = new Array();
  92461. var primitives = mesh.primitives;
  92462. if (!primitives || primitives.length === 0) {
  92463. throw new Error(context + ": Primitives are missing");
  92464. }
  92465. GLTF2.ArrayItem.Assign(primitives);
  92466. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  92467. var primitive = primitives_1[_i];
  92468. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  92469. }
  92470. if (node.skin != undefined) {
  92471. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  92472. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  92473. }
  92474. return Promise.all(promises).then(function () {
  92475. if (node._primitiveBabylonMeshes) {
  92476. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92477. var primitiveBabylonMesh = _a[_i];
  92478. primitiveBabylonMesh._refreshBoundingInfo(true);
  92479. }
  92480. }
  92481. });
  92482. };
  92483. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  92484. var _this = this;
  92485. var promises = new Array();
  92486. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  92487. babylonMesh.setEnabled(false);
  92488. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  92489. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  92490. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  92491. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  92492. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  92493. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  92494. }));
  92495. if (primitive.material == undefined) {
  92496. babylonMesh.material = this._getDefaultMaterial();
  92497. }
  92498. else {
  92499. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  92500. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  92501. }
  92502. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  92503. return Promise.all(promises).then(function () {
  92504. babylonMesh.setEnabled(true);
  92505. });
  92506. };
  92507. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  92508. var _this = this;
  92509. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  92510. if (promise) {
  92511. return promise;
  92512. }
  92513. var attributes = primitive.attributes;
  92514. if (!attributes) {
  92515. throw new Error(context + ": Attributes are missing");
  92516. }
  92517. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  92518. // TODO: handle other primitive modes
  92519. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  92520. }
  92521. var promises = new Array();
  92522. var babylonVertexData = new BABYLON.VertexData();
  92523. if (primitive.indices == undefined) {
  92524. var positionAccessorIndex = attributes["POSITION"];
  92525. if (positionAccessorIndex != undefined) {
  92526. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  92527. babylonVertexData.indices = new Uint32Array(accessor.count);
  92528. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  92529. babylonVertexData.indices[i] = i;
  92530. }
  92531. }
  92532. }
  92533. else {
  92534. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  92535. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  92536. babylonVertexData.indices = data;
  92537. }));
  92538. }
  92539. var loadAttribute = function (attribute, kind) {
  92540. if (attributes[attribute] == undefined) {
  92541. return;
  92542. }
  92543. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  92544. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  92545. babylonMesh._delayInfo.push(kind);
  92546. }
  92547. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92548. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92549. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  92550. if (attribute === "COLOR_0") {
  92551. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  92552. babylonMesh.hasVertexAlpha = true;
  92553. if (accessor.type === "VEC3") {
  92554. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  92555. }
  92556. }
  92557. babylonVertexData.set(attributeData, kind);
  92558. }));
  92559. };
  92560. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  92561. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  92562. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  92563. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  92564. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  92565. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  92566. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  92567. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  92568. return Promise.all(promises).then(function () {
  92569. return babylonVertexData;
  92570. });
  92571. };
  92572. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  92573. if (!primitive.targets) {
  92574. return;
  92575. }
  92576. if (node._numMorphTargets == undefined) {
  92577. node._numMorphTargets = primitive.targets.length;
  92578. }
  92579. else if (primitive.targets.length !== node._numMorphTargets) {
  92580. throw new Error(context + ": Primitives do not have the same number of targets");
  92581. }
  92582. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  92583. for (var index = 0; index < primitive.targets.length; index++) {
  92584. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  92585. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  92586. // TODO: tell the target whether it has positions, normals, tangents
  92587. }
  92588. };
  92589. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  92590. if (!primitive.targets) {
  92591. return Promise.resolve();
  92592. }
  92593. var promises = new Array();
  92594. var morphTargetManager = babylonMesh.morphTargetManager;
  92595. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  92596. var babylonMorphTarget = morphTargetManager.getTarget(index);
  92597. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  92598. }
  92599. return Promise.all(promises).then(function () { });
  92600. };
  92601. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  92602. var _this = this;
  92603. var promises = new Array();
  92604. var loadAttribute = function (attribute, setData) {
  92605. if (attributes[attribute] == undefined) {
  92606. return;
  92607. }
  92608. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  92609. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92610. setData(data);
  92611. }));
  92612. };
  92613. loadAttribute("POSITION", function (data) {
  92614. if (babylonVertexData.positions) {
  92615. for (var i = 0; i < data.length; i++) {
  92616. data[i] += babylonVertexData.positions[i];
  92617. }
  92618. babylonMorphTarget.setPositions(data);
  92619. }
  92620. });
  92621. loadAttribute("NORMAL", function (data) {
  92622. if (babylonVertexData.normals) {
  92623. for (var i = 0; i < data.length; i++) {
  92624. data[i] += babylonVertexData.normals[i];
  92625. }
  92626. babylonMorphTarget.setNormals(data);
  92627. }
  92628. });
  92629. loadAttribute("TANGENT", function (data) {
  92630. if (babylonVertexData.tangents) {
  92631. // Tangent data for morph targets is stored as xyz delta.
  92632. // The vertexData.tangent is stored as xyzw.
  92633. // So we need to skip every fourth vertexData.tangent.
  92634. for (var i = 0, j = 0; i < data.length; i++) {
  92635. data[i] += babylonVertexData.tangents[j++];
  92636. if ((i + 1) % 3 == 0) {
  92637. j++;
  92638. }
  92639. }
  92640. babylonMorphTarget.setTangents(data);
  92641. }
  92642. });
  92643. return Promise.all(promises).then(function () { });
  92644. };
  92645. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  92646. if (accessor.componentType == 5126 /* FLOAT */) {
  92647. return data;
  92648. }
  92649. var factor = 1;
  92650. if (accessor.normalized) {
  92651. switch (accessor.componentType) {
  92652. case 5121 /* UNSIGNED_BYTE */: {
  92653. factor = 1 / 255;
  92654. break;
  92655. }
  92656. case 5123 /* UNSIGNED_SHORT */: {
  92657. factor = 1 / 65535;
  92658. break;
  92659. }
  92660. default: {
  92661. throw new Error(context + ": Invalid component type " + accessor.componentType);
  92662. }
  92663. }
  92664. }
  92665. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  92666. for (var i = 0; i < result.length; i++) {
  92667. result[i] = data[i] * factor;
  92668. }
  92669. return result;
  92670. };
  92671. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  92672. var result = new Float32Array(data.length / 3 * 4);
  92673. var offset = 0;
  92674. for (var i = 0; i < result.length; i++) {
  92675. if ((i + 1) % 4 === 0) {
  92676. result[i] = 1;
  92677. }
  92678. else {
  92679. result[i] = data[offset++];
  92680. }
  92681. }
  92682. return result;
  92683. };
  92684. GLTFLoader._LoadTransform = function (node, babylonNode) {
  92685. var position = BABYLON.Vector3.Zero();
  92686. var rotation = BABYLON.Quaternion.Identity();
  92687. var scaling = BABYLON.Vector3.One();
  92688. if (node.matrix) {
  92689. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  92690. matrix.decompose(scaling, rotation, position);
  92691. }
  92692. else {
  92693. if (node.translation)
  92694. position = BABYLON.Vector3.FromArray(node.translation);
  92695. if (node.rotation)
  92696. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  92697. if (node.scale)
  92698. scaling = BABYLON.Vector3.FromArray(node.scale);
  92699. }
  92700. babylonNode.position = position;
  92701. babylonNode.rotationQuaternion = rotation;
  92702. babylonNode.scaling = scaling;
  92703. };
  92704. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  92705. var _this = this;
  92706. var assignSkeleton = function () {
  92707. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92708. var babylonMesh = _a[_i];
  92709. babylonMesh.skeleton = skin._babylonSkeleton;
  92710. }
  92711. node._babylonMesh.parent = _this._rootBabylonMesh;
  92712. node._babylonMesh.position = BABYLON.Vector3.Zero();
  92713. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  92714. node._babylonMesh.scaling = BABYLON.Vector3.One();
  92715. };
  92716. if (skin._loaded) {
  92717. return skin._loaded.then(function () {
  92718. assignSkeleton();
  92719. });
  92720. }
  92721. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  92722. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  92723. var skeletonId = "skeleton" + skin._index;
  92724. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  92725. skin._babylonSkeleton = babylonSkeleton;
  92726. _this._loadBones(context, skin, inverseBindMatricesData);
  92727. assignSkeleton();
  92728. }));
  92729. };
  92730. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  92731. if (skin.inverseBindMatrices == undefined) {
  92732. return Promise.resolve(null);
  92733. }
  92734. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  92735. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  92736. return data;
  92737. });
  92738. };
  92739. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  92740. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  92741. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  92742. node._babylonAnimationTargets.push(babylonBone);
  92743. return babylonBone;
  92744. };
  92745. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  92746. var babylonBones = {};
  92747. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  92748. var index = _a[_i];
  92749. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  92750. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  92751. }
  92752. };
  92753. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  92754. var babylonBone = babylonBones[node._index];
  92755. if (babylonBone) {
  92756. return babylonBone;
  92757. }
  92758. var boneIndex = skin.joints.indexOf(node._index);
  92759. var baseMatrix = BABYLON.Matrix.Identity();
  92760. if (inverseBindMatricesData && boneIndex !== -1) {
  92761. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  92762. baseMatrix.invertToRef(baseMatrix);
  92763. }
  92764. var babylonParentBone = null;
  92765. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  92766. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  92767. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  92768. }
  92769. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  92770. babylonBones[node._index] = babylonBone;
  92771. return babylonBone;
  92772. };
  92773. GLTFLoader.prototype._getNodeMatrix = function (node) {
  92774. return node.matrix ?
  92775. BABYLON.Matrix.FromArray(node.matrix) :
  92776. 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());
  92777. };
  92778. GLTFLoader.prototype._loadAnimationsAsync = function () {
  92779. var animations = this._gltf.animations;
  92780. if (!animations) {
  92781. return Promise.resolve();
  92782. }
  92783. var promises = new Array();
  92784. for (var index = 0; index < animations.length; index++) {
  92785. var animation = animations[index];
  92786. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  92787. }
  92788. return Promise.all(promises).then(function () { });
  92789. };
  92790. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  92791. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  92792. animation._babylonAnimationGroup = babylonAnimationGroup;
  92793. var promises = new Array();
  92794. GLTF2.ArrayItem.Assign(animation.channels);
  92795. GLTF2.ArrayItem.Assign(animation.samplers);
  92796. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  92797. var channel = _a[_i];
  92798. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  92799. }
  92800. return Promise.all(promises).then(function () {
  92801. babylonAnimationGroup.normalize();
  92802. });
  92803. };
  92804. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  92805. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  92806. if (!targetNode._babylonMesh) {
  92807. return Promise.resolve();
  92808. }
  92809. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  92810. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  92811. var targetPath;
  92812. var animationType;
  92813. switch (channel.target.path) {
  92814. case "translation" /* TRANSLATION */: {
  92815. targetPath = "position";
  92816. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92817. break;
  92818. }
  92819. case "rotation" /* ROTATION */: {
  92820. targetPath = "rotationQuaternion";
  92821. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92822. break;
  92823. }
  92824. case "scale" /* SCALE */: {
  92825. targetPath = "scaling";
  92826. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92827. break;
  92828. }
  92829. case "weights" /* WEIGHTS */: {
  92830. targetPath = "influence";
  92831. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  92832. break;
  92833. }
  92834. default: {
  92835. throw new Error(context + ": Invalid target path " + channel.target.path);
  92836. }
  92837. }
  92838. var outputBufferOffset = 0;
  92839. var getNextOutputValue;
  92840. switch (targetPath) {
  92841. case "position": {
  92842. getNextOutputValue = function () {
  92843. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92844. outputBufferOffset += 3;
  92845. return value;
  92846. };
  92847. break;
  92848. }
  92849. case "rotationQuaternion": {
  92850. getNextOutputValue = function () {
  92851. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  92852. outputBufferOffset += 4;
  92853. return value;
  92854. };
  92855. break;
  92856. }
  92857. case "scaling": {
  92858. getNextOutputValue = function () {
  92859. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  92860. outputBufferOffset += 3;
  92861. return value;
  92862. };
  92863. break;
  92864. }
  92865. case "influence": {
  92866. getNextOutputValue = function () {
  92867. var value = new Array(targetNode._numMorphTargets);
  92868. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  92869. value[i] = data.output[outputBufferOffset++];
  92870. }
  92871. return value;
  92872. };
  92873. break;
  92874. }
  92875. }
  92876. var getNextKey;
  92877. switch (data.interpolation) {
  92878. case "STEP" /* STEP */: {
  92879. getNextKey = function (frameIndex) { return ({
  92880. frame: data.input[frameIndex],
  92881. value: getNextOutputValue(),
  92882. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  92883. }); };
  92884. break;
  92885. }
  92886. case "LINEAR" /* LINEAR */: {
  92887. getNextKey = function (frameIndex) { return ({
  92888. frame: data.input[frameIndex],
  92889. value: getNextOutputValue()
  92890. }); };
  92891. break;
  92892. }
  92893. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92894. getNextKey = function (frameIndex) { return ({
  92895. frame: data.input[frameIndex],
  92896. inTangent: getNextOutputValue(),
  92897. value: getNextOutputValue(),
  92898. outTangent: getNextOutputValue()
  92899. }); };
  92900. break;
  92901. }
  92902. }
  92903. var keys;
  92904. if (data.input.length === 1) {
  92905. var key = getNextKey(0);
  92906. keys = [
  92907. { frame: key.frame, value: key.value },
  92908. { frame: key.frame + 1, value: key.value }
  92909. ];
  92910. }
  92911. else {
  92912. keys = new Array(data.input.length);
  92913. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  92914. keys[frameIndex] = getNextKey(frameIndex);
  92915. }
  92916. }
  92917. if (targetPath === "influence") {
  92918. var _loop_1 = function (targetIndex) {
  92919. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92920. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92921. babylonAnimation.setKeys(keys.map(function (key) { return ({
  92922. frame: key.frame,
  92923. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  92924. value: key.value[targetIndex],
  92925. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  92926. }); }));
  92927. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  92928. var babylonMesh = _a[_i];
  92929. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  92930. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  92931. }
  92932. };
  92933. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  92934. _loop_1(targetIndex);
  92935. }
  92936. }
  92937. else {
  92938. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  92939. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  92940. babylonAnimation.setKeys(keys);
  92941. if (targetNode._babylonAnimationTargets) {
  92942. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  92943. var target = _a[_i];
  92944. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  92945. }
  92946. }
  92947. }
  92948. });
  92949. };
  92950. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  92951. if (sampler._data) {
  92952. return sampler._data;
  92953. }
  92954. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  92955. switch (interpolation) {
  92956. case "STEP" /* STEP */:
  92957. case "LINEAR" /* LINEAR */:
  92958. case "CUBICSPLINE" /* CUBICSPLINE */: {
  92959. break;
  92960. }
  92961. default: {
  92962. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  92963. }
  92964. }
  92965. var inputData;
  92966. var outputData;
  92967. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  92968. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  92969. sampler._data = Promise.all([
  92970. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  92971. inputData = data;
  92972. }),
  92973. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  92974. outputData = data;
  92975. })
  92976. ]).then(function () {
  92977. return {
  92978. input: inputData,
  92979. interpolation: interpolation,
  92980. output: outputData,
  92981. };
  92982. });
  92983. return sampler._data;
  92984. };
  92985. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  92986. if (buffer._data) {
  92987. return buffer._data;
  92988. }
  92989. if (!buffer.uri) {
  92990. throw new Error(context + ": Uri is missing");
  92991. }
  92992. buffer._data = this._loadUriAsync(context, buffer.uri);
  92993. return buffer._data;
  92994. };
  92995. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  92996. if (bufferView._data) {
  92997. return bufferView._data;
  92998. }
  92999. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  93000. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  93001. try {
  93002. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  93003. }
  93004. catch (e) {
  93005. throw new Error(context + ": " + e.message);
  93006. }
  93007. });
  93008. return bufferView._data;
  93009. };
  93010. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  93011. var _this = this;
  93012. if (accessor.sparse) {
  93013. throw new Error(context + ": Sparse accessors are not currently supported");
  93014. }
  93015. if (accessor._data) {
  93016. return accessor._data;
  93017. }
  93018. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  93019. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  93020. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  93021. var byteOffset = accessor.byteOffset || 0;
  93022. var byteStride = bufferView.byteStride;
  93023. if (byteStride === 0) {
  93024. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  93025. }
  93026. try {
  93027. switch (accessor.componentType) {
  93028. case 5120 /* BYTE */: {
  93029. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93030. }
  93031. case 5121 /* UNSIGNED_BYTE */: {
  93032. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93033. }
  93034. case 5122 /* SHORT */: {
  93035. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93036. }
  93037. case 5123 /* UNSIGNED_SHORT */: {
  93038. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93039. }
  93040. case 5125 /* UNSIGNED_INT */: {
  93041. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93042. }
  93043. case 5126 /* FLOAT */: {
  93044. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  93045. }
  93046. default: {
  93047. throw new Error(context + ": Invalid component type " + accessor.componentType);
  93048. }
  93049. }
  93050. }
  93051. catch (e) {
  93052. throw new Error(context + ": " + e);
  93053. }
  93054. });
  93055. return accessor._data;
  93056. };
  93057. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  93058. byteOffset += data.byteOffset;
  93059. var targetLength = count * numComponents;
  93060. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  93061. return new typedArray(data.buffer, byteOffset, targetLength);
  93062. }
  93063. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  93064. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  93065. var targetBuffer = new typedArray(targetLength);
  93066. var sourceIndex = 0;
  93067. var targetIndex = 0;
  93068. while (targetIndex < targetLength) {
  93069. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  93070. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  93071. targetIndex++;
  93072. }
  93073. sourceIndex += elementStride;
  93074. }
  93075. return targetBuffer;
  93076. };
  93077. GLTFLoader.prototype._getDefaultMaterial = function () {
  93078. var id = "__gltf_default";
  93079. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  93080. if (!babylonMaterial) {
  93081. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  93082. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93083. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93084. babylonMaterial.metallic = 1;
  93085. babylonMaterial.roughness = 1;
  93086. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93087. }
  93088. return babylonMaterial;
  93089. };
  93090. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  93091. var promises = new Array();
  93092. var babylonMaterial = material._babylonMaterial;
  93093. // Ensure metallic workflow
  93094. babylonMaterial.metallic = 1;
  93095. babylonMaterial.roughness = 1;
  93096. var properties = material.pbrMetallicRoughness;
  93097. if (properties) {
  93098. if (properties.baseColorFactor) {
  93099. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  93100. babylonMaterial.alpha = properties.baseColorFactor[3];
  93101. }
  93102. else {
  93103. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93104. }
  93105. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  93106. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  93107. if (properties.baseColorTexture) {
  93108. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  93109. babylonMaterial.albedoTexture = texture;
  93110. }));
  93111. }
  93112. if (properties.metallicRoughnessTexture) {
  93113. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  93114. babylonMaterial.metallicTexture = texture;
  93115. }));
  93116. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  93117. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  93118. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  93119. }
  93120. }
  93121. this._loadMaterialAlphaProperties(context, material);
  93122. return Promise.all(promises).then(function () { });
  93123. };
  93124. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93125. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  93126. if (promise) {
  93127. return promise;
  93128. }
  93129. material._babylonMeshes = material._babylonMeshes || [];
  93130. material._babylonMeshes.push(babylonMesh);
  93131. if (material._loaded) {
  93132. babylonMesh.material = material._babylonMaterial;
  93133. return material._loaded;
  93134. }
  93135. var promises = new Array();
  93136. var babylonMaterial = this._createMaterial(material);
  93137. material._babylonMaterial = babylonMaterial;
  93138. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  93139. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  93140. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93141. babylonMesh.material = babylonMaterial;
  93142. return (material._loaded = Promise.all(promises).then(function () { }));
  93143. };
  93144. GLTFLoader.prototype._createMaterial = function (material) {
  93145. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  93146. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  93147. return babylonMaterial;
  93148. };
  93149. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  93150. var promises = new Array();
  93151. var babylonMaterial = material._babylonMaterial;
  93152. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  93153. if (material.doubleSided) {
  93154. babylonMaterial.backFaceCulling = false;
  93155. babylonMaterial.twoSidedLighting = true;
  93156. }
  93157. if (material.normalTexture) {
  93158. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  93159. babylonMaterial.bumpTexture = texture;
  93160. }));
  93161. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  93162. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  93163. if (material.normalTexture.scale != undefined) {
  93164. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  93165. }
  93166. }
  93167. if (material.occlusionTexture) {
  93168. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  93169. babylonMaterial.ambientTexture = texture;
  93170. }));
  93171. babylonMaterial.useAmbientInGrayScale = true;
  93172. if (material.occlusionTexture.strength != undefined) {
  93173. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  93174. }
  93175. }
  93176. if (material.emissiveTexture) {
  93177. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  93178. babylonMaterial.emissiveTexture = texture;
  93179. }));
  93180. }
  93181. return Promise.all(promises).then(function () { });
  93182. };
  93183. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  93184. var babylonMaterial = material._babylonMaterial;
  93185. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  93186. switch (alphaMode) {
  93187. case "OPAQUE" /* OPAQUE */: {
  93188. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  93189. break;
  93190. }
  93191. case "MASK" /* MASK */: {
  93192. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  93193. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  93194. if (babylonMaterial.alpha) {
  93195. if (babylonMaterial.alpha === 0) {
  93196. babylonMaterial.alphaCutOff = 1;
  93197. }
  93198. else {
  93199. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  93200. }
  93201. babylonMaterial.alpha = 1;
  93202. }
  93203. if (babylonMaterial.albedoTexture) {
  93204. babylonMaterial.albedoTexture.hasAlpha = true;
  93205. }
  93206. break;
  93207. }
  93208. case "BLEND" /* BLEND */: {
  93209. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  93210. if (babylonMaterial.albedoTexture) {
  93211. babylonMaterial.albedoTexture.hasAlpha = true;
  93212. babylonMaterial.useAlphaFromAlbedoTexture = true;
  93213. }
  93214. break;
  93215. }
  93216. default: {
  93217. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  93218. }
  93219. }
  93220. };
  93221. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  93222. var _this = this;
  93223. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  93224. context = "#/textures/" + textureInfo.index;
  93225. var promises = new Array();
  93226. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  93227. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  93228. var deferred = new BABYLON.Deferred();
  93229. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  93230. if (!_this._disposed) {
  93231. deferred.resolve();
  93232. }
  93233. }, function (message, exception) {
  93234. if (!_this._disposed) {
  93235. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  93236. }
  93237. });
  93238. promises.push(deferred.promise);
  93239. babylonTexture.name = texture.name || "texture" + texture._index;
  93240. babylonTexture.wrapU = samplerData.wrapU;
  93241. babylonTexture.wrapV = samplerData.wrapV;
  93242. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  93243. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  93244. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  93245. babylonTexture.updateURL(objectURL);
  93246. }));
  93247. assign(babylonTexture);
  93248. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  93249. return Promise.all(promises).then(function () { });
  93250. };
  93251. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  93252. if (!sampler._data) {
  93253. sampler._data = {
  93254. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  93255. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  93256. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  93257. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  93258. };
  93259. }
  93260. ;
  93261. return sampler._data;
  93262. };
  93263. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  93264. if (image._objectURL) {
  93265. return image._objectURL;
  93266. }
  93267. var promise;
  93268. if (image.uri) {
  93269. promise = this._loadUriAsync(context, image.uri);
  93270. }
  93271. else {
  93272. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  93273. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  93274. }
  93275. image._objectURL = promise.then(function (data) {
  93276. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  93277. });
  93278. return image._objectURL;
  93279. };
  93280. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  93281. var _this = this;
  93282. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  93283. if (promise) {
  93284. return promise;
  93285. }
  93286. if (!GLTFLoader._ValidateUri(uri)) {
  93287. throw new Error(context + ": Uri '" + uri + "' is invalid");
  93288. }
  93289. if (BABYLON.Tools.IsBase64(uri)) {
  93290. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  93291. }
  93292. return new Promise(function (resolve, reject) {
  93293. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  93294. if (!_this._disposed) {
  93295. resolve(new Uint8Array(data));
  93296. }
  93297. }, function (event) {
  93298. if (!_this._disposed) {
  93299. try {
  93300. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  93301. request._lengthComputable = event.lengthComputable;
  93302. request._loaded = event.loaded;
  93303. request._total = event.total;
  93304. _this._onProgress();
  93305. }
  93306. }
  93307. catch (e) {
  93308. reject(e);
  93309. }
  93310. }
  93311. }, _this._babylonScene.database, true, function (request, exception) {
  93312. if (!_this._disposed) {
  93313. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  93314. }
  93315. });
  93316. _this._requests.push(request);
  93317. });
  93318. };
  93319. GLTFLoader.prototype._onProgress = function () {
  93320. if (!this._progressCallback) {
  93321. return;
  93322. }
  93323. var lengthComputable = true;
  93324. var loaded = 0;
  93325. var total = 0;
  93326. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93327. var request = _a[_i];
  93328. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  93329. return;
  93330. }
  93331. lengthComputable = lengthComputable && request._lengthComputable;
  93332. loaded += request._loaded;
  93333. total += request._total;
  93334. }
  93335. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  93336. };
  93337. GLTFLoader._GetProperty = function (context, array, index) {
  93338. if (!array || index == undefined || !array[index]) {
  93339. throw new Error(context + ": Failed to find index " + index);
  93340. }
  93341. return array[index];
  93342. };
  93343. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  93344. // Set defaults if undefined
  93345. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  93346. switch (mode) {
  93347. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93348. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93349. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93350. default:
  93351. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  93352. return BABYLON.Texture.WRAP_ADDRESSMODE;
  93353. }
  93354. };
  93355. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  93356. // Set defaults if undefined
  93357. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  93358. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  93359. if (magFilter === 9729 /* LINEAR */) {
  93360. switch (minFilter) {
  93361. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  93362. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  93363. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  93364. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  93365. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  93366. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93367. default:
  93368. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93369. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  93370. }
  93371. }
  93372. else {
  93373. if (magFilter !== 9728 /* NEAREST */) {
  93374. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  93375. }
  93376. switch (minFilter) {
  93377. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  93378. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  93379. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93380. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  93381. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  93382. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  93383. default:
  93384. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  93385. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  93386. }
  93387. }
  93388. };
  93389. GLTFLoader._GetNumComponents = function (context, type) {
  93390. switch (type) {
  93391. case "SCALAR": return 1;
  93392. case "VEC2": return 2;
  93393. case "VEC3": return 3;
  93394. case "VEC4": return 4;
  93395. case "MAT2": return 4;
  93396. case "MAT3": return 9;
  93397. case "MAT4": return 16;
  93398. }
  93399. throw new Error(context + ": Invalid type " + type);
  93400. };
  93401. GLTFLoader._ValidateUri = function (uri) {
  93402. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  93403. };
  93404. GLTFLoader.prototype._compileMaterialsAsync = function () {
  93405. var promises = new Array();
  93406. if (this._gltf.materials) {
  93407. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  93408. var material = _a[_i];
  93409. var babylonMaterial = material._babylonMaterial;
  93410. var babylonMeshes = material._babylonMeshes;
  93411. if (babylonMaterial && babylonMeshes) {
  93412. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  93413. var babylonMesh = babylonMeshes_1[_b];
  93414. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  93415. if (this.useClipPlane) {
  93416. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  93417. }
  93418. }
  93419. }
  93420. }
  93421. }
  93422. return Promise.all(promises).then(function () { });
  93423. };
  93424. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  93425. var promises = new Array();
  93426. var lights = this._babylonScene.lights;
  93427. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  93428. var light = lights_1[_i];
  93429. var generator = light.getShadowGenerator();
  93430. if (generator) {
  93431. promises.push(generator.forceCompilationAsync());
  93432. }
  93433. }
  93434. return Promise.all(promises).then(function () { });
  93435. };
  93436. GLTFLoader.prototype._clear = function () {
  93437. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  93438. var request = _a[_i];
  93439. request.abort();
  93440. }
  93441. this._requests.length = 0;
  93442. if (this._gltf && this._gltf.images) {
  93443. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  93444. var image = _c[_b];
  93445. if (image._objectURL) {
  93446. image._objectURL.then(function (value) {
  93447. URL.revokeObjectURL(value);
  93448. });
  93449. image._objectURL = undefined;
  93450. }
  93451. }
  93452. }
  93453. delete this._gltf;
  93454. delete this._babylonScene;
  93455. this._completePromises.length = 0;
  93456. for (var name_3 in this._extensions) {
  93457. this._extensions[name_3].dispose();
  93458. }
  93459. this._extensions = {};
  93460. delete this._rootBabylonMesh;
  93461. delete this._progressCallback;
  93462. this.onMeshLoadedObservable.clear();
  93463. this.onTextureLoadedObservable.clear();
  93464. this.onMaterialLoadedObservable.clear();
  93465. };
  93466. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  93467. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  93468. var name_4 = _a[_i];
  93469. var extension = this._extensions[name_4];
  93470. if (extension.enabled) {
  93471. var promise = actionAsync(extension);
  93472. if (promise) {
  93473. return promise;
  93474. }
  93475. }
  93476. }
  93477. return null;
  93478. };
  93479. GLTFLoader._Names = new Array();
  93480. GLTFLoader._Factories = {};
  93481. return GLTFLoader;
  93482. }());
  93483. GLTF2.GLTFLoader = GLTFLoader;
  93484. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  93485. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93486. })(BABYLON || (BABYLON = {}));
  93487. //# sourceMappingURL=babylon.glTFLoader.js.map
  93488. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93489. var BABYLON;
  93490. (function (BABYLON) {
  93491. var GLTF2;
  93492. (function (GLTF2) {
  93493. var GLTFLoaderExtension = /** @class */ (function () {
  93494. function GLTFLoaderExtension(loader) {
  93495. this.enabled = true;
  93496. this._loader = loader;
  93497. }
  93498. GLTFLoaderExtension.prototype.dispose = function () {
  93499. delete this._loader;
  93500. };
  93501. // #region Overridable Methods
  93502. /** Override this method to modify the default behavior for loading scenes. */
  93503. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  93504. /** Override this method to modify the default behavior for loading nodes. */
  93505. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  93506. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  93507. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  93508. /** Override this method to modify the default behavior for loading materials. */
  93509. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  93510. /** Override this method to modify the default behavior for loading uris. */
  93511. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  93512. // #endregion
  93513. /** Helper method called by a loader extension to load an glTF extension. */
  93514. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  93515. if (!property.extensions) {
  93516. return null;
  93517. }
  93518. var extensions = property.extensions;
  93519. var extension = extensions[this.name];
  93520. if (!extension) {
  93521. return null;
  93522. }
  93523. // Clear out the extension before executing the action to avoid recursing into the same property.
  93524. delete extensions[this.name];
  93525. try {
  93526. return actionAsync(context + "/extensions/" + this.name, extension);
  93527. }
  93528. finally {
  93529. // Restore the extension after executing the action.
  93530. extensions[this.name] = extension;
  93531. }
  93532. };
  93533. /** Helper method called by the loader to allow extensions to override loading scenes. */
  93534. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  93535. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  93536. };
  93537. /** Helper method called by the loader to allow extensions to override loading nodes. */
  93538. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  93539. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  93540. };
  93541. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  93542. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  93543. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  93544. };
  93545. /** Helper method called by the loader to allow extensions to override loading materials. */
  93546. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  93547. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  93548. };
  93549. /** Helper method called by the loader to allow extensions to override loading uris. */
  93550. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  93551. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  93552. };
  93553. return GLTFLoaderExtension;
  93554. }());
  93555. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  93556. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93557. })(BABYLON || (BABYLON = {}));
  93558. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93559. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93560. var BABYLON;
  93561. (function (BABYLON) {
  93562. var GLTF2;
  93563. (function (GLTF2) {
  93564. var Extensions;
  93565. (function (Extensions) {
  93566. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  93567. var NAME = "MSFT_lod";
  93568. var MSFT_lod = /** @class */ (function (_super) {
  93569. __extends(MSFT_lod, _super);
  93570. function MSFT_lod() {
  93571. var _this = _super !== null && _super.apply(this, arguments) || this;
  93572. _this.name = NAME;
  93573. /**
  93574. * Maximum number of LODs to load, starting from the lowest LOD.
  93575. */
  93576. _this.maxLODsToLoad = Number.MAX_VALUE;
  93577. _this._loadingNodeLOD = null;
  93578. _this._loadNodeSignals = {};
  93579. _this._loadingMaterialLOD = null;
  93580. _this._loadMaterialSignals = {};
  93581. return _this;
  93582. }
  93583. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  93584. var _this = this;
  93585. return this._loadExtensionAsync(context, node, function (context, extension) {
  93586. var firstPromise;
  93587. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  93588. var _loop_1 = function (indexLOD) {
  93589. var nodeLOD = nodeLODs[indexLOD];
  93590. if (indexLOD !== 0) {
  93591. _this._loadingNodeLOD = nodeLOD;
  93592. if (!_this._loadNodeSignals[nodeLOD._index]) {
  93593. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  93594. }
  93595. }
  93596. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  93597. if (indexLOD !== 0) {
  93598. var previousNodeLOD = nodeLODs[indexLOD - 1];
  93599. previousNodeLOD._babylonMesh.setEnabled(false);
  93600. }
  93601. if (indexLOD !== nodeLODs.length - 1) {
  93602. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  93603. if (_this._loadNodeSignals[nodeIndex]) {
  93604. _this._loadNodeSignals[nodeIndex].resolve();
  93605. delete _this._loadNodeSignals[nodeIndex];
  93606. }
  93607. }
  93608. });
  93609. if (indexLOD === 0) {
  93610. firstPromise = promise;
  93611. }
  93612. else {
  93613. _this._loader._completePromises.push(promise);
  93614. _this._loadingNodeLOD = null;
  93615. }
  93616. };
  93617. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  93618. _loop_1(indexLOD);
  93619. }
  93620. return firstPromise;
  93621. });
  93622. };
  93623. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93624. var _this = this;
  93625. // Don't load material LODs if already loading a node LOD.
  93626. if (this._loadingNodeLOD) {
  93627. return null;
  93628. }
  93629. return this._loadExtensionAsync(context, material, function (context, extension) {
  93630. var firstPromise;
  93631. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  93632. var _loop_2 = function (indexLOD) {
  93633. var materialLOD = materialLODs[indexLOD];
  93634. if (indexLOD !== 0) {
  93635. _this._loadingMaterialLOD = materialLOD;
  93636. if (!_this._loadMaterialSignals[materialLOD._index]) {
  93637. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  93638. }
  93639. }
  93640. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  93641. if (indexLOD !== materialLODs.length - 1) {
  93642. var materialIndex = materialLODs[indexLOD + 1]._index;
  93643. if (_this._loadMaterialSignals[materialIndex]) {
  93644. _this._loadMaterialSignals[materialIndex].resolve();
  93645. delete _this._loadMaterialSignals[materialIndex];
  93646. }
  93647. }
  93648. });
  93649. if (indexLOD === 0) {
  93650. firstPromise = promise;
  93651. }
  93652. else {
  93653. _this._loader._completePromises.push(promise);
  93654. _this._loadingMaterialLOD = null;
  93655. }
  93656. };
  93657. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  93658. _loop_2(indexLOD);
  93659. }
  93660. return firstPromise;
  93661. });
  93662. };
  93663. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  93664. var _this = this;
  93665. // Defer the loading of uris if loading a material or node LOD.
  93666. if (this._loadingMaterialLOD) {
  93667. var index = this._loadingMaterialLOD._index;
  93668. return this._loadMaterialSignals[index].promise.then(function () {
  93669. return _this._loader._loadUriAsync(context, uri);
  93670. });
  93671. }
  93672. else if (this._loadingNodeLOD) {
  93673. var index = this._loadingNodeLOD._index;
  93674. return this._loadNodeSignals[index].promise.then(function () {
  93675. return _this._loader._loadUriAsync(context, uri);
  93676. });
  93677. }
  93678. return null;
  93679. };
  93680. /**
  93681. * Gets an array of LOD properties from lowest to highest.
  93682. */
  93683. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  93684. if (this.maxLODsToLoad <= 0) {
  93685. throw new Error("maxLODsToLoad must be greater than zero");
  93686. }
  93687. var properties = new Array();
  93688. for (var i = ids.length - 1; i >= 0; i--) {
  93689. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  93690. if (properties.length === this.maxLODsToLoad) {
  93691. return properties;
  93692. }
  93693. }
  93694. properties.push(property);
  93695. return properties;
  93696. };
  93697. return MSFT_lod;
  93698. }(GLTF2.GLTFLoaderExtension));
  93699. Extensions.MSFT_lod = MSFT_lod;
  93700. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  93701. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93702. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93703. })(BABYLON || (BABYLON = {}));
  93704. //# sourceMappingURL=MSFT_lod.js.map
  93705. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93706. var BABYLON;
  93707. (function (BABYLON) {
  93708. var GLTF2;
  93709. (function (GLTF2) {
  93710. var Extensions;
  93711. (function (Extensions) {
  93712. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  93713. var NAME = "KHR_draco_mesh_compression";
  93714. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  93715. __extends(KHR_draco_mesh_compression, _super);
  93716. function KHR_draco_mesh_compression(loader) {
  93717. var _this = _super.call(this, loader) || this;
  93718. _this.name = NAME;
  93719. _this._dracoCompression = null;
  93720. // Disable extension if decoder is not available.
  93721. if (!BABYLON.DracoCompression.DecoderUrl) {
  93722. _this.enabled = false;
  93723. }
  93724. return _this;
  93725. }
  93726. KHR_draco_mesh_compression.prototype.dispose = function () {
  93727. if (this._dracoCompression) {
  93728. this._dracoCompression.dispose();
  93729. }
  93730. _super.prototype.dispose.call(this);
  93731. };
  93732. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  93733. var _this = this;
  93734. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  93735. if (primitive.mode != undefined) {
  93736. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  93737. primitive.mode !== 4 /* TRIANGLES */) {
  93738. throw new Error(context + ": Unsupported mode " + primitive.mode);
  93739. }
  93740. // TODO: handle triangle strips
  93741. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  93742. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  93743. }
  93744. }
  93745. var attributes = {};
  93746. var loadAttribute = function (name, kind) {
  93747. var uniqueId = extension.attributes[name];
  93748. if (uniqueId == undefined) {
  93749. return;
  93750. }
  93751. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  93752. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  93753. babylonMesh._delayInfo.push(kind);
  93754. }
  93755. attributes[kind] = uniqueId;
  93756. };
  93757. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  93758. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  93759. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  93760. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  93761. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  93762. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  93763. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  93764. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  93765. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  93766. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  93767. try {
  93768. if (!_this._dracoCompression) {
  93769. _this._dracoCompression = new BABYLON.DracoCompression();
  93770. }
  93771. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  93772. }
  93773. catch (e) {
  93774. throw new Error(context + ": " + e.message);
  93775. }
  93776. });
  93777. });
  93778. };
  93779. return KHR_draco_mesh_compression;
  93780. }(GLTF2.GLTFLoaderExtension));
  93781. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  93782. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  93783. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93784. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93785. })(BABYLON || (BABYLON = {}));
  93786. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  93787. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93788. var BABYLON;
  93789. (function (BABYLON) {
  93790. var GLTF2;
  93791. (function (GLTF2) {
  93792. var Extensions;
  93793. (function (Extensions) {
  93794. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  93795. var NAME = "KHR_materials_pbrSpecularGlossiness";
  93796. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  93797. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  93798. function KHR_materials_pbrSpecularGlossiness() {
  93799. var _this = _super !== null && _super.apply(this, arguments) || this;
  93800. _this.name = NAME;
  93801. return _this;
  93802. }
  93803. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  93804. var _this = this;
  93805. return this._loadExtensionAsync(context, material, function (context, extension) {
  93806. material._babylonMeshes = material._babylonMeshes || [];
  93807. material._babylonMeshes.push(babylonMesh);
  93808. if (material._loaded) {
  93809. babylonMesh.material = material._babylonMaterial;
  93810. return material._loaded;
  93811. }
  93812. var promises = new Array();
  93813. var babylonMaterial = _this._loader._createMaterial(material);
  93814. material._babylonMaterial = babylonMaterial;
  93815. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  93816. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  93817. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  93818. babylonMesh.material = babylonMaterial;
  93819. return (material._loaded = Promise.all(promises).then(function () { }));
  93820. });
  93821. };
  93822. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  93823. var promises = new Array();
  93824. var babylonMaterial = material._babylonMaterial;
  93825. if (properties.diffuseFactor) {
  93826. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  93827. babylonMaterial.alpha = properties.diffuseFactor[3];
  93828. }
  93829. else {
  93830. babylonMaterial.albedoColor = BABYLON.Color3.White();
  93831. }
  93832. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  93833. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  93834. if (properties.diffuseTexture) {
  93835. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  93836. babylonMaterial.albedoTexture = texture;
  93837. }));
  93838. }
  93839. if (properties.specularGlossinessTexture) {
  93840. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  93841. babylonMaterial.reflectivityTexture = texture;
  93842. }));
  93843. babylonMaterial.reflectivityTexture.hasAlpha = true;
  93844. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  93845. }
  93846. loader._loadMaterialAlphaProperties(context, material);
  93847. return Promise.all(promises).then(function () { });
  93848. };
  93849. return KHR_materials_pbrSpecularGlossiness;
  93850. }(GLTF2.GLTFLoaderExtension));
  93851. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  93852. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  93853. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93854. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93855. })(BABYLON || (BABYLON = {}));
  93856. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  93857. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  93858. var BABYLON;
  93859. (function (BABYLON) {
  93860. var GLTF2;
  93861. (function (GLTF2) {
  93862. var Extensions;
  93863. (function (Extensions) {
  93864. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  93865. var NAME = "KHR_lights";
  93866. var LightType;
  93867. (function (LightType) {
  93868. LightType["AMBIENT"] = "ambient";
  93869. LightType["DIRECTIONAL"] = "directional";
  93870. LightType["POINT"] = "point";
  93871. LightType["SPOT"] = "spot";
  93872. })(LightType || (LightType = {}));
  93873. var KHR_lights = /** @class */ (function (_super) {
  93874. __extends(KHR_lights, _super);
  93875. function KHR_lights() {
  93876. var _this = _super !== null && _super.apply(this, arguments) || this;
  93877. _this.name = NAME;
  93878. return _this;
  93879. }
  93880. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  93881. var _this = this;
  93882. return this._loadExtensionAsync(context, scene, function (context, extension) {
  93883. var promise = _this._loader._loadSceneAsync(context, scene);
  93884. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93885. if (light.type !== LightType.AMBIENT) {
  93886. throw new Error(context + ": Only ambient lights are allowed on a scene");
  93887. }
  93888. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  93889. return promise;
  93890. });
  93891. };
  93892. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  93893. var _this = this;
  93894. return this._loadExtensionAsync(context, node, function (context, extension) {
  93895. var promise = _this._loader._loadNodeAsync(context, node);
  93896. var babylonLight;
  93897. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  93898. var name = node._babylonMesh.name;
  93899. switch (light.type) {
  93900. case LightType.AMBIENT: {
  93901. throw new Error(context + ": Ambient lights are not allowed on a node");
  93902. }
  93903. case LightType.DIRECTIONAL: {
  93904. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  93905. break;
  93906. }
  93907. case LightType.POINT: {
  93908. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  93909. break;
  93910. }
  93911. case LightType.SPOT: {
  93912. var spotLight = light;
  93913. // TODO: support inner and outer cone angles
  93914. //const innerConeAngle = spotLight.innerConeAngle || 0;
  93915. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  93916. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  93917. break;
  93918. }
  93919. default: {
  93920. throw new Error(context + ": Invalid light type " + light.type);
  93921. }
  93922. }
  93923. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  93924. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  93925. babylonLight.parent = node._babylonMesh;
  93926. return promise;
  93927. });
  93928. };
  93929. Object.defineProperty(KHR_lights.prototype, "_lights", {
  93930. get: function () {
  93931. var extensions = this._loader._gltf.extensions;
  93932. if (!extensions || !extensions[this.name]) {
  93933. throw new Error("#/extensions: " + this.name + " not found");
  93934. }
  93935. var extension = extensions[this.name];
  93936. return extension.lights;
  93937. },
  93938. enumerable: true,
  93939. configurable: true
  93940. });
  93941. return KHR_lights;
  93942. }(GLTF2.GLTFLoaderExtension));
  93943. Extensions.KHR_lights = KHR_lights;
  93944. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  93945. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  93946. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93947. })(BABYLON || (BABYLON = {}));
  93948. //# sourceMappingURL=KHR_lights.js.map
  93949. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  93950. globalObject["BABYLON"] = BABYLON;
  93951. 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 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;
  93952. 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,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 };